Browse Source

Merge branch 'master' into ka-GE_translation-init

pull/11897/head
David Kadaria 11 months ago
committed by GitHub
parent
commit
1667f12ad0
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 6
      .github/actions/people/app/main.py
  2. 34
      .github/labeler.yml
  3. 18
      .github/workflows/add-to-project.yml
  4. 31
      .github/workflows/labeler.yml
  5. 3
      .github/workflows/latest-changes.yml
  6. 2
      .github/workflows/publish.yml
  7. 2
      .github/workflows/test.yml
  8. 2
      .gitignore
  9. 6
      .pre-commit-config.yaml
  10. 6
      README.md
  11. 185
      docs/az/docs/fastapi-people.md
  12. 2
      docs/az/docs/index.md
  13. 2
      docs/bn/docs/index.md
  14. 1
      docs/de/docs/advanced/middleware.md
  15. 7
      docs/de/docs/deployment/docker.md
  16. 42
      docs/de/docs/external-links.md
  17. 176
      docs/de/docs/fastapi-people.md
  18. 2
      docs/de/docs/features.md
  19. 2
      docs/de/docs/index.md
  20. 5
      docs/de/docs/newsletter.md
  21. 24
      docs/de/docs/reference/apirouter.md
  22. 11
      docs/de/docs/reference/background.md
  23. 29
      docs/de/docs/reference/dependencies.md
  24. 3
      docs/de/docs/reference/encoders.md
  25. 20
      docs/de/docs/reference/exceptions.md
  26. 31
      docs/de/docs/reference/fastapi.md
  27. 11
      docs/de/docs/reference/httpconnection.md
  28. 11
      docs/de/docs/reference/index.md
  29. 45
      docs/de/docs/reference/middleware.md
  30. 11
      docs/de/docs/reference/openapi/docs.md
  31. 5
      docs/de/docs/reference/openapi/index.md
  32. 5
      docs/de/docs/reference/openapi/models.md
  33. 35
      docs/de/docs/reference/parameters.md
  34. 17
      docs/de/docs/reference/request.md
  35. 13
      docs/de/docs/reference/response.md
  36. 164
      docs/de/docs/reference/responses.md
  37. 73
      docs/de/docs/reference/security/index.md
  38. 13
      docs/de/docs/reference/staticfiles.md
  39. 36
      docs/de/docs/reference/status.md
  40. 13
      docs/de/docs/reference/templating.md
  41. 13
      docs/de/docs/reference/testclient.md
  42. 22
      docs/de/docs/reference/uploadfile.md
  43. 67
      docs/de/docs/reference/websockets.md
  44. 2
      docs/de/docs/tutorial/response-model.md
  45. 1
      docs/em/docs/advanced/middleware.md
  46. 7
      docs/em/docs/deployment/docker.md
  47. 38
      docs/em/docs/external-links.md
  48. 183
      docs/em/docs/fastapi-people.md
  49. 2
      docs/em/docs/index.md
  50. 2
      docs/em/docs/tutorial/response-model.md
  51. 12
      docs/en/data/members.yml
  52. 6
      docs/en/docs/advanced/additional-responses.md
  53. 2
      docs/en/docs/advanced/behind-a-proxy.md
  54. 8
      docs/en/docs/advanced/custom-response.md
  55. 2
      docs/en/docs/advanced/middleware.md
  56. 2
      docs/en/docs/advanced/openapi-callbacks.md
  57. 4
      docs/en/docs/advanced/response-directly.md
  58. 4
      docs/en/docs/advanced/security/oauth2-scopes.md
  59. 130
      docs/en/docs/advanced/settings.md
  60. 4
      docs/en/docs/advanced/sub-applications.md
  61. 2
      docs/en/docs/advanced/templates.md
  62. 2
      docs/en/docs/advanced/websockets.md
  63. 2
      docs/en/docs/alternatives.md
  64. 4
      docs/en/docs/async.md
  65. 158
      docs/en/docs/contributing.md
  66. 8
      docs/en/docs/deployment/concepts.md
  67. 265
      docs/en/docs/deployment/docker.md
  68. 89
      docs/en/docs/deployment/manually.md
  69. 163
      docs/en/docs/deployment/server-workers.md
  70. 2
      docs/en/docs/deployment/versions.md
  71. 300
      docs/en/docs/environment-variables.md
  72. 2
      docs/en/docs/features.md
  73. 2
      docs/en/docs/help-fastapi.md
  74. 6
      docs/en/docs/index.md
  75. 2
      docs/en/docs/management-tasks.md
  76. 1
      docs/en/docs/project-generation.md
  77. 4
      docs/en/docs/python-types.md
  78. 91
      docs/en/docs/release-notes.md
  79. 2
      docs/en/docs/tutorial/background-tasks.md
  80. 8
      docs/en/docs/tutorial/bigger-applications.md
  81. 12
      docs/en/docs/tutorial/body-multiple-params.md
  82. 2
      docs/en/docs/tutorial/body-nested-models.md
  83. 2
      docs/en/docs/tutorial/body-updates.md
  84. 8
      docs/en/docs/tutorial/body.md
  85. 2
      docs/en/docs/tutorial/cookie-params.md
  86. 8
      docs/en/docs/tutorial/cors.md
  87. 2
      docs/en/docs/tutorial/dependencies/classes-as-dependencies.md
  88. 2
      docs/en/docs/tutorial/dependencies/dependencies-with-yield.md
  89. 4
      docs/en/docs/tutorial/extra-data-types.md
  90. 6
      docs/en/docs/tutorial/extra-models.md
  91. 4
      docs/en/docs/tutorial/handling-errors.md
  92. 2
      docs/en/docs/tutorial/header-params.md
  93. 10
      docs/en/docs/tutorial/index.md
  94. 2
      docs/en/docs/tutorial/middleware.md
  95. 20
      docs/en/docs/tutorial/query-params-str-validations.md
  96. 8
      docs/en/docs/tutorial/request-files.md
  97. 6
      docs/en/docs/tutorial/request-forms-and-files.md
  98. 6
      docs/en/docs/tutorial/request-forms.md
  99. 25
      docs/en/docs/tutorial/response-model.md
  100. 4
      docs/en/docs/tutorial/schema-extra-example.md

6
.github/actions/people/app/main.py

@ -515,9 +515,9 @@ def get_individual_sponsors(settings: Settings):
tiers: DefaultDict[float, Dict[str, SponsorEntity]] = defaultdict(dict)
for node in nodes:
tiers[node.tier.monthlyPriceInDollars][
node.sponsorEntity.login
] = node.sponsorEntity
tiers[node.tier.monthlyPriceInDollars][node.sponsorEntity.login] = (
node.sponsorEntity
)
return tiers

34
.github/labeler.yml

@ -0,0 +1,34 @@
docs:
- all:
- changed-files:
- any-glob-to-any-file:
- docs/en/docs/**
- docs_src/**
- all-globs-to-all-files:
- '!fastapi/**'
- '!pyproject.toml'
lang-all:
- all:
- changed-files:
- any-glob-to-any-file:
- docs/*/docs/**
- all-globs-to-all-files:
- '!docs/en/docs/**'
- '!fastapi/**'
- '!pyproject.toml'
internal:
- all:
- changed-files:
- any-glob-to-any-file:
- .github/**
- scripts/**
- .gitignore
- .pre-commit-config.yaml
- pdm_build.py
- requirements*.txt
- all-globs-to-all-files:
- '!docs/*/docs/**'
- '!fastapi/**'
- '!pyproject.toml'

18
.github/workflows/add-to-project.yml

@ -0,0 +1,18 @@
name: Add to Project
on:
pull_request_target:
issues:
types:
- opened
- reopened
jobs:
add-to-project:
name: Add to project
runs-on: ubuntu-latest
steps:
- uses: actions/add-to-project@v1.0.2
with:
project-url: https://github.com/orgs/fastapi/projects/2
github-token: ${{ secrets.PROJECTS_TOKEN }}

31
.github/workflows/labeler.yml

@ -0,0 +1,31 @@
name: Labels
on:
pull_request_target:
types:
- opened
- synchronize
- reopened
# For label-checker
- labeled
- unlabeled
jobs:
labeler:
permissions:
contents: read
pull-requests: write
runs-on: ubuntu-latest
steps:
- uses: actions/labeler@v5
# Run this after labeler applied labels
check-labels:
needs:
- labeler
permissions:
pull-requests: read
runs-on: ubuntu-latest
steps:
- uses: docker://agilepathway/pull-request-label-checker:latest
with:
one_of: breaking,security,feature,bug,refactor,upgrade,docs,lang-all,internal
repo_token: ${{ secrets.GITHUB_TOKEN }}

3
.github/workflows/latest-changes.yml

@ -34,8 +34,7 @@ jobs:
if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled == 'true' }}
with:
limit-access-to-actor: true
- uses: docker://tiangolo/latest-changes:0.3.0
# - uses: tiangolo/latest-changes@main
- uses: tiangolo/latest-changes@0.3.1
with:
token: ${{ secrets.GITHUB_TOKEN }}
latest_changes_file: docs/en/docs/release-notes.md

2
.github/workflows/publish.yml

@ -35,7 +35,7 @@ jobs:
TIANGOLO_BUILD_PACKAGE: ${{ matrix.package }}
run: python -m build
- name: Publish
uses: pypa/gh-action-pypi-publish@v1.8.14
uses: pypa/gh-action-pypi-publish@v1.9.0
- name: Dump GitHub context
env:
GITHUB_CONTEXT: ${{ toJson(github) }}

2
.github/workflows/test.yml

@ -117,7 +117,7 @@ jobs:
- run: ls -la coverage
- run: coverage combine coverage
- run: coverage report
- run: coverage html --show-contexts --title "Coverage for ${{ github.sha }}"
- run: coverage html --title "Coverage for ${{ github.sha }}"
- name: Store coverage HTML
uses: actions/upload-artifact@v4
with:

2
.gitignore

@ -7,7 +7,7 @@ __pycache__
htmlcov
dist
site
.coverage
.coverage*
coverage.xml
.netlify
test.db

6
.pre-commit-config.yaml

@ -4,7 +4,7 @@ default_language_version:
python: python3.10
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
rev: v4.6.0
hooks:
- id: check-added-large-files
- id: check-toml
@ -13,8 +13,8 @@ repos:
- --unsafe
- id: end-of-file-fixer
- id: trailing-whitespace
- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: v0.2.0
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.6.2
hooks:
- id: ruff
args:

6
README.md

@ -132,6 +132,8 @@ FastAPI stands on the shoulders of giants:
## Installation
Create and activate a <a href="https://fastapi.tiangolo.com/virtual-environments/" class="external-link" target="_blank">virtual environment</a> and then install FastAPI:
<div class="termy">
```console
@ -392,7 +394,7 @@ Coming back to the previous code example, **FastAPI** will:
* Check if there is an optional query parameter named `q` (as in `http://127.0.0.1:8000/items/foo?q=somequery`) for `GET` requests.
* As the `q` parameter is declared with `= None`, it is optional.
* Without the `None` it would be required (as is the body in the case with `PUT`).
* For `PUT` requests to `/items/{item_id}`, Read the body as JSON:
* For `PUT` requests to `/items/{item_id}`, read the body as JSON:
* Check that it has a required attribute `name` that should be a `str`.
* Check that it has a required attribute `price` that has to be a `float`.
* Check that it has an optional attribute `is_offer`, that should be a `bool`, if present.
@ -462,7 +464,7 @@ When you install FastAPI with `pip install "fastapi[standard]"` it comes the `st
Used by Pydantic:
* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email_validator</code></a> - for email validation.
* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email-validator</code></a> - for email validation.
Used by Starlette:

185
docs/az/docs/fastapi-people.md

@ -1,185 +0,0 @@
---
hide:
- navigation
---
# FastAPI İnsanlar
FastAPI-ın bütün mənşəli insanları qəbul edən heyrətamiz icması var.
## Yaradıcı - İcraçı
Salam! 👋
Bu mənəm:
{% if people %}
<div class="user-list user-list-center">
{% for user in people.maintainers %}
<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Cavablar: {{ user.answers }}</div><div class="count">Pull Request-lər: {{ user.prs }}</div></div>
{% endfor %}
</div>
{% endif %}
Mən **FastAPI**-ın yaradıcısı və icraçısıyam. Əlavə məlumat almaq üçün [Yardım FastAPI - Yardım alın - Müəlliflə əlaqə qurun](help-fastapi.md#connect-with-the-author){.internal-link target=_blank} səhifəsinə baxa bilərsiniz.
...Burada isə sizə icmanı göstərmək istəyirəm.
---
**FastAPI** icmadan çoxlu dəstək alır və mən onların əməyini vurğulamaq istəyirəm.
Bu insanlar:
* [GitHub-da başqalarının suallarına kömək edirlər](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}.
* [Pull Request-lər yaradırlar](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}.
* Pull Request-ləri ([xüsusilə tərcümələr üçün vacib olan](contributing.md#translations){.internal-link target=_blank}.) nəzərdən keçirirlər.
Bu insanlara təşəkkür edirəm. 👏 🙇
## Keçən ayın ən fəal istifadəçiləri
Bu istifadəçilər keçən ay [GitHub-da başqalarının suallarına](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} ən çox kömək edənlərdir. ☕
{% if people %}
<div class="user-list user-list-center">
{% for user in people.last_month_experts[:10] %}
<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Cavablandırılmış suallar: {{ user.count }}</div></div>
{% endfor %}
</div>
{% endif %}
## Mütəxəssislər
Burada **FastAPI Mütəxəssisləri** var. 🤓
Bu istifadəçilər indiyə qədər [GitHub-da başqalarının suallarına](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} ən çox kömək edənlərdir.
Onlar bir çox insanlara kömək edərək mütəxəssis olduqlarını sübut ediblər. ✨
{% if people %}
<div class="user-list user-list-center">
{% for user in people.experts[:50] %}
<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Cavablandırılmış suallar: {{ user.count }}</div></div>
{% endfor %}
</div>
{% endif %}
## Ən yaxşı əməkdaşlar
Burada **Ən yaxşı əməkdaşlar** var. 👷
Bu istifadəçilərin ən çox *birləşdirilmiş* [Pull Request-ləri var](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}.
Onlar mənbə kodu, sənədləmə, tərcümələr və s. barədə əmək göstərmişlər. 📦
{% if people %}
<div class="user-list user-list-center">
{% for user in people.top_contributors[:50] %}
<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Pull Request-lər: {{ user.count }}</div></div>
{% endfor %}
</div>
{% endif %}
Bundan başqa bir neçə (yüzdən çox) əməkdaş var ki, onları <a href="https://github.com/fastapi/fastapi/graphs/contributors" class="external-link" target="_blank">FastAPI GitHub Əməkdaşlar səhifəsində</a> görə bilərsiniz. 👷
## Ən çox rəy verənlər
Bu istifadəçilər **ən çox rəy verənlər**dir.
### Tərcümələr üçün rəylər
Mən yalnız bir neçə dildə danışıram (və çox da yaxşı deyil 😅). Bu səbəbdən, rəy verənlər sənədlərin [**tərcümələrini təsdiqləmək üçün gücə malik olanlar**](contributing.md#translations){.internal-link target=_blank}dır. Onlar olmadan, bir çox dilə tərcümə olunmuş sənədlər olmazdı.
---
Başqalarının Pull Request-lərinə **Ən çox rəy verənlər** 🕵️ kodun, sənədlərin və xüsusilə də **tərcümələrin** keyfiyyətini təmin edirlər.
{% if people %}
<div class="user-list user-list-center">
{% for user in people.top_translations_reviewers[:50] %}
<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Rəylər: {{ user.count }}</div></div>
{% endfor %}
</div>
{% endif %}
## Sponsorlar
Bunlar **Sponsorlar**dır. 😎
Onlar mənim **FastAPI** (və digər) işlərimi əsasən <a href="https://github.com/sponsors/tiangolo" class="external-link" target="_blank">GitHub Sponsorlar</a> vasitəsilə dəstəkləyirlər.
{% if sponsors %}
{% if sponsors.gold %}
### Qızıl Sponsorlar
{% for sponsor in sponsors.gold -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor %}
{% endif %}
{% if sponsors.silver %}
### Gümüş Sponsorlar
{% for sponsor in sponsors.silver -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor %}
{% endif %}
{% if sponsors.bronze %}
### Bürünc Sponsorlar
{% for sponsor in sponsors.bronze -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor %}
{% endif %}
{% endif %}
### Fərdi Sponsorlar
{% if github_sponsors %}
{% for group in github_sponsors.sponsors %}
<div class="user-list user-list-center">
{% for user in group %}
{% if user.login not in sponsors_badge.logins %}
<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a></div>
{% endif %}
{% endfor %}
</div>
{% endfor %}
{% endif %}
## Məlumatlar haqqında - texniki detallar
Bu səhifənin əsas məqsədi, icmanın başqalarına kömək etmək üçün göstərdiyi əməyi vurğulamaqdır.
Xüsusilə də normalda daha az görünən və bir çox hallarda daha çətin olan, başqalarının suallarına kömək etmək və tərcümələrlə bağlı Pull Request-lərə rəy vermək kimi səy göstərmək.
Bu səhifənin məlumatları hər ay hesablanır və siz <a href="https://github.com/fastapi/fastapi/blob/master/.github/actions/people/app/main.py" class="external-link" target="_blank">buradan mənbə kodunu</a> oxuya bilərsiniz.
Burada sponsorların əməyini də vurğulamaq istəyirəm.
Mən həmçinin alqoritmi, bölmələri, eşikləri və s. yeniləmək hüququnu da qoruyuram (hər ehtimala qarşı 🤷).

2
docs/az/docs/index.md

@ -442,7 +442,7 @@ Müstəqil TechEmpower meyarları göstərir ki, Uvicorn üzərində işləyən
Pydantic tərəfindən istifadə olunanlar:
* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email_validator</code></a> - e-poçtun yoxlanılması üçün.
* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email-validator</code></a> - e-poçtun yoxlanılması üçün.
* <a href="https://docs.pydantic.dev/latest/usage/pydantic_settings/" target="_blank"><code>pydantic-settings</code></a> - parametrlərin idarə edilməsi üçün.
* <a href="https://docs.pydantic.dev/latest/usage/types/extra_types/extra_types/" target="_blank"><code>pydantic-extra-types</code></a> - Pydantic ilə istifadə edilə bilən əlavə tiplər üçün.

2
docs/bn/docs/index.md

@ -439,7 +439,7 @@ item: Item
Pydantic দ্বারা ব্যবহৃত:
- <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email_validator</code></a> - ইমেল যাচাইকরণের জন্য।
- <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email-validator</code></a> - ইমেল যাচাইকরণের জন্য।
স্টারলেট দ্বারা ব্যবহৃত:

1
docs/de/docs/advanced/middleware.md

@ -95,7 +95,6 @@ Es gibt viele andere ASGI-Middlewares.
Zum Beispiel:
* <a href="https://docs.sentry.io/platforms/python/guides/fastapi/" class="external-link" target="_blank">Sentry</a>
* <a href="https://github.com/encode/uvicorn/blob/master/uvicorn/middleware/proxy_headers.py" class="external-link" target="_blank">Uvicorns `ProxyHeadersMiddleware`</a>
* <a href="https://github.com/florimondmanca/msgpack-asgi" class="external-link" target="_blank">MessagePack</a>

7
docs/de/docs/deployment/docker.md

@ -205,8 +205,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"]
Die Option `--no-cache-dir` weist `pip` an, die heruntergeladenen Pakete nicht lokal zu speichern, da dies nur benötigt wird, sollte `pip` erneut ausgeführt werden, um dieselben Pakete zu installieren, aber das ist beim Arbeiten mit Containern nicht der Fall.
!!! note "Hinweis"
Das `--no-cache-dir` bezieht sich nur auf `pip`, es hat nichts mit Docker oder Containern zu tun.
/// note | Hinweis
Das `--no-cache-dir` bezieht sich nur auf `pip`, es hat nichts mit Docker oder Containern zu tun.
///
Die Option `--upgrade` weist `pip` an, die Packages zu aktualisieren, wenn sie bereits installiert sind.

42
docs/de/docs/external-links.md

@ -1,42 +0,0 @@
# Externe Links und Artikel
**FastAPI** hat eine großartige Community, die ständig wächst.
Es gibt viele Beiträge, Artikel, Tools und Projekte zum Thema **FastAPI**.
Hier ist eine unvollständige Liste einiger davon.
/// tip | "Tipp"
Wenn Sie einen Artikel, ein Projekt, ein Tool oder irgendetwas im Zusammenhang mit **FastAPI** haben, was hier noch nicht aufgeführt ist, erstellen Sie einen <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">Pull Request und fügen Sie es hinzu</a>.
///
/// note | "Hinweis Deutsche Übersetzung"
Die folgenden Überschriften und Links werden aus einer <a href="https://github.com/fastapi/fastapi/blob/master/docs/en/data/external_links.yml" class="external-link" target="_blank">anderen Datei</a> gelesen und sind daher nicht ins Deutsche übersetzt.
///
{% for section_name, section_content in external_links.items() %}
## {{ section_name }}
{% for lang_name, lang_content in section_content.items() %}
### {{ lang_name }}
{% for item in lang_content %}
* <a href="{{ item.link }}" class="external-link" target="_blank">{{ item.title }}</a> by <a href="{{ item.author_link }}" class="external-link" target="_blank">{{ item.author }}</a>.
{% endfor %}
{% endfor %}
{% endfor %}
## Projekte
Die neuesten GitHub-Projekte zum Thema `fastapi`:
<div class="github-topic-projects">
</div>

176
docs/de/docs/fastapi-people.md

@ -1,176 +0,0 @@
---
hide:
- navigation
---
# FastAPI Leute
FastAPI hat eine großartige Gemeinschaft, die Menschen mit unterschiedlichstem Hintergrund willkommen heißt.
## Erfinder - Betreuer
Hey! 👋
Das bin ich:
{% if people %}
<div class="user-list user-list-center">
{% for user in people.maintainers %}
<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Answers: {{ user.answers }}</div><div class="count">Pull Requests: {{ user.prs }}</div></div>
{% endfor %}
</div>
{% endif %}
Ich bin der Erfinder und Betreuer von **FastAPI**. Sie können mehr darüber in [FastAPI helfen – Hilfe erhalten – Mit dem Autor vernetzen](help-fastapi.md#mit-dem-autor-vernetzen){.internal-link target=_blank} erfahren.
... Aber hier möchte ich Ihnen die Gemeinschaft vorstellen.
---
**FastAPI** erhält eine Menge Unterstützung aus der Gemeinschaft. Und ich möchte ihre Beiträge hervorheben.
Das sind die Menschen, die:
* [Anderen bei Fragen auf GitHub helfen](help-fastapi.md#anderen-bei-fragen-auf-github-helfen){.internal-link target=_blank}.
* [<abbr title='Pull Request – „Zieh-Anfrage“: Geänderten Quellcode senden, mit dem Vorschlag, ihn mit dem aktuellen Quellcode zu verschmelzen'>Pull Requests</abbr> erstellen](help-fastapi.md#einen-pull-request-erstellen){.internal-link target=_blank}.
* Pull Requests überprüfen (Review), [besonders wichtig für Übersetzungen](contributing.md#ubersetzungen){.internal-link target=_blank}.
Eine Runde Applaus für sie. 👏 🙇
## Aktivste Benutzer im letzten Monat
Hier die Benutzer, die im letzten Monat am meisten [anderen mit Fragen auf Github](help-fastapi.md#anderen-bei-fragen-auf-github-helfen){.internal-link target=_blank} geholfen haben. ☕
{% if people %}
<div class="user-list user-list-center">
{% for user in people.last_month_active %}
<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Fragen beantwortet: {{ user.count }}</div></div>
{% endfor %}
</div>
{% endif %}
## Experten
Hier die **FastAPI-Experten**. 🤓
Das sind die Benutzer, die *insgesamt* [anderen am meisten mit Fragen auf GitHub geholfen haben](help-fastapi.md#anderen-bei-fragen-auf-github-helfen){.internal-link target=_blank}.
Sie haben bewiesen, dass sie Experten sind, weil sie vielen anderen geholfen haben. ✨
{% if people %}
<div class="user-list user-list-center">
{% for user in people.experts %}
<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Fragen beantwortet: {{ user.count }}</div></div>
{% endfor %}
</div>
{% endif %}
## Top-Mitwirkende
Hier sind die **Top-Mitwirkenden**. 👷
Diese Benutzer haben [die meisten Pull Requests erstellt](help-fastapi.md#einen-pull-request-erstellen){.internal-link target=_blank} welche *<abbr title="Mergen – Zusammenführen: Unterschiedliche Versionen eines Quellcodes zusammenführen">gemerged</abbr>* wurden.
Sie haben Quellcode, Dokumentation, Übersetzungen, usw. beigesteuert. 📦
{% if people %}
<div class="user-list user-list-center">
{% for user in people.top_contributors %}
<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Pull Requests: {{ user.count }}</div></div>
{% endfor %}
</div>
{% endif %}
Es gibt viele andere Mitwirkende (mehr als hundert), Sie können sie alle auf der <a href="https://github.com/fastapi/fastapi/graphs/contributors" class="external-link" target="_blank">FastAPI GitHub Contributors-Seite</a> sehen. 👷
## Top-Rezensenten
Diese Benutzer sind die **Top-Rezensenten**. 🕵️
### Rezensionen für Übersetzungen
Ich spreche nur ein paar Sprachen (und nicht sehr gut 😅). Daher bestätigen Reviewer [**Übersetzungen der Dokumentation**](contributing.md#ubersetzungen){.internal-link target=_blank}. Ohne sie gäbe es keine Dokumentation in mehreren anderen Sprachen.
---
Die **Top-Reviewer** 🕵️ haben die meisten Pull Requests von anderen überprüft und stellen die Qualität des Codes, der Dokumentation und insbesondere der **Übersetzungen** sicher.
{% if people %}
<div class="user-list user-list-center">
{% for user in people.top_reviewers %}
<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Reviews: {{ user.count }}</div></div>
{% endfor %}
</div>
{% endif %}
## Sponsoren
Dies sind die **Sponsoren**. 😎
Sie unterstützen meine Arbeit an **FastAPI** (und andere), hauptsächlich durch <a href="https://github.com/sponsors/tiangolo" class="external-link" target="_blank">GitHub-Sponsoren</a>.
### Gold Sponsoren
{% if sponsors %}
{% for sponsor in sponsors.gold -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}"></a>
{% endfor %}
{% endif %}
### Silber Sponsoren
{% if sponsors %}
{% for sponsor in sponsors.silver -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}"></a>
{% endfor %}
{% endif %}
{% if people %}
{% if people.sponsors_50 %}
### Bronze Sponsoren
<div class="user-list user-list-center">
{% for user in people.sponsors_50 %}
<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a></div>
{% endfor %}
</div>
{% endif %}
{% endif %}
### Individuelle Sponsoren
{% if people %}
<div class="user-list user-list-center">
{% for user in people.sponsors %}
<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a></div>
{% endfor %}
</div>
{% endif %}
## Über diese Daten - technische Details
Der Hauptzweck dieser Seite ist es zu zeigen, wie die Gemeinschaft anderen hilft.
Das beinhaltet auch Hilfe, die normalerweise weniger sichtbar und in vielen Fällen mühsamer ist, wie, anderen bei Problemen zu helfen und Pull Requests mit Übersetzungen zu überprüfen.
Diese Daten werden jeden Monat berechnet, Sie können den <a href="https://github.com/fastapi/fastapi/blob/master/.github/actions/people/app/main.py" class="external-link" target="_blank">Quellcode hier lesen</a>.
Hier weise ich auch auf Beiträge von Sponsoren hin.
Ich behalte mir auch das Recht vor, den Algorithmus, die Abschnitte, die Schwellenwerte usw. zu aktualisieren (nur für den Fall 🤷).

2
docs/de/docs/features.md

@ -6,7 +6,7 @@
### Basiert auf offenen Standards
* <a href="https://github.com/OAI/OpenAPI-Specification" class="external-link" target="_blank"><strong>OpenAPI</strong></a> für die Erstellung von APIs, inklusive Deklarationen von <abbr title="auch genannt Endpunkte, Routen">Pfad</abbr>-<abbr title="gemeint sind HTTP-Methoden wie POST, GET, PUT, DELETE">Operationen</abbr>, Parametern, Body-Anfragen, Sicherheit, usw.
* <a href="https://github.com/OAI/OpenAPI-Specification" class="external-link" target="_blank"><strong>OpenAPI</strong></a> für die Erstellung von APIs, inklusive Deklarationen von <abbr title="auch genannt Endpunkte, Routen">Pfad</abbr>-<abbr title="gemeint sind HTTP-Methoden wie POST, GET, PUT, DELETE">Operationen</abbr>, Parametern, Requestbodys, Sicherheit, usw.
* Automatische Dokumentation der Datenmodelle mit <a href="https://json-schema.org/" class="external-link" target="_blank"><strong>JSON Schema</strong></a> (da OpenAPI selbst auf JSON Schema basiert).
* Um diese Standards herum entworfen, nach sorgfältigem Studium. Statt einer nachträglichen Schicht darüber.
* Dies ermöglicht auch automatische **Client-Code-Generierung** in vielen Sprachen.

2
docs/de/docs/index.md

@ -449,7 +449,7 @@ Um mehr darüber zu erfahren, siehe den Abschnitt <a href="https://fastapi.tiang
Wird von Pydantic verwendet:
* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email_validator</code></a> - für E-Mail-Validierung.
* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email-validator</code></a> - für E-Mail-Validierung.
* <a href="https://docs.pydantic.dev/latest/usage/pydantic_settings/" target="_blank"><code>pydantic-settings</code></a> - für die Verwaltung von Einstellungen.
* <a href="https://docs.pydantic.dev/latest/usage/types/extra_types/extra_types/" target="_blank"><code>pydantic-extra-types</code></a> - für zusätzliche Typen, mit Pydantic zu verwenden.

5
docs/de/docs/newsletter.md

@ -1,5 +0,0 @@
# FastAPI und Freunde Newsletter
<iframe data-w-type="embedded" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="https://xr4n4.mjt.lu/wgt/xr4n4/hj5/form?c=40a44fa4" width="100%" style="height: 0;"></iframe>
<script type="text/javascript" src="https://app.mailjet.com/pas-nc-embedded-v1.js"></script>

24
docs/de/docs/reference/apirouter.md

@ -1,24 +0,0 @@
# `APIRouter`-Klasse
Hier sind die Referenzinformationen für die Klasse `APIRouter` mit all ihren Parametern, Attributen und Methoden.
Sie können die `APIRouter`-Klasse direkt von `fastapi` importieren:
```python
from fastapi import APIRouter
```
::: fastapi.APIRouter
options:
members:
- websocket
- include_router
- get
- put
- post
- delete
- options
- head
- patch
- trace
- on_event

11
docs/de/docs/reference/background.md

@ -1,11 +0,0 @@
# Hintergrundtasks – `BackgroundTasks`
Sie können einen Parameter in einer *Pfadoperation-Funktion* oder einer Abhängigkeitsfunktion mit dem Typ `BackgroundTasks` deklarieren und diesen danach verwenden, um die Ausführung von Hintergrundtasks nach dem Senden der Response zu definieren.
Sie können `BackgroundTasks` direkt von `fastapi` importieren:
```python
from fastapi import BackgroundTasks
```
::: fastapi.BackgroundTasks

29
docs/de/docs/reference/dependencies.md

@ -1,29 +0,0 @@
# Abhängigkeiten – `Depends()` und `Security()`
## `Depends()`
Abhängigkeiten werden hauptsächlich mit der speziellen Funktion `Depends()` behandelt, die ein Callable entgegennimmt.
Hier finden Sie deren Referenz und Parameter.
Sie können sie direkt von `fastapi` importieren:
```python
from fastapi import Depends
```
::: fastapi.Depends
## `Security()`
In vielen Szenarien können Sie die Sicherheit (Autorisierung, Authentifizierung usw.) mit Abhängigkeiten handhaben, indem Sie `Depends()` verwenden.
Wenn Sie jedoch auch OAuth2-Scopes deklarieren möchten, können Sie `Security()` anstelle von `Depends()` verwenden.
Sie können `Security()` direkt von `fastapi` importieren:
```python
from fastapi import Security
```
::: fastapi.Security

3
docs/de/docs/reference/encoders.md

@ -1,3 +0,0 @@
# Encoder – `jsonable_encoder`
::: fastapi.encoders.jsonable_encoder

20
docs/de/docs/reference/exceptions.md

@ -1,20 +0,0 @@
# Exceptions – `HTTPException` und `WebSocketException`
Dies sind die <abbr title="Exception – Ausnahme, Fehler: Python-Objekt, das einen Fehler nebst Metadaten repräsentiert">Exceptions</abbr>, die Sie auslösen können, um dem Client Fehler zu berichten.
Wenn Sie eine Exception auslösen, wird, wie es bei normalem Python der Fall wäre, der Rest der Ausführung abgebrochen. Auf diese Weise können Sie diese Exceptions von überall im Code werfen, um einen Request abzubrechen und den Fehler dem Client anzuzeigen.
Sie können Folgendes verwenden:
* `HTTPException`
* `WebSocketException`
Diese Exceptions können direkt von `fastapi` importiert werden:
```python
from fastapi import HTTPException, WebSocketException
```
::: fastapi.HTTPException
::: fastapi.WebSocketException

31
docs/de/docs/reference/fastapi.md

@ -1,31 +0,0 @@
# `FastAPI`-Klasse
Hier sind die Referenzinformationen für die Klasse `FastAPI` mit all ihren Parametern, Attributen und Methoden.
Sie können die `FastAPI`-Klasse direkt von `fastapi` importieren:
```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

11
docs/de/docs/reference/httpconnection.md

@ -1,11 +0,0 @@
# `HTTPConnection`-Klasse
Wenn Sie Abhängigkeiten definieren möchten, die sowohl mit HTTP als auch mit WebSockets kompatibel sein sollen, können Sie einen Parameter definieren, der eine `HTTPConnection` anstelle eines `Request` oder eines `WebSocket` akzeptiert.
Sie können diese von `fastapi.requests` importieren:
```python
from fastapi.requests import HTTPConnection
```
::: fastapi.requests.HTTPConnection

11
docs/de/docs/reference/index.md

@ -1,11 +0,0 @@
# Referenz – Code-API
Hier ist die Referenz oder Code-API, die Klassen, Funktionen, Parameter, Attribute und alle FastAPI-Teile, die Sie in Ihren Anwendungen verwenden können.
Wenn Sie **FastAPI** lernen möchten, ist es viel besser, das [FastAPI-Tutorial](https://fastapi.tiangolo.com/tutorial/) zu lesen.
/// note | "Hinweis Deutsche Übersetzung"
Die nachfolgende API wird aus der Quelltext-Dokumentation erstellt, daher sind nur die Einleitungen auf Deutsch.
///

45
docs/de/docs/reference/middleware.md

@ -1,45 +0,0 @@
# Middleware
Es gibt mehrere Middlewares, die direkt von Starlette bereitgestellt werden.
Lesen Sie mehr darüber in der [FastAPI-Dokumentation über Middleware](../advanced/middleware.md).
::: fastapi.middleware.cors.CORSMiddleware
Kann von `fastapi` importiert werden:
```python
from fastapi.middleware.cors import CORSMiddleware
```
::: fastapi.middleware.gzip.GZipMiddleware
Kann von `fastapi` importiert werden:
```python
from fastapi.middleware.gzip import GZipMiddleware
```
::: fastapi.middleware.httpsredirect.HTTPSRedirectMiddleware
Kann von `fastapi` importiert werden:
```python
from fastapi.middleware.httpsredirect import HTTPSRedirectMiddleware
```
::: fastapi.middleware.trustedhost.TrustedHostMiddleware
Kann von `fastapi` importiert werden:
```python
from fastapi.middleware.trustedhost import TrustedHostMiddleware
```
::: fastapi.middleware.wsgi.WSGIMiddleware
Kann von `fastapi` importiert werden:
```python
from fastapi.middleware.wsgi import WSGIMiddleware
```

11
docs/de/docs/reference/openapi/docs.md

@ -1,11 +0,0 @@
# OpenAPI `docs`
Werkzeuge zur Verwaltung der automatischen OpenAPI-UI-Dokumentation, einschließlich Swagger UI (standardmäßig unter `/docs`) und ReDoc (standardmäßig unter `/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

5
docs/de/docs/reference/openapi/index.md

@ -1,5 +0,0 @@
# OpenAPI
Es gibt mehrere Werkzeuge zur Handhabung von OpenAPI.
Normalerweise müssen Sie diese nicht verwenden, es sei denn, Sie haben einen bestimmten fortgeschrittenen Anwendungsfall, welcher das erfordert.

5
docs/de/docs/reference/openapi/models.md

@ -1,5 +0,0 @@
# OpenAPI-`models`
OpenAPI Pydantic-Modelle, werden zum Generieren und Validieren der generierten OpenAPI verwendet.
::: fastapi.openapi.models

35
docs/de/docs/reference/parameters.md

@ -1,35 +0,0 @@
# Request-Parameter
Hier die Referenzinformationen für die Request-Parameter.
Dies sind die Sonderfunktionen, die Sie mittels `Annotated` in *Pfadoperation-Funktion*-Parameter oder Abhängigkeitsfunktionen einfügen können, um Daten aus dem Request abzurufen.
Dies beinhaltet:
* `Query()`
* `Path()`
* `Body()`
* `Cookie()`
* `Header()`
* `Form()`
* `File()`
Sie können diese alle direkt von `fastapi` importieren:
```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

17
docs/de/docs/reference/request.md

@ -1,17 +0,0 @@
# `Request`-Klasse
Sie können einen Parameter in einer *Pfadoperation-Funktion* oder einer Abhängigkeit als vom Typ `Request` deklarieren und dann direkt auf das Requestobjekt zugreifen, ohne jegliche Validierung, usw.
Sie können es direkt von `fastapi` importieren:
```python
from fastapi import Request
```
/// tip | "Tipp"
Wenn Sie Abhängigkeiten definieren möchten, die sowohl mit HTTP als auch mit WebSockets kompatibel sein sollen, können Sie einen Parameter definieren, der eine `HTTPConnection` anstelle eines `Request` oder eines `WebSocket` akzeptiert.
///
::: fastapi.Request

13
docs/de/docs/reference/response.md

@ -1,13 +0,0 @@
# `Response`-Klasse
Sie können einen Parameter in einer *Pfadoperation-Funktion* oder einer Abhängigkeit als `Response` deklarieren und dann Daten für die Response wie Header oder Cookies festlegen.
Diese können Sie auch direkt verwenden, um eine Instanz davon zu erstellen und diese von Ihren *Pfadoperationen* zurückzugeben.
Sie können sie direkt von `fastapi` importieren:
```python
from fastapi import Response
```
::: fastapi.Response

164
docs/de/docs/reference/responses.md

@ -1,164 +0,0 @@
# Benutzerdefinierte Responseklassen – File, HTML, Redirect, Streaming, usw.
Es gibt mehrere benutzerdefinierte Responseklassen, von denen Sie eine Instanz erstellen und diese direkt von Ihren *Pfadoperationen* zurückgeben können.
Lesen Sie mehr darüber in der [FastAPI-Dokumentation zu benutzerdefinierten Responses – HTML, Stream, Datei, andere](../advanced/custom-response.md).
Sie können diese direkt von `fastapi.responses` importieren:
```python
from fastapi.responses import (
FileResponse,
HTMLResponse,
JSONResponse,
ORJSONResponse,
PlainTextResponse,
RedirectResponse,
Response,
StreamingResponse,
UJSONResponse,
)
```
## FastAPI-Responses
Es gibt einige benutzerdefinierte FastAPI-Responseklassen, welche Sie verwenden können, um die JSON-Performanz zu optimieren.
::: 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
::: 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

73
docs/de/docs/reference/security/index.md

@ -1,73 +0,0 @@
# Sicherheitstools
Wenn Sie Abhängigkeiten mit OAuth2-Scopes deklarieren müssen, verwenden Sie `Security()`.
Aber Sie müssen immer noch definieren, was das <abbr title="Das von dem abhängt, die zu verwendende Abhängigkeit">Dependable</abbr>, das Callable ist, welches Sie als Parameter an `Depends()` oder `Security()` übergeben.
Es gibt mehrere Tools, mit denen Sie diese Dependables erstellen können, und sie werden in OpenAPI integriert, sodass sie in der Oberfläche der automatischen Dokumentation angezeigt werden und von automatisch generierten Clients und SDKs, usw., verwendet werden können.
Sie können sie von `fastapi.security` importieren:
```python
from fastapi.security import (
APIKeyCookie,
APIKeyHeader,
APIKeyQuery,
HTTPAuthorizationCredentials,
HTTPBasic,
HTTPBasicCredentials,
HTTPBearer,
HTTPDigest,
OAuth2,
OAuth2AuthorizationCodeBearer,
OAuth2PasswordBearer,
OAuth2PasswordRequestForm,
OAuth2PasswordRequestFormStrict,
OpenIdConnect,
SecurityScopes,
)
```
## API-Schlüssel-Sicherheitsschemas
::: fastapi.security.APIKeyCookie
::: fastapi.security.APIKeyHeader
::: fastapi.security.APIKeyQuery
## HTTP-Authentifizierungsschemas
::: fastapi.security.HTTPBasic
::: fastapi.security.HTTPBearer
::: fastapi.security.HTTPDigest
## HTTP-Anmeldeinformationen
::: fastapi.security.HTTPAuthorizationCredentials
::: fastapi.security.HTTPBasicCredentials
## OAuth2-Authentifizierung
::: fastapi.security.OAuth2
::: fastapi.security.OAuth2AuthorizationCodeBearer
::: fastapi.security.OAuth2PasswordBearer
## OAuth2-Passwortformulare
::: fastapi.security.OAuth2PasswordRequestForm
::: fastapi.security.OAuth2PasswordRequestFormStrict
## OAuth2-Sicherheitsscopes in Abhängigkeiten
::: fastapi.security.SecurityScopes
## OpenID Connect
::: fastapi.security.OpenIdConnect

13
docs/de/docs/reference/staticfiles.md

@ -1,13 +0,0 @@
# Statische Dateien – `StaticFiles`
Sie können die `StaticFiles`-Klasse verwenden, um statische Dateien wie JavaScript, CSS, Bilder, usw. bereitzustellen.
Lesen Sie mehr darüber in der [FastAPI-Dokumentation zu statischen Dateien](../tutorial/static-files.md).
Sie können sie direkt von `fastapi.staticfiles` importieren:
```python
from fastapi.staticfiles import StaticFiles
```
::: fastapi.staticfiles.StaticFiles

36
docs/de/docs/reference/status.md

@ -1,36 +0,0 @@
# Statuscodes
Sie können das Modul `status` von `fastapi` importieren:
```python
from fastapi import status
```
`status` wird direkt von Starlette bereitgestellt.
Es enthält eine Gruppe benannter Konstanten (Variablen) mit ganzzahligen Statuscodes.
Zum Beispiel:
* 200: `status.HTTP_200_OK`
* 403: `status.HTTP_403_FORBIDDEN`
* usw.
Es kann praktisch sein, schnell auf HTTP- (und WebSocket-)Statuscodes in Ihrer Anwendung zuzugreifen, indem Sie die automatische Vervollständigung für den Namen verwenden, ohne sich die Zahlen für die Statuscodes merken zu müssen.
Lesen Sie mehr darüber in der [FastAPI-Dokumentation zu Response-Statuscodes](../tutorial/response-status-code.md).
## Beispiel
```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

13
docs/de/docs/reference/templating.md

@ -1,13 +0,0 @@
# Templating – `Jinja2Templates`
Sie können die `Jinja2Templates`-Klasse verwenden, um Jinja-Templates zu rendern.
Lesen Sie mehr darüber in der [FastAPI-Dokumentation zu Templates](../advanced/templates.md).
Sie können die Klasse direkt von `fastapi.templating` importieren:
```python
from fastapi.templating import Jinja2Templates
```
::: fastapi.templating.Jinja2Templates

13
docs/de/docs/reference/testclient.md

@ -1,13 +0,0 @@
# Testclient – `TestClient`
Sie können die `TestClient`-Klasse verwenden, um FastAPI-Anwendungen zu testen, ohne eine tatsächliche HTTP- und Socket-Verbindung zu erstellen, Sie kommunizieren einfach direkt mit dem FastAPI-Code.
Lesen Sie mehr darüber in der [FastAPI-Dokumentation über Testen](../tutorial/testing.md).
Sie können sie direkt von `fastapi.testclient` importieren:
```python
from fastapi.testclient import TestClient
```
::: fastapi.testclient.TestClient

22
docs/de/docs/reference/uploadfile.md

@ -1,22 +0,0 @@
# `UploadFile`-Klasse
Sie können *Pfadoperation-Funktionsparameter* als Parameter vom Typ `UploadFile` definieren, um Dateien aus dem Request zu erhalten.
Sie können es direkt von `fastapi` importieren:
```python
from fastapi import UploadFile
```
::: fastapi.UploadFile
options:
members:
- file
- filename
- size
- headers
- content_type
- read
- write
- seek
- close

67
docs/de/docs/reference/websockets.md

@ -1,67 +0,0 @@
# WebSockets
Bei der Definition von WebSockets deklarieren Sie normalerweise einen Parameter vom Typ `WebSocket` und können damit Daten vom Client lesen und an ihn senden. Er wird direkt von Starlette bereitgestellt, Sie können ihn aber von `fastapi` importieren:
```python
from fastapi import WebSocket
```
/// tip | "Tipp"
Wenn Sie Abhängigkeiten definieren möchten, die sowohl mit HTTP als auch mit WebSockets kompatibel sein sollen, können Sie einen Parameter definieren, der eine `HTTPConnection` anstelle eines `Request` oder eines `WebSocket` akzeptiert.
///
::: 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
Wenn ein Client die Verbindung trennt, wird eine `WebSocketDisconnect`-Exception ausgelöst, die Sie abfangen können.
Sie können diese direkt von `fastapi` importieren:
```python
from fastapi import WebSocketDisconnect
```
::: fastapi.WebSocketDisconnect
## WebSockets – zusätzliche Klassen
Zusätzliche Klassen für die Handhabung von WebSockets.
Werden direkt von Starlette bereitgestellt, Sie können sie jedoch von `fastapi` importieren:
```python
from fastapi.websockets import WebSocketDisconnect, WebSocketState
```
::: fastapi.websockets.WebSocketDisconnect
::: fastapi.websockets.WebSocketState

2
docs/de/docs/tutorial/response-model.md

@ -131,7 +131,7 @@ Im Folgenden deklarieren wir ein `UserIn`-Modell; es enthält ein Klartext-Passw
/// info
Um `EmailStr` zu verwenden, installieren Sie zuerst <a href="https://github.com/JoshData/python-email-validator" class="external-link" target="_blank">`email_validator`</a>.
Um `EmailStr` zu verwenden, installieren Sie zuerst <a href="https://github.com/JoshData/python-email-validator" class="external-link" target="_blank">`email-validator`</a>.
Z. B. `pip install email-validator`
oder `pip install pydantic[email]`.

1
docs/em/docs/advanced/middleware.md

@ -95,7 +95,6 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow")
🖼:
* <a href="https://docs.sentry.io/platforms/python/asgi/" class="external-link" target="_blank">🔫</a>
* <a href="https://github.com/encode/uvicorn/blob/master/uvicorn/middleware/proxy_headers.py" class="external-link" target="_blank">Uvicorn `ProxyHeadersMiddleware`</a>
* <a href="https://github.com/florimondmanca/msgpack-asgi" class="external-link" target="_blank">🇸🇲</a>

7
docs/em/docs/deployment/docker.md

@ -205,8 +205,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"]
`--no-cache-dir` 🎛 💬 `pip` 🚫 🖊 ⏬ 📦 🌐, 👈 🕴 🚥 `pip` 🔜 🏃 🔄 ❎ 🎏 📦, ✋️ 👈 🚫 💼 🕐❔ 👷 ⏮️ 📦.
!!! note
`--no-cache-dir` 🕴 🔗 `pip`, ⚫️ ✔️ 🕳 ⏮️ ☁ ⚖️ 📦.
/// note
`--no-cache-dir` 🕴 🔗 `pip`, ⚫️ ✔️ 🕳 ⏮️ ☁ ⚖️ 📦.
///
`--upgrade` 🎛 💬 `pip` ♻ 📦 🚥 👫 ⏪ ❎.

38
docs/em/docs/external-links.md

@ -1,38 +0,0 @@
# 🔢 🔗 &amp; 📄
**FastAPI** ✔️ 👑 👪 🕧 💗.
📤 📚 🏤, 📄, 🧰, &amp; 🏗, 🔗 **FastAPI**.
📥 ❌ 📇 👫.
/// tip
🚥 👆 ✔️ 📄, 🏗, 🧰, ⚖️ 🕳 🔗 **FastAPI** 👈 🚫 📇 📥, ✍ <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">🚲 📨 ❎ ⚫️</a>.
///
## 📄
{% for section_name, section_content in external_links.items() %}
## {{ section_name }}
{% for lang_name, lang_content in section_content.items() %}
### {{ lang_name }}
{% for item in lang_content %}
* <a href="{{ item.link }}" class="external-link" target="_blank">{{ item.title }}</a> by <a href="{{ item.author_link }}" class="external-link" target="_blank">{{ item.author }}</a>.
{% endfor %}
{% endfor %}
{% endfor %}
## 🏗
⏪ 📂 🏗 ⏮️ ❔ `fastapi`:
<div class="github-topic-projects">
</div>

183
docs/em/docs/fastapi-people.md

@ -1,183 +0,0 @@
---
hide:
- navigation
---
# FastAPI 👫👫
FastAPI ✔️ 🎆 👪 👈 🙋 👫👫 ⚪️➡️ 🌐 🖥.
## 👼 - 🐛
🙋 ❗ 👶
👉 👤:
{% if people %}
<div class="user-list user-list-center">
{% for user in people.maintainers %}
<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">❔: {{ user.answers }}</div><div class="count">🚲 📨: {{ user.prs }}</div></div>
{% endfor %}
</div>
{% endif %}
👤 👼 &amp; 🐛 **FastAPI**. 👆 💪 ✍ 🌅 🔃 👈 [ℹ FastAPI - 🤚 ℹ - 🔗 ⏮️ 📕](help-fastapi.md#_3){.internal-link target=_blank}.
...✋️ 📥 👤 💚 🎦 👆 👪.
---
**FastAPI** 📨 📚 🐕‍🦺 ⚪️➡️ 👪. &amp; 👤 💚 🎦 👫 💰.
👫 👫👫 👈:
* [ℹ 🎏 ⏮️ ❔ 📂](help-fastapi.md#i){.internal-link target=_blank}.
* [✍ 🚲 📨](help-fastapi.md#_15){.internal-link target=_blank}.
* 📄 🚲 📨, [✴️ ⚠ ✍](contributing.md#_9){.internal-link target=_blank}.
👏 👫. 👶 👶
## 🌅 🦁 👩‍💻 🏁 🗓️
👫 👩‍💻 👈 ✔️ [🤝 🎏 🏆 ⏮️ ❔ 📂](help-fastapi.md#i){.internal-link target=_blank} ⏮️ 🏁 🗓️. 👶
{% if people %}
<div class="user-list user-list-center">
{% for user in people.last_month_experts[:10] %}
<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">❔ 📨: {{ user.count }}</div></div>
{% endfor %}
</div>
{% endif %}
## 🕴
📥 **FastAPI 🕴**. 👶
👫 👩‍💻 👈 ✔️ [ℹ 🎏 🏆 ⏮️ ❔ 📂](help-fastapi.md#i){.internal-link target=_blank} 🔘 *🌐 🕰*.
👫 ✔️ 🎦 🕴 🤝 📚 🎏. 👶
{% if people %}
<div class="user-list user-list-center">
{% for user in people.experts[:50] %}
<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">❔ 📨: {{ user.count }}</div></div>
{% endfor %}
</div>
{% endif %}
## 🔝 👨‍🔬
📥 **🔝 👨‍🔬**. 👶
👉 👩‍💻 ✔️ [✍ 🏆 🚲 📨](help-fastapi.md#_15){.internal-link target=_blank} 👈 ✔️ *🔗*.
👫 ✔️ 📉 ℹ 📟, 🧾, ✍, ♒️. 👶
{% if people %}
<div class="user-list user-list-center">
{% for user in people.top_contributors[:50] %}
<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">🚲 📨: {{ user.count }}</div></div>
{% endfor %}
</div>
{% endif %}
📤 📚 🎏 👨‍🔬 (🌅 🌘 💯), 👆 💪 👀 👫 🌐 <a href="https://github.com/fastapi/fastapi/graphs/contributors" class="external-link" target="_blank">FastAPI 📂 👨‍🔬 📃</a>. 👶
## 🔝 👨‍🔬
👫 👩‍💻 **🔝 👨‍🔬**. 👶 👶
### 📄 ✍
👤 🕴 💬 👩‍❤‍👨 🇪🇸 (&amp; 🚫 📶 👍 👶). , 👨‍🔬 🕐 👈 ✔️ [**🏋️ ✔ ✍**](contributing.md#_9){.internal-link target=_blank} 🧾. 🍵 👫, 📤 🚫🔜 🧾 📚 🎏 🇪🇸.
---
**🔝 👨‍🔬** 👶 👶 ✔️ 📄 🏆 🚲 📨 ⚪️➡️ 🎏, 🚚 🔆 📟, 🧾, &amp; ✴️, **✍**.
{% if people %}
<div class="user-list user-list-center">
{% for user in people.top_translations_reviewers[:50] %}
<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">📄: {{ user.count }}</div></div>
{% endfor %}
</div>
{% endif %}
## 💰
👫 **💰**. 👶
👫 🔗 👇 👷 ⏮️ **FastAPI** (&amp; 🎏), ✴️ 🔘 <a href="https://github.com/sponsors/tiangolo" class="external-link" target="_blank">📂 💰</a>.
{% if sponsors %}
{% if sponsors.gold %}
### 🌟 💰
{% for sponsor in sponsors.gold -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor %}
{% endif %}
{% if sponsors.silver %}
### 🥇1st 💰
{% for sponsor in sponsors.silver -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor %}
{% endif %}
{% if sponsors.bronze %}
### 🥈2nd 💰
{% for sponsor in sponsors.bronze -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor %}
{% endif %}
{% endif %}
### 🎯 💰
{% if github_sponsors %}
{% for group in github_sponsors.sponsors %}
<div class="user-list user-list-center">
{% for user in group %}
{% if user.login not in sponsors_badge.logins %}
<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a></div>
{% endif %}
{% endfor %}
</div>
{% endfor %}
{% endif %}
## 🔃 📊 - 📡 ℹ
👑 🎯 👉 📃 🎦 🎯 👪 ℹ 🎏.
✴️ ✅ 🎯 👈 🛎 🌘 ⭐, &amp; 📚 💼 🌅 😩, 💖 🤝 🎏 ⏮️ ❔ &amp; ⚖ 🚲 📨 ⏮️ ✍.
💽 ⚖ 🔠 🗓️, 👆 💪 ✍ <a href="https://github.com/fastapi/fastapi/blob/master/.github/actions/people/app/main.py" class="external-link" target="_blank">ℹ 📟 📥</a>.
📥 👤 🎦 💰 ⚪️➡️ 💰.
👤 🏦 ▶️️ ℹ 📊, 📄, ⚡, ♒️ (💼 🤷).

2
docs/em/docs/index.md

@ -451,7 +451,7 @@ item: Item
⚙️ Pydantic:
* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email_validator</code></a> - 📧 🔬.
* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email-validator</code></a> - 📧 🔬.
⚙️ 💃:

2
docs/em/docs/tutorial/response-model.md

@ -131,7 +131,7 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. &amp; **
/// info
⚙️ `EmailStr`, 🥇 ❎ <a href="https://github.com/JoshData/python-email-validator" class="external-link" target="_blank">`email_validator`</a>.
⚙️ `EmailStr`, 🥇 ❎ <a href="https://github.com/JoshData/python-email-validator" class="external-link" target="_blank">`email-validator`</a>.
🤶 Ⓜ. `pip install email-validator`
⚖️ `pip install pydantic[email]`.

12
docs/en/data/members.yml

@ -1,19 +1,19 @@
members:
- login: tiangolo
avatar_url: https://github.com/tiangolo.png
avatar_url: https://avatars.githubusercontent.com/u/1326112
url: https://github.com/tiangolo
- login: Kludex
avatar_url: https://github.com/Kludex.png
avatar_url: https://avatars.githubusercontent.com/u/7353520
url: https://github.com/Kludex
- login: alejsdev
avatar_url: https://github.com/alejsdev.png
avatar_url: https://avatars.githubusercontent.com/u/90076947
url: https://github.com/alejsdev
- login: svlandeg
avatar_url: https://github.com/svlandeg.png
avatar_url: https://avatars.githubusercontent.com/u/8796347
url: https://github.com/svlandeg
- login: estebanx64
avatar_url: https://github.com/estebanx64.png
avatar_url: https://avatars.githubusercontent.com/u/10840422
url: https://github.com/estebanx64
- login: patrick91
avatar_url: https://github.com/patrick91.png
avatar_url: https://avatars.githubusercontent.com/u/667029
url: https://github.com/patrick91

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

@ -40,7 +40,7 @@ Keep in mind that you have to return the `JSONResponse` directly.
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:
@ -251,5 +251,5 @@ For example:
To see what exactly you can include in the responses, you can check these sections in the OpenAPI specification:
* <a href="https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#responsesObject" class="external-link" target="_blank">OpenAPI Responses Object</a>, it includes the `Response Object`.
* <a href="https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#responseObject" class="external-link" target="_blank">OpenAPI Response Object</a>, 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`.
* <a href="https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#responses-object" class="external-link" target="_blank">OpenAPI Responses Object</a>, it includes the `Response Object`.
* <a href="https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#response-object" class="external-link" target="_blank">OpenAPI Response Object</a>, 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`.

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

@ -211,7 +211,7 @@ Now create that other file `routes.toml`:
This file configures Traefik to use the path prefix `/api/v1`.
And then it will redirect its requests to your Uvicorn running on `http://127.0.0.1:8000`.
And then Traefik will redirect its requests to your Uvicorn running on `http://127.0.0.1:8000`.
Now start Traefik:

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

@ -4,9 +4,9 @@ By default, **FastAPI** will return the responses using `JSONResponse`.
You can override it by returning a `Response` directly as seen in [Return a Response directly](response-directly.md){.internal-link target=_blank}.
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`.
@ -255,11 +255,11 @@ This includes many libraries to interact with cloud storage, video processing, a
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.
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 (`iterfile`).
So, it is a generator function that transfers the "generating" work to something else internally.
By doing it this way, we can put it in a `with` block, and that way, ensure that it is closed after finishing.
By doing it this way, we can put it in a `with` block, and that way, ensure that the file-like object is closed after finishing.
/// tip

2
docs/en/docs/advanced/middleware.md

@ -88,6 +88,7 @@ The middleware will handle both standard and streaming responses.
The following arguments are supported:
* `minimum_size` - Do not GZip responses that are smaller than this minimum size in bytes. Defaults to `500`.
* `compresslevel` - Used during GZip compression. It is an integer ranging from 1 to 9. Defaults to `9`. Lower value results in faster compression but larger file sizes, while higher value results in slower compression but smaller file sizes.
## Other middlewares
@ -95,7 +96,6 @@ There are many other ASGI middlewares.
For example:
* <a href="https://docs.sentry.io/platforms/python/guides/fastapi/" class="external-link" target="_blank">Sentry</a>
* <a href="https://github.com/encode/uvicorn/blob/master/uvicorn/middleware/proxy_headers.py" class="external-link" target="_blank">Uvicorn's `ProxyHeadersMiddleware`</a>
* <a href="https://github.com/florimondmanca/msgpack-asgi" class="external-link" target="_blank">MessagePack</a>

2
docs/en/docs/advanced/openapi-callbacks.md

@ -37,7 +37,7 @@ This part is pretty normal, most of the code is probably already familiar to you
/// tip
The `callback_url` query parameter uses a Pydantic <a href="https://docs.pydantic.dev/latest/concepts/types/#urls" class="external-link" target="_blank">URL</a> type.
The `callback_url` query parameter uses a Pydantic <a href="https://docs.pydantic.dev/latest/api/networks/" class="external-link" target="_blank">Url</a> type.
///

4
docs/en/docs/advanced/response-directly.md

@ -28,7 +28,7 @@ This gives you a lot of flexibility. You can return any data type, override any
## Using the `jsonable_encoder` in a `Response`
Because **FastAPI** doesn't do any change to a `Response` you return, you have to make sure it's contents are ready for it.
Because **FastAPI** doesn't do any change 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.
@ -54,7 +54,7 @@ Now, let's see how you could use that to return a custom response.
Let's say that you want to return an <a href="https://en.wikipedia.org/wiki/XML" class="external-link" target="_blank">XML</a> response.
You could put your XML content in a string, put it in a `Response`, and return it:
You could put your XML content in a string, put that in a `Response`, and return it:
```Python hl_lines="1 18"
{!../../../docs_src/response_directly/tutorial002.py!}

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

@ -398,7 +398,7 @@ 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.
@ -725,7 +725,7 @@ 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

130
docs/en/docs/advanced/settings.md

@ -6,143 +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
If you already know what "environment variables" are and how to use them, feel free to skip to the next section below.
///
An <a href="https://en.wikipedia.org/wiki/Environment_variable" class="external-link" target="_blank">environment variable</a> (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:
//// tab | Linux, macOS, Windows Bash
<div class="termy">
```console
// You could create an env var MY_NAME with
$ export MY_NAME="Wade Wilson"
// Then you could use it with other programs, like
$ echo "Hello $MY_NAME"
Hello Wade Wilson
```
</div>
////
//// tab | Windows PowerShell
<div class="termy">
```console
// Create an env var MY_NAME
$ $Env:MY_NAME = "Wade Wilson"
// Use it with other programs, like
$ echo "Hello $Env:MY_NAME"
Hello Wade Wilson
```
</div>
////
### Read env vars in Python
You could also create environment variables outside of Python, in the terminal (or with any other method), and then read them in Python.
For example you could have a file `main.py` with:
```Python hl_lines="3"
import os
name = os.getenv("MY_NAME", "World")
print(f"Hello {name} from Python")
```
/// tip
The second argument to <a href="https://docs.python.org/3.8/library/os.html#os.getenv" class="external-link" target="_blank">`os.getenv()`</a> is the default value to return.
If not provided, it's `None` by default, here we provide `"World"` as the default value to use.
///
Then you could call that Python program:
<div class="termy">
```console
// Here we don't set the env var yet
$ python main.py
// As we didn't set the env var, we get the default value
Hello World from Python
// But if we create an environment variable first
$ export MY_NAME="Wade Wilson"
// And then call the program again
$ python main.py
// Now it can read the environment variable
Hello Wade Wilson from Python
```
</div>
As environment variables can be set outside of the code, but can be read by the code, and don't have to be stored (committed to `git`) with the rest of the files, it's common to use them for configurations or settings.
You can also create an environment variable only for a specific program invocation, that is only available to that program, and only for its duration.
To do that, create it right before the program itself, on the same line:
<div class="termy">
```console
// Create an env var MY_NAME in line for this program call
$ MY_NAME="Wade Wilson" python main.py
// Now it can read the environment variable
Hello Wade Wilson from Python
// The env var no longer exists afterwards
$ python main.py
Hello World from Python
```
</div>
/// tip
You can read more about it at <a href="https://12factor.net/config" class="external-link" target="_blank">The Twelve-Factor App: Config</a>.
To understand environment variables you can read [Environment Variables](../environment-variables.md){.internal-link target=_blank}.
///
### Types and validation
## Types and validation
These environment variables can only handle text strings, as they are external to Python and have to be compatible with other programs and the rest of the system (and even with different operating systems, as Linux, Windows, macOS).
That means that any value read in Python from an environment variable will be a `str`, and any conversion to a different type or validation has to be done in code.
That means that any value read in Python from an environment variable will be a `str`, and any conversion to a different type or any validation has to be done in code.
## Pydantic `Settings`
Fortunately, Pydantic provides a great utility to handle these settings coming from environment variables with <a href="https://docs.pydantic.dev/latest/usage/pydantic_settings/" class="external-link" target="_blank">Pydantic: Settings management</a>.
Fortunately, Pydantic provides a great utility to handle these settings coming from environment variables with <a href="https://docs.pydantic.dev/latest/concepts/pydantic_settings/" class="external-link" target="_blank">Pydantic: Settings management</a>.
### Install `pydantic-settings`
First, install the `pydantic-settings` package:
First, make sure you create your [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install the `pydantic-settings` package:
<div class="termy">
@ -411,7 +293,7 @@ And then update your `config.py` with:
/// tip
The `model_config` attribute is used just for Pydantic configuration. You can read more at <a href="https://docs.pydantic.dev/latest/usage/model_config/" class="external-link" target="_blank">Pydantic Model Config</a>.
The `model_config` attribute is used just for Pydantic configuration. You can read more at <a href="https://docs.pydantic.dev/latest/concepts/config/" class="external-link" target="_blank">Pydantic: Concepts: Configuration</a>.
///

4
docs/en/docs/advanced/sub-applications.md

@ -36,12 +36,12 @@ In this case, it will be mounted at the path `/subapi`:
### Check the automatic API docs
Now, run `uvicorn` with the main app, if your file is `main.py`, it would be:
Now, run the `fastapi` command with your file:
<div class="termy">
```console
$ uvicorn main:app --reload
$ fastapi dev main.py
<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
```

2
docs/en/docs/advanced/templates.md

@ -8,7 +8,7 @@ There are utilities to configure it easily that you can use directly in your **F
## Install dependencies
Install `jinja2`:
Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and install `jinja2`:
<div class="termy">

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

@ -4,7 +4,7 @@ You can use <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSockets
## Install `WebSockets`
First you need to install `WebSockets`:
Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and install `websockets`:
<div class="termy">

2
docs/en/docs/alternatives.md

@ -474,7 +474,7 @@ It is the recommended server for Starlette and **FastAPI**.
The main web server to run **FastAPI** applications.
You can combine it with Gunicorn, to have an asynchronous multi-process server.
You can also use the `--workers` command line option to have an asynchronous multi-process server.
Check more details in the [Deployment](deployment/index.md){.internal-link target=_blank} section.

4
docs/en/docs/async.md

@ -292,7 +292,7 @@ For example:
### 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.
@ -369,6 +369,8 @@ In particular, you can directly use <a href="https://anyio.readthedocs.io/en/sta
And even if you were not using FastAPI, you could also write your own async applications with <a href="https://anyio.readthedocs.io/en/stable/" class="external-link" target="_blank">AnyIO</a> 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**: <a href="https://asyncer.tiangolo.com/" class="external-link" target="_blank">Asyncer</a>. It would be particularly useful if you need to **combine async code with regular** (blocking/synchronous) code.
### Other forms of asynchronous code
This style of using `async` and `await` is relatively new in the language.

158
docs/en/docs/contributing.md

@ -6,117 +6,13 @@ First, you might want to see the basic ways to [help FastAPI and get help](help-
If you already cloned the <a href="https://github.com/fastapi/fastapi" class="external-link" target="_blank">fastapi repository</a> and you want to deep dive in the code, here are some guidelines to set up your environment.
### Virtual environment with `venv`
### Virtual environment
You can create an isolated virtual local environment in a directory using Python's `venv` module. Let's do this in the cloned repository (where the `requirements.txt` is):
<div class="termy">
```console
$ python -m venv env
```
</div>
That will create a directory `./env/` with the Python binaries, and then you will be able to install packages for that local environment.
### Activate the environment
Activate the new environment with:
//// tab | Linux, macOS
<div class="termy">
```console
$ source ./env/bin/activate
```
</div>
////
//// tab | Windows PowerShell
<div class="termy">
```console
$ .\env\Scripts\Activate.ps1
```
</div>
////
//// tab | Windows Bash
Or if you use Bash for Windows (e.g. <a href="https://gitforwindows.org/" class="external-link" target="_blank">Git Bash</a>):
<div class="termy">
```console
$ source ./env/Scripts/activate
```
</div>
////
To check it worked, use:
//// tab | Linux, macOS, Windows Bash
<div class="termy">
```console
$ which pip
some/directory/fastapi/env/bin/pip
```
</div>
////
//// tab | Windows PowerShell
<div class="termy">
```console
$ Get-Command pip
some/directory/fastapi/env/bin/pip
```
</div>
////
If it shows the `pip` binary at `env/bin/pip` then it worked. 🎉
Make sure you have the latest pip version on your local environment to avoid errors on the next steps:
<div class="termy">
```console
$ python -m pip install --upgrade pip
---> 100%
```
</div>
/// tip
Every time you install a new package with `pip` under that environment, activate the environment again.
This makes sure that if you use a terminal program installed by that package, you use the one from your local environment and not any other that could be installed globally.
///
Follow the instructions to create and activate a [virtual environment](virtual-environments.md){.internal-link target=_blank} for the internal code of `fastapi`.
### Install requirements using pip
After activating the environment as described above:
After activating the environment, install the required packages:
<div class="termy">
@ -160,7 +56,19 @@ $ bash scripts/format.sh
It will also auto-sort all your imports.
For it to sort them correctly, you need to have FastAPI installed locally in your environment, with the command in the section above using `-e`.
## Tests
There is a script that you can run locally to test all the code and generate coverage reports in HTML:
<div class="termy">
```console
$ bash scripts/test-cov-html.sh
```
</div>
This command generates a directory `./htmlcov/`, if you open the file `./htmlcov/index.html` in your browser, you can explore interactively the regions of code that are covered by the tests, and notice if there is any region missing.
## Docs
@ -262,7 +170,7 @@ If you run the examples with, e.g.:
<div class="termy">
```console
$ uvicorn tutorial001:app --reload
$ fastapi dev tutorial001.py
<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
```
@ -370,6 +278,20 @@ If you go to your browser you will see that now the docs show your new section (
Now you can translate it all and see how it looks as you save the file.
#### Don't Translate these Pages
🚨 Don't translate:
* Files under `reference/`
* `release-notes.md`
* `fastapi-people.md`
* `external-links.md`
* `newsletter.md`
* `management-tasks.md`
* `management.md`
Some of these files are updated very frequently and a translation would always be behind, or they include the main content from English source files, etc.
#### New Language
Let's say that you want to add translations for a language that is not yet translated, not even some pages.
@ -458,9 +380,9 @@ Serving at: http://127.0.0.1:8008
* Do not change anything enclosed in "``" (inline code).
* In lines starting with `===` or `!!!`, translate only the ` "... Text ..."` part. Leave the rest unchanged.
* In lines starting with `///` translate only the ` "... Text ..."` part. Leave the rest unchanged.
* You can translate info boxes like `!!! warning` with for example `!!! warning "Achtung"`. But do not change the word immediately after the `!!!`, it determines the color of the info box.
* You can translate info boxes like `/// warning` with for example `/// warning | Achtung`. But do not change the word immediately after the `///`, it determines the color of the info box.
* Do not change the paths in links to images, code files, Markdown documents.
@ -468,17 +390,3 @@ Serving at: http://127.0.0.1:8008
* Search for such links in the translated document using the regex `#[^# ]`.
* Search in all documents already translated into your language for `your-translated-document.md`. For example VS Code has an option "Edit" -> "Find in Files".
* When translating a document, do not "pre-translate" `#hash-parts` that link to headings in untranslated documents.
## Tests
There is a script that you can run locally to test all the code and generate coverage reports in HTML:
<div class="termy">
```console
$ bash scripts/test-cov-html.sh
```
</div>
This command generates a directory `./htmlcov/`, if you open the file `./htmlcov/index.html` in your browser, you can explore interactively the regions of code that are covered by the tests, and notice if there is any region missing.

8
docs/en/docs/deployment/concepts.md

@ -94,7 +94,7 @@ In most cases, when you create a web API, you want it to be **always running**,
### In a Remote Server
When you set up a remote server (a cloud server, a virtual machine, etc.) the simplest thing you can do is to use `fastapi run`, Uvicorn (or similar) manually, the same way you do when developing locally.
When you set up a remote server (a cloud server, a virtual machine, etc.) the simplest thing you can do is use `fastapi run` (which uses Uvicorn) or something similar, manually, the same way you do when developing locally.
And it will work and will be useful **during development**.
@ -178,7 +178,7 @@ For example, this could be handled by:
## Replication - Processes and Memory
With a FastAPI application, using a server program like Uvicorn, running it once in **one process** can serve multiple clients concurrently.
With a FastAPI application, using a server program like the `fastapi` command that runs Uvicorn, running it once in **one process** can serve multiple clients concurrently.
But in many cases, you will want to run several worker processes at the same time.
@ -232,9 +232,7 @@ The main constraint to consider is that there has to be a **single** component h
Here are some possible combinations and strategies:
* **Gunicorn** managing **Uvicorn workers**
* Gunicorn would be the **process manager** listening on the **IP** and **port**, the replication would be by having **multiple Uvicorn worker processes**.
* **Uvicorn** managing **Uvicorn workers**
* **Uvicorn** with `--workers`
* One Uvicorn **process manager** would listen on the **IP** and **port**, and it would start **multiple Uvicorn worker processes**.
* **Kubernetes** and other distributed **container systems**
* Something in the **Kubernetes** layer would listen on the **IP** and **port**. The replication would be by having **multiple containers**, each with **one Uvicorn process** running.

265
docs/en/docs/deployment/docker.md

@ -167,22 +167,22 @@ def read_item(item_id: int, q: Union[str, None] = None):
Now in the same project directory create a file `Dockerfile` with:
```{ .dockerfile .annotate }
# (1)
# (1)!
FROM python:3.9
# (2)
# (2)!
WORKDIR /code
# (3)
# (3)!
COPY ./requirements.txt /code/requirements.txt
# (4)
# (4)!
RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
# (5)
# (5)!
COPY ./app /code/app
# (6)
# (6)!
CMD ["fastapi", "run", "app/main.py", "--port", "80"]
```
@ -202,8 +202,11 @@ CMD ["fastapi", "run", "app/main.py", "--port", "80"]
The `--no-cache-dir` option tells `pip` to not save the downloaded packages locally, as that is only if `pip` was going to be run again to install the same packages, but that's not the case when working with containers.
!!! note
The `--no-cache-dir` is only related to `pip`, it has nothing to do with Docker or containers.
/// note
The `--no-cache-dir` is only related to `pip`, it has nothing to do with Docker or containers.
///
The `--upgrade` option tells `pip` to upgrade the packages if they are already installed.
@ -229,6 +232,38 @@ Review what each line does by clicking each number bubble in the code. 👆
///
/// warning
Make sure to **always** use the **exec form** of the `CMD` instruction, as explained below.
///
#### Use `CMD` - Exec Form
The <a href="https://docs.docker.com/reference/dockerfile/#cmd" class="external-link" target="_blank">`CMD`</a> Docker instruction can be written using two forms:
**Exec** form:
```Dockerfile
# ✅ Do this
CMD ["fastapi", "run", "app/main.py", "--port", "80"]
```
⛔️ **Shell** form:
```Dockerfile
# ⛔️ Don't do this
CMD fastapi run app/main.py --port 80
```
Make sure to always use the **exec** form to ensure that FastAPI can shutdown gracefully and [lifespan events](../advanced/events.md){.internal-link target=_blank} are triggered.
You can read more about it in the <a href="https://docs.docker.com/reference/dockerfile/#shell-and-exec-form" class="external-link" target="_blank">Docker docs for shell and exec form</a>.
This can be quite noticeable when using `docker compose`. See this Docker Compose FAQ section for more technical details: <a href="https://docs.docker.com/compose/faq/#why-do-my-services-take-10-seconds-to-recreate-or-stop" class="external-link" target="_blank">Why do my services take 10 seconds to recreate or stop?</a>.
#### Directory Structure
You should now have a directory structure like:
```
@ -365,10 +400,10 @@ COPY ./requirements.txt /code/requirements.txt
RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
# (1)
# (1)!
COPY ./main.py /code/
# (2)
# (2)!
CMD ["fastapi", "run", "main.py", "--port", "80"]
```
@ -421,11 +456,11 @@ Without using containers, making applications run on startup and with restarts c
## Replication - Number of Processes
If you have a <abbr title="A group of machines that are configured to be connected and work together in some way.">cluster</abbr> of machines with **Kubernetes**, Docker Swarm Mode, Nomad, or another similar complex system to manage distributed containers on multiple machines, then you will probably want to **handle replication** at the **cluster level** instead of using a **process manager** (like Gunicorn with workers) in each container.
If you have a <abbr title="A group of machines that are configured to be connected and work together in some way.">cluster</abbr> of machines with **Kubernetes**, Docker Swarm Mode, Nomad, or another similar complex system to manage distributed containers on multiple machines, then you will probably want to **handle replication** at the **cluster level** instead of using a **process manager** (like Uvicorn with workers) in each container.
One of those distributed container management systems like Kubernetes normally has some integrated way of handling **replication of containers** while still supporting **load balancing** for the incoming requests. All at the **cluster level**.
In those cases, you would probably want to build a **Docker image from scratch** as [explained above](#dockerfile), installing your dependencies, and running **a single Uvicorn process** instead of running something like Gunicorn with Uvicorn workers.
In those cases, you would probably want to build a **Docker image from scratch** as [explained above](#dockerfile), installing your dependencies, and running **a single Uvicorn process** instead of using multiple Uvicorn workers.
### Load Balancer
@ -455,37 +490,44 @@ And normally this **load balancer** would be able to handle requests that go to
In this type of scenario, you probably would want to have **a single (Uvicorn) process per container**, as you would already be handling replication at the cluster level.
So, in this case, you **would not** want to have a process manager like Gunicorn with Uvicorn workers, or Uvicorn using its own Uvicorn workers. You would want to have just a **single Uvicorn process** per container (but probably multiple containers).
So, in this case, you **would not** want to have a multiple workers in the container, for example with the `--workers` command line option.You would want to have just a **single Uvicorn process** per container (but probably multiple containers).
Having another process manager inside the container (as would be with Gunicorn or Uvicorn managing Uvicorn workers) would only add **unnecessary complexity** that you are most probably already taking care of with your cluster system.
Having another process manager inside the container (as would be with multiple workers) would only add **unnecessary complexity** that you are most probably already taking care of with your cluster system.
### Containers with Multiple Processes and Special Cases
Of course, there are **special cases** where you could want to have **a container** with a **Gunicorn process manager** starting several **Uvicorn worker processes** inside.
Of course, there are **special cases** where you could want to have **a container** with several **Uvicorn worker processes** inside.
In those cases, you can use the **official Docker image** that includes **Gunicorn** as a process manager running multiple **Uvicorn worker processes**, and some default settings to adjust the number of workers based on the current CPU cores automatically. I'll tell you more about it below in [Official Docker Image with Gunicorn - Uvicorn](#official-docker-image-with-gunicorn-uvicorn).
In those cases, you can use the `--workers` command line option to set the number of workers that you want to run:
Here are some examples of when that could make sense:
```{ .dockerfile .annotate }
FROM python:3.9
#### A Simple App
WORKDIR /code
You could want a process manager in the container if your application is **simple enough** that you don't need (at least not yet) to fine-tune the number of processes too much, and you can just use an automated default (with the official Docker image), and you are running it on a **single server**, not a cluster.
COPY ./requirements.txt /code/requirements.txt
#### Docker Compose
RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
You could be deploying to a **single server** (not a cluster) with **Docker Compose**, so you wouldn't have an easy way to manage replication of containers (with Docker Compose) while preserving the shared network and **load balancing**.
COPY ./app /code/app
Then you could want to have **a single container** with a **process manager** starting **several worker processes** inside.
# (1)!
CMD ["fastapi", "run", "app/main.py", "--port", "80", "--workers", "4"]
```
1. Here we use the `--workers` command line option to set the number of workers to 4.
#### Prometheus and Other Reasons
Here are some examples of when that could make sense:
You could also have **other reasons** that would make it easier to have a **single container** with **multiple processes** instead of having **multiple containers** with **a single process** in each of them.
#### A Simple App
For example (depending on your setup) you could have some tool like a Prometheus exporter in the same container that should have access to **each of the requests** that come.
You could want a process manager in the container if your application is **simple enough** that can run it on a **single server**, not a cluster.
In this case, if you had **multiple containers**, by default, when Prometheus came to **read the metrics**, it would get the ones for **a single container each time** (for the container that handled that particular request), instead of getting the **accumulated metrics** for all the replicated containers.
#### Docker Compose
Then, in that case, it could be simpler to have **one container** with **multiple processes**, and a local tool (e.g. a Prometheus exporter) on the same container collecting Prometheus metrics for all the internal processes and exposing those metrics on that single container.
You could be deploying to a **single server** (not a cluster) with **Docker Compose**, so you wouldn't have an easy way to manage replication of containers (with Docker Compose) while preserving the shared network and **load balancing**.
Then you could want to have **a single container** with a **process manager** starting **several worker processes** inside.
---
@ -506,7 +548,7 @@ And then you can set those same memory limits and requirements in your configura
If your application is **simple**, this will probably **not be a problem**, and you might not need to specify hard memory limits. But if you are **using a lot of memory** (for example with **machine learning** models), you should check how much memory you are consuming and adjust the **number of containers** that runs in **each machine** (and maybe add more machines to your cluster).
If you run **multiple processes per container** (for example with the official Docker image) you will have to make sure that the number of processes started doesn't **consume more memory** than what is available.
If you run **multiple processes per container** you will have to make sure that the number of processes started doesn't **consume more memory** than what is available.
## Previous Steps Before Starting and Containers
@ -526,80 +568,26 @@ If in your use case there's no problem in running those previous steps **multipl
### Single Container
If you have a simple setup, with a **single container** that then starts multiple **worker processes** (or also just one process), then you could run those previous steps in the same container, right before starting the process with the app. The official Docker image supports this internally.
## Official Docker Image with Gunicorn - Uvicorn
There is an official Docker image that includes Gunicorn running with Uvicorn workers, as detailed in a previous chapter: [Server Workers - Gunicorn with Uvicorn](server-workers.md){.internal-link target=_blank}.
If you have a simple setup, with a **single container** that then starts multiple **worker processes** (or also just one process), then you could run those previous steps in the same container, right before starting the process with the app.
This image would be useful mainly in the situations described above in: [Containers with Multiple Processes and Special Cases](#containers-with-multiple-processes-and-special-cases).
* <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>.
/// warning
### Base Docker Image
There's a high chance that you **don't** need this base image or any other similar one, and would be better off by building the image from scratch as [described above in: Build a Docker Image for FastAPI](#build-a-docker-image-for-fastapi).
There used to be an official FastAPI Docker image: <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>. But it is now deprecated. ⛔️
///
You should probably **not** use this base Docker image (or any other similar one).
This image has an **auto-tuning** mechanism included to set the **number of worker processes** based on the CPU cores available.
If you are using **Kubernetes** (or others) and you are already setting **replication** at the cluster level, with multiple **containers**. In those cases, you are better off **building an image from scratch** as described above: [Build a Docker Image for FastAPI](#build-a-docker-image-for-fastapi).
It has **sensible defaults**, but you can still change and update all the configurations with **environment variables** or configuration files.
And if you need to have multiple workers, you can simply use the `--workers` command line option.
It also supports running <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker#pre_start_path" class="external-link" target="_blank">**previous steps before starting**</a> with a script.
/// note | Technical Details
/// tip
The Docker image was created when Uvicorn didn't support managing and restarting dead workers, so it was needed to use Gunicorn with Uvicorn, which added quite some complexity, just to have Gunicorn manage and restart the Uvicorn worker processes.
To see all the configurations and options, go to the Docker image page: <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>.
But now that Uvicorn (and the `fastapi` command) support using `--workers`, there's no reason to use a base Docker image instead of building your own (it's pretty much the same amount of code 😅).
///
### Number of Processes on the Official Docker Image
The **number of processes** on this image is **computed automatically** from the CPU **cores** available.
This means that it will try to **squeeze** as much **performance** from the CPU as possible.
You can also adjust it with the configurations using **environment variables**, etc.
But it also means that as the number of processes depends on the CPU the container is running, the **amount of memory consumed** will also depend on that.
So, if your application consumes a lot of memory (for example with machine learning models), and your server has a lot of CPU cores **but little memory**, then your container could end up trying to use more memory than what is available, and degrading performance a lot (or even crashing). 🚨
### Create a `Dockerfile`
Here's how you would create a `Dockerfile` based on this image:
```Dockerfile
FROM tiangolo/uvicorn-gunicorn-fastapi:python3.9
COPY ./requirements.txt /app/requirements.txt
RUN pip install --no-cache-dir --upgrade -r /app/requirements.txt
COPY ./app /app
```
### Bigger Applications
If you followed the section about creating [Bigger Applications with Multiple Files](../tutorial/bigger-applications.md){.internal-link target=_blank}, your `Dockerfile` might instead look like:
```Dockerfile hl_lines="7"
FROM tiangolo/uvicorn-gunicorn-fastapi:python3.9
COPY ./requirements.txt /app/requirements.txt
RUN pip install --no-cache-dir --upgrade -r /app/requirements.txt
COPY ./app /app/app
```
### When to Use
You should probably **not** use this official base image (or any other similar one) if you are using **Kubernetes** (or others) and you are already setting **replication** at the cluster level, with multiple **containers**. In those cases, you are better off **building an image from scratch** as described above: [Build a Docker Image for FastAPI](#build-a-docker-image-for-fastapi).
This image would be useful mainly in the special cases described above in [Containers with Multiple Processes and Special Cases](#containers-with-multiple-processes-and-special-cases). For example, if your application is **simple enough** that setting a default number of processes based on the CPU works well, you don't want to bother with manually configuring the replication at the cluster level, and you are not running more than one container with your app. Or if you are deploying with **Docker Compose**, running on a single server, etc.
## Deploy the Container Image
After having a Container (Docker) Image there are several ways to deploy it.
@ -612,98 +600,9 @@ For example:
* With another tool like Nomad
* With a cloud service that takes your container image and deploys it
## Docker Image with Poetry
If you use <a href="https://python-poetry.org/" class="external-link" target="_blank">Poetry</a> to manage your project's dependencies, you could use Docker multi-stage building:
```{ .dockerfile .annotate }
# (1)
FROM python:3.9 as requirements-stage
# (2)
WORKDIR /tmp
# (3)
RUN pip install poetry
# (4)
COPY ./pyproject.toml ./poetry.lock* /tmp/
# (5)
RUN poetry export -f requirements.txt --output requirements.txt --without-hashes
# (6)
FROM python:3.9
# (7)
WORKDIR /code
# (8)
COPY --from=requirements-stage /tmp/requirements.txt /code/requirements.txt
# (9)
RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
# (10)
COPY ./app /code/app
# (11)
CMD ["fastapi", "run", "app/main.py", "--port", "80"]
```
1. This is the first stage, it is named `requirements-stage`.
## Docker Image with `uv`
2. Set `/tmp` as the current working directory.
Here's where we will generate the file `requirements.txt`
3. Install Poetry in this Docker stage.
4. Copy the `pyproject.toml` and `poetry.lock` files to the `/tmp` directory.
Because it uses `./poetry.lock*` (ending with a `*`), it won't crash if that file is not available yet.
5. Generate the `requirements.txt` file.
6. This is the final stage, anything here will be preserved in the final container image.
7. Set the current working directory to `/code`.
8. Copy the `requirements.txt` file to the `/code` directory.
This file only lives in the previous Docker stage, that's why we use `--from-requirements-stage` to copy it.
9. Install the package dependencies in the generated `requirements.txt` file.
10. Copy the `app` directory to the `/code` directory.
11. Use the `fastapi run` command to run your app.
/// tip
Click the bubble numbers to see what each line does.
///
A **Docker stage** is a part of a `Dockerfile` that works as a **temporary container image** that is only used to generate some files to be used later.
The first stage will only be used to **install Poetry** and to **generate the `requirements.txt`** with your project dependencies from Poetry's `pyproject.toml` file.
This `requirements.txt` file will be used with `pip` later in the **next stage**.
In the final container image **only the final stage** is preserved. The previous stage(s) will be discarded.
When using Poetry, it would make sense to use **Docker multi-stage builds** because you don't really need to have Poetry and its dependencies installed in the final container image, you **only need** to have the generated `requirements.txt` file to install your project dependencies.
Then in the next (and final) stage you would build the image more or less in the same way as described before.
### Behind a TLS Termination Proxy - Poetry
Again, if you are running your container behind a TLS Termination Proxy (load balancer) like Nginx or Traefik, add the option `--proxy-headers` to the command:
```Dockerfile
CMD ["fastapi", "run", "app/main.py", "--proxy-headers", "--port", "80"]
```
If you are using <a href="https://github.com/astral-sh/uv" class="external-link" target="_blank">uv</a> to install and manage your project, you can follow their <a href="https://docs.astral.sh/uv/guides/integration/docker/" class="external-link" target="_blank">uv Docker guide</a>.
## Recap
@ -719,5 +618,3 @@ Using container systems (e.g. with **Docker** and **Kubernetes**) it becomes fai
In most cases, you probably won't want to use any base image, and instead **build a container image from scratch** one based on the official Python Docker image.
Taking care of the **order** of instructions in the `Dockerfile` and the **Docker cache** you can **minimize build times**, to maximize your productivity (and avoid boredom). 😎
In certain special cases, you might want to use the official Docker image for FastAPI. 🤓

89
docs/en/docs/deployment/manually.md

@ -67,6 +67,8 @@ There are several alternatives, including:
* <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>: a high performance ASGI server.
* <a href="https://hypercorn.readthedocs.io/" class="external-link" target="_blank">Hypercorn</a>: an ASGI server compatible with HTTP/2 and Trio among other features.
* <a href="https://github.com/django/daphne" class="external-link" target="_blank">Daphne</a>: the ASGI server built for Django Channels.
* <a href="https://github.com/emmett-framework/granian" class="external-link" target="_blank">Granian</a>: A Rust HTTP server for Python applications.
* <a href="https://unit.nginx.org/howto/fastapi/" class="external-link" target="_blank">NGINX Unit</a>: NGINX Unit is a lightweight and versatile web application runtime.
## Server Machine and Server Program
@ -82,11 +84,11 @@ When referring to the remote machine, it's common to call it **server**, but als
When you install FastAPI, it comes with a production server, Uvicorn, and you can start it with the `fastapi run` command.
But you can also install an ASGI server manually:
But you can also install an ASGI server manually.
//// tab | Uvicorn
Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then you can install the server application.
* <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>, a lightning-fast ASGI server, built on uvloop and httptools.
For example, to install Uvicorn:
<div class="termy">
@ -98,6 +100,8 @@ $ pip install "uvicorn[standard]"
</div>
A similar process would apply to any other ASGI server program.
/// tip
By adding the `standard`, Uvicorn will install and use some recommended extra dependencies.
@ -108,32 +112,10 @@ When you install FastAPI with something like `pip install "fastapi[standard]"` y
///
////
//// tab | Hypercorn
* <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, an ASGI server also compatible with HTTP/2.
<div class="termy">
```console
$ pip install hypercorn
---> 100%
```
</div>
...or any other ASGI server.
////
## Run the Server Program
If you installed an ASGI server manually, you would normally need to pass an import string in a special format for it to import your FastAPI application:
//// tab | Uvicorn
<div class="termy">
```console
@ -144,22 +126,6 @@ $ uvicorn main:app --host 0.0.0.0 --port 80
</div>
////
//// tab | Hypercorn
<div class="termy">
```console
$ hypercorn main:app --bind 0.0.0.0:80
Running on 0.0.0.0:8080 over http (CTRL + C to quit)
```
</div>
////
/// note
The command `uvicorn main:app` refers to:
@ -175,9 +141,11 @@ from main import app
///
Each alternative ASGI server program would have a similar command, you can read more in their respective documentation.
/// warning
Uvicorn and others support a `--reload` option that is useful during development.
Uvicorn and other servers support a `--reload` option that is useful during development.
The `--reload` option consumes much more resources, is more unstable, etc.
@ -185,43 +153,6 @@ It helps a lot during **development**, but you **shouldn't** use it in **product
///
## Hypercorn with Trio
Starlette and **FastAPI** are based on <a href="https://anyio.readthedocs.io/en/stable/" class="external-link" target="_blank">AnyIO</a>, which makes them compatible with both Python's standard library <a href="https://docs.python.org/3/library/asyncio-task.html" class="external-link" target="_blank">asyncio</a> and <a href="https://trio.readthedocs.io/en/stable/" class="external-link" target="_blank">Trio</a>.
Nevertheless, Uvicorn is currently only compatible with asyncio, and it normally uses <a href="https://github.com/MagicStack/uvloop" class="external-link" target="_blank">`uvloop`</a>, the high-performance drop-in replacement for `asyncio`.
But if you want to directly use **Trio**, then you can use **Hypercorn** as it supports it. ✨
### Install Hypercorn with Trio
First you need to install Hypercorn with Trio support:
<div class="termy">
```console
$ pip install "hypercorn[trio]"
---> 100%
```
</div>
### Run with Trio
Then you can pass the command line option `--worker-class` with the value `trio`:
<div class="termy">
```console
$ hypercorn main:app --worker-class trio
```
</div>
And that will start Hypercorn with your app using Trio as the backend.
Now you can use Trio internally in your app. Or even better, you can use AnyIO, to keep your code compatible with both Trio and asyncio. 🎉
## Deployment Concepts
These examples run the server program (e.g Uvicorn), starting **a single process**, listening on all the IPs (`0.0.0.0`) on a predefined port (e.g. `80`).

163
docs/en/docs/deployment/server-workers.md

@ -1,4 +1,4 @@
# Server Workers - Gunicorn with Uvicorn
# Server Workers - Uvicorn with Workers
Let's check back those deployment concepts from before:
@ -9,123 +9,92 @@ Let's check back those deployment concepts from before:
* Memory
* Previous steps before starting
Up to this point, with all the tutorials in the docs, you have probably been running a **server program** like Uvicorn, running a **single process**.
Up to this point, with all the tutorials in the docs, you have probably been running a **server program**, for example, using the `fastapi` command, that runs Uvicorn, running a **single process**.
When deploying applications you will probably want to have some **replication of processes** to take advantage of **multiple cores** and to be able to handle more requests.
As you saw in the previous chapter about [Deployment Concepts](concepts.md){.internal-link target=_blank}, there are multiple strategies you can use.
Here I'll show you how to use <a href="https://gunicorn.org/" class="external-link" target="_blank">**Gunicorn**</a> with **Uvicorn worker processes**.
Here I'll show you how to use **Uvicorn** with **worker processes** using the `fastapi` command or the `uvicorn` command directly.
/// info
If you are using containers, for example with Docker or Kubernetes, I'll tell you more about that in the next chapter: [FastAPI in Containers - Docker](docker.md){.internal-link target=_blank}.
In particular, when running on **Kubernetes** you will probably **not** want to use Gunicorn and instead run **a single Uvicorn process per container**, but I'll tell you about it later in that chapter.
In particular, when running on **Kubernetes** you will probably **not** want to use workers and instead run **a single Uvicorn process per container**, but I'll tell you about it later in that chapter.
///
## Gunicorn with Uvicorn Workers
## Multiple Workers
**Gunicorn** is mainly an application server using the **WSGI standard**. That means that Gunicorn can serve applications like Flask and Django. Gunicorn by itself is not compatible with **FastAPI**, as FastAPI uses the newest **<a href="https://asgi.readthedocs.io/en/latest/" class="external-link" target="_blank">ASGI standard</a>**.
You can start multiple workers with the `--workers` command line option:
But Gunicorn supports working as a **process manager** and allowing users to tell it which specific **worker process class** to use. Then Gunicorn would start one or more **worker processes** using that class.
//// tab | `fastapi`
And **Uvicorn** has a **Gunicorn-compatible worker class**.
Using that combination, Gunicorn would act as a **process manager**, listening on the **port** and the **IP**. And it would **transmit** the communication to the worker processes running the **Uvicorn class**.
And then the Gunicorn-compatible **Uvicorn worker** class would be in charge of converting the data sent by Gunicorn to the ASGI standard for FastAPI to use it.
## Install Gunicorn and Uvicorn
If you use the `fastapi` command:
<div class="termy">
```console
$ pip install "uvicorn[standard]" gunicorn
---> 100%
$ <pre> <font color="#4E9A06">fastapi</font> run --workers 4 <u style="text-decoration-style:single">main.py</u>
<font color="#3465A4">INFO </font> Using path <font color="#3465A4">main.py</font>
<font color="#3465A4">INFO </font> Resolved absolute path <font color="#75507B">/home/user/code/awesomeapp/</font><font color="#AD7FA8">main.py</font>
<font color="#3465A4">INFO </font> Searching for package file structure from directories with <font color="#3465A4">__init__.py</font> files
<font color="#3465A4">INFO </font> Importing from <font color="#75507B">/home/user/code/</font><font color="#AD7FA8">awesomeapp</font>
╭─ <font color="#8AE234"><b>Python module file</b></font> ─╮
│ │
│ 🐍 main.py │
│ │
╰──────────────────────╯
<font color="#3465A4">INFO </font> Importing module <font color="#4E9A06">main</font>
<font color="#3465A4">INFO </font> Found importable FastAPI app
╭─ <font color="#8AE234"><b>Importable FastAPI app</b></font> ─╮
│ │
<span style="background-color:#272822"><font color="#FF4689">from</font></span><span style="background-color:#272822"><font color="#F8F8F2"> main </font></span><span style="background-color:#272822"><font color="#FF4689">import</font></span><span style="background-color:#272822"><font color="#F8F8F2"> app</font></span><span style="background-color:#272822"> </span>
│ │
╰──────────────────────────╯
<font color="#3465A4">INFO </font> Using import string <font color="#8AE234"><b>main:app</b></font>
<font color="#4E9A06">╭─────────── FastAPI CLI - Production mode ───────────╮</font>
<font color="#4E9A06">│ │</font>
<font color="#4E9A06">│ Serving at: http://0.0.0.0:8000 │</font>
<font color="#4E9A06">│ │</font>
<font color="#4E9A06">│ API docs: http://0.0.0.0:8000/docs │</font>
<font color="#4E9A06">│ │</font>
<font color="#4E9A06">│ Running in production mode, for development use: │</font>
<font color="#4E9A06">│ │</font>
<font color="#4E9A06"></font><font color="#8AE234"><b>fastapi dev</b></font><font color="#4E9A06"></font>
<font color="#4E9A06">│ │</font>
<font color="#4E9A06">╰─────────────────────────────────────────────────────╯</font>
<font color="#4E9A06">INFO</font>: Uvicorn running on <b>http://0.0.0.0:8000</b> (Press CTRL+C to quit)
<font color="#4E9A06">INFO</font>: Started parent process [<font color="#34E2E2"><b>27365</b></font>]
<font color="#4E9A06">INFO</font>: Started server process [<font color="#06989A">27368</font>]
<font color="#4E9A06">INFO</font>: Waiting for application startup.
<font color="#4E9A06">INFO</font>: Application startup complete.
<font color="#4E9A06">INFO</font>: Started server process [<font color="#06989A">27369</font>]
<font color="#4E9A06">INFO</font>: Waiting for application startup.
<font color="#4E9A06">INFO</font>: Application startup complete.
<font color="#4E9A06">INFO</font>: Started server process [<font color="#06989A">27370</font>]
<font color="#4E9A06">INFO</font>: Waiting for application startup.
<font color="#4E9A06">INFO</font>: Application startup complete.
<font color="#4E9A06">INFO</font>: Started server process [<font color="#06989A">27367</font>]
<font color="#4E9A06">INFO</font>: Waiting for application startup.
<font color="#4E9A06">INFO</font>: Application startup complete.
</pre>
```
</div>
That will install both Uvicorn with the `standard` extra packages (to get high performance) and Gunicorn.
## Run Gunicorn with Uvicorn Workers
Then you can run Gunicorn with:
<div class="termy">
```console
$ gunicorn main:app --workers 4 --worker-class uvicorn.workers.UvicornWorker --bind 0.0.0.0:80
[19499] [INFO] Starting gunicorn 20.1.0
[19499] [INFO] Listening at: http://0.0.0.0:80 (19499)
[19499] [INFO] Using worker: uvicorn.workers.UvicornWorker
[19511] [INFO] Booting worker with pid: 19511
[19513] [INFO] Booting worker with pid: 19513
[19514] [INFO] Booting worker with pid: 19514
[19515] [INFO] Booting worker with pid: 19515
[19511] [INFO] Started server process [19511]
[19511] [INFO] Waiting for application startup.
[19511] [INFO] Application startup complete.
[19513] [INFO] Started server process [19513]
[19513] [INFO] Waiting for application startup.
[19513] [INFO] Application startup complete.
[19514] [INFO] Started server process [19514]
[19514] [INFO] Waiting for application startup.
[19514] [INFO] Application startup complete.
[19515] [INFO] Started server process [19515]
[19515] [INFO] Waiting for application startup.
[19515] [INFO] Application startup complete.
```
</div>
Let's see what each of those options mean:
* `main:app`: This is the same syntax used by Uvicorn, `main` means the Python module named "`main`", so, a file `main.py`. And `app` is the name of the variable that is the **FastAPI** application.
* You can imagine that `main:app` is equivalent to a Python `import` statement like:
////
```Python
from main import app
```
//// tab | `uvicorn`
* So, the colon in `main:app` would be equivalent to the Python `import` part in `from main import app`.
* `--workers`: The number of worker processes to use, each will run a Uvicorn worker, in this case, 4 workers.
* `--worker-class`: The Gunicorn-compatible worker class to use in the worker processes.
* Here we pass the class that Gunicorn can import and use with:
```Python
import uvicorn.workers.UvicornWorker
```
* `--bind`: This tells Gunicorn the IP and the port to listen to, using a colon (`:`) to separate the IP and the port.
* If you were running Uvicorn directly, instead of `--bind 0.0.0.0:80` (the Gunicorn option) you would use `--host 0.0.0.0` and `--port 80`.
In the output, you can see that it shows the **PID** (process ID) of each process (it's just a number).
You can see that:
* The Gunicorn **process manager** starts with PID `19499` (in your case it will be a different number).
* Then it starts `Listening at: http://0.0.0.0:80`.
* Then it detects that it has to use the worker class at `uvicorn.workers.UvicornWorker`.
* And then it starts **4 workers**, each with its own PID: `19511`, `19513`, `19514`, and `19515`.
Gunicorn would also take care of managing **dead processes** and **restarting** new ones if needed to keep the number of workers. So that helps in part with the **restart** concept from the list above.
Nevertheless, you would probably also want to have something outside making sure to **restart Gunicorn** if necessary, and also to **run it on startup**, etc.
## Uvicorn with Workers
Uvicorn also has an option to start and run several **worker processes**.
Nevertheless, as of now, Uvicorn's capabilities for handling worker processes are more limited than Gunicorn's. So, if you want to have a process manager at this level (at the Python level), then it might be better to try with Gunicorn as the process manager.
In any case, you would run it like this:
If you prefer to use the `uvicorn` command directly:
<div class="termy">
@ -149,13 +118,15 @@ $ uvicorn main:app --host 0.0.0.0 --port 8080 --workers 4
</div>
////
The only new option here is `--workers` telling Uvicorn to start 4 worker processes.
You can also see that it shows the **PID** of each process, `27365` for the parent process (this is the **process manager**) and one for each worker process: `27368`, `27369`, `27370`, and `27367`.
## Deployment Concepts
Here you saw how to use **Gunicorn** (or Uvicorn) managing **Uvicorn worker processes** to **parallelize** the execution of the application, take advantage of **multiple cores** in the CPU, and be able to serve **more requests**.
Here you saw how to use multiple **workers** to **parallelize** the execution of the application, take advantage of **multiple cores** in the CPU, and be able to serve **more requests**.
From the list of deployment concepts from above, using workers would mainly help with the **replication** part, and a little bit with the **restarts**, but you still need to take care of the others:
@ -170,13 +141,11 @@ From the list of deployment concepts from above, using workers would mainly help
In the next chapter about [FastAPI in Containers - Docker](docker.md){.internal-link target=_blank} I'll tell some strategies you could use to handle the other **deployment concepts**.
I'll also show you the **official Docker image** that includes **Gunicorn with Uvicorn workers** and some default configurations that can be useful for simple cases.
There I'll also show you how to **build your own image from scratch** to run a single Uvicorn process (without Gunicorn). It is a simple process and is probably what you would want to do when using a distributed container management system like **Kubernetes**.
I'll show you how to **build your own image from scratch** to run a single Uvicorn process. It is a simple process and is probably what you would want to do when using a distributed container management system like **Kubernetes**.
## Recap
You can use **Gunicorn** (or also Uvicorn) as a process manager with Uvicorn workers to take advantage of **multi-core CPUs**, to run **multiple processes in parallel**.
You can use multiple worker processes with the `--workers` CLI option with the `fastapi` or `uvicorn` commands to take advantage of **multi-core CPUs**, to run **multiple processes in parallel**.
You could use these tools and ideas if you are setting up **your own deployment system** while taking care of the other deployment concepts yourself.

2
docs/en/docs/deployment/versions.md

@ -30,7 +30,7 @@ fastapi[standard]>=0.112.0,<0.113.0
that would mean that you would use the versions `0.112.0` or above, but less than `0.113.0`, for example, a version `0.112.2` would still be accepted.
If you use any other tool to manage your installations, like Poetry, Pipenv, or others, they all have a way that you can use to define specific versions for your packages.
If you use any other tool to manage your installations, like `uv`, Poetry, Pipenv, or others, they all have a way that you can use to define specific versions for your packages.
## Available versions

300
docs/en/docs/environment-variables.md

@ -0,0 +1,300 @@
# Environment Variables
/// tip
If you already know what "environment variables" are and how to use them, feel free to skip this.
///
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).
Environment variables could be useful for handling application **settings**, as part of the **installation** of Python, etc.
## Create and Use Env Vars
You can **create** and use environment variables in the **shell (terminal)**, without needing Python:
//// tab | Linux, macOS, Windows Bash
<div class="termy">
```console
// You could create an env var MY_NAME with
$ export MY_NAME="Wade Wilson"
// Then you could use it with other programs, like
$ echo "Hello $MY_NAME"
Hello Wade Wilson
```
</div>
////
//// tab | Windows PowerShell
<div class="termy">
```console
// Create an env var MY_NAME
$ $Env:MY_NAME = "Wade Wilson"
// Use it with other programs, like
$ echo "Hello $Env:MY_NAME"
Hello Wade Wilson
```
</div>
////
## Read env vars in Python
You could also create environment variables **outside** of Python, in the terminal (or with any other method), and then **read them in Python**.
For example you could have a file `main.py` with:
```Python hl_lines="3"
import os
name = os.getenv("MY_NAME", "World")
print(f"Hello {name} from Python")
```
/// tip
The second argument to <a href="https://docs.python.org/3.8/library/os.html#os.getenv" class="external-link" target="_blank">`os.getenv()`</a> is the default value to return.
If not provided, it's `None` by default, here we provide `"World"` as the default value to use.
///
Then you could call that Python program:
//// tab | Linux, macOS, Windows Bash
<div class="termy">
```console
// Here we don't set the env var yet
$ python main.py
// As we didn't set the env var, we get the default value
Hello World from Python
// But if we create an environment variable first
$ export MY_NAME="Wade Wilson"
// And then call the program again
$ python main.py
// Now it can read the environment variable
Hello Wade Wilson from Python
```
</div>
////
//// tab | Windows PowerShell
<div class="termy">
```console
// Here we don't set the env var yet
$ python main.py
// As we didn't set the env var, we get the default value
Hello World from Python
// But if we create an environment variable first
$ $Env:MY_NAME = "Wade Wilson"
// And then call the program again
$ python main.py
// Now it can read the environment variable
Hello Wade Wilson from Python
```
</div>
////
As environment variables can be set outside of the code, but can be read by the code, and don't have to be stored (committed to `git`) with the rest of the files, it's common to use them for configurations or **settings**.
You can also create an environment variable only for a **specific program invocation**, that is only available to that program, and only for its duration.
To do that, create it right before the program itself, on the same line:
<div class="termy">
```console
// Create an env var MY_NAME in line for this program call
$ MY_NAME="Wade Wilson" python main.py
// Now it can read the environment variable
Hello Wade Wilson from Python
// The env var no longer exists afterwards
$ python main.py
Hello World from Python
```
</div>
/// tip
You can read more about it at <a href="https://12factor.net/config" class="external-link" target="_blank">The Twelve-Factor App: Config</a>.
///
## Types and Validation
These environment variables can only handle **text strings**, as they are external to Python and have to be compatible with other programs and the rest of the system (and even with different operating systems, as Linux, Windows, macOS).
That means that **any value** read in Python from an environment variable **will be a `str`**, and any conversion to a different type or any validation has to be done in code.
You will learn more about using environment variables for handling **application settings** in the [Advanced User Guide - Settings and Environment Variables](./advanced/settings.md){.internal-link target=_blank}.
## `PATH` Environment Variable
There is a **special** environment variable called **`PATH`** that is used by the operating systems (Linux, macOS, Windows) to find programs to run.
The value of the variable `PATH` is a long string that is made of directories separated by a colon `:` on Linux and macOS, and by a semicolon `;` on Windows.
For example, the `PATH` environment variable could look like this:
//// tab | Linux, macOS
```plaintext
/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
```
This means that the system should look for programs in the directories:
* `/usr/local/bin`
* `/usr/bin`
* `/bin`
* `/usr/sbin`
* `/sbin`
////
//// tab | Windows
```plaintext
C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32
```
This means that the system should look for programs in the directories:
* `C:\Program Files\Python312\Scripts`
* `C:\Program Files\Python312`
* `C:\Windows\System32`
////
When you type a **command** in the terminal, the operating system **looks for** the program in **each of those directories** listed in the `PATH` environment variable.
For example, when you type `python` in the terminal, the operating system looks for a program called `python` in the **first directory** in that list.
If it finds it, then it will **use it**. Otherwise it keeps looking in the **other directories**.
### Installing Python and Updating the `PATH`
When you install Python, you might be asked if you want to update the `PATH` environment variable.
//// tab | Linux, macOS
Let's say you install Python and it ends up in a directory `/opt/custompython/bin`.
If you say yes to update the `PATH` environment variable, then the installer will add `/opt/custompython/bin` to the `PATH` environment variable.
It could look like this:
```plaintext
/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/custompython/bin
```
This way, when you type `python` in the terminal, the system will find the Python program in `/opt/custompython/bin` (the last directory) and use that one.
////
//// tab | Windows
Let's say you install Python and it ends up in a directory `C:\opt\custompython\bin`.
If you say yes to update the `PATH` environment variable, then the installer will add `C:\opt\custompython\bin` to the `PATH` environment variable.
```plaintext
C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32;C:\opt\custompython\bin
```
This way, when you type `python` in the terminal, the system will find the Python program in `C:\opt\custompython\bin` (the last directory) and use that one.
////
This way, when you type `python` in the terminal, the system will find the Python program in `/opt/custompython/bin` (the last directory) and use that one.
So, if you type:
<div class="termy">
```console
$ python
```
</div>
//// tab | Linux, macOS
The system will **find** the `python` program in `/opt/custompython/bin` and run it.
It would be roughly equivalent to typing:
<div class="termy">
```console
$ /opt/custompython/bin/python
```
</div>
////
//// tab | Windows
The system will **find** the `python` program in `C:\opt\custompython\bin\python` and run it.
It would be roughly equivalent to typing:
<div class="termy">
```console
$ C:\opt\custompython\bin\python
```
</div>
////
This information will be useful when learning about [Virtual Environments](virtual-environments.md){.internal-link target=_blank}.
## Conclusion
With this you should have a basic understanding of what **environment variables** are and how to use them in Python.
You can also read more about them in the <a href="https://en.wikipedia.org/wiki/Environment_variable" class="external-link" target="_blank">Wikipedia for Environment Variable</a>.
In many cases it's not very obvious how environment variables would be useful and applicable right away. But they keep showing up in many different scenarios when you are developing, so it's good to know about them.
For example, you will need this information in the next section, about [Virtual Environments](virtual-environments.md).

2
docs/en/docs/features.md

@ -6,7 +6,7 @@
### Based on open standards
* <a href="https://github.com/OAI/OpenAPI-Specification" class="external-link" target="_blank"><strong>OpenAPI</strong></a> for API creation, including declarations of <abbr title="also known as: endpoints, routes">path</abbr> <abbr title="also known as HTTP methods, as POST, GET, PUT, DELETE">operations</abbr>, parameters, body requests, security, etc.
* <a href="https://github.com/OAI/OpenAPI-Specification" class="external-link" target="_blank"><strong>OpenAPI</strong></a> for API creation, including declarations of <abbr title="also known as: endpoints, routes">path</abbr> <abbr title="also known as HTTP methods, as POST, GET, PUT, DELETE">operations</abbr>, parameters, request bodies, security, etc.
* Automatic data model documentation with <a href="https://json-schema.org/" class="external-link" target="_blank"><strong>JSON Schema</strong></a> (as OpenAPI itself is based on JSON Schema).
* Designed around these standards, after a meticulous study. Instead of an afterthought layer on top.
* This also allows using automatic **client code generation** in many languages.

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

@ -66,7 +66,7 @@ I love to hear about how **FastAPI** is being used, what you have liked in it, i
## Vote for FastAPI
* <a href="https://www.slant.co/options/34241/~fastapi-review" class="external-link" target="_blank">Vote for **FastAPI** in Slant</a>.
* <a href="https://alternativeto.net/software/fastapi/" class="external-link" target="_blank">Vote for **FastAPI** in AlternativeTo</a>.
* <a href="https://alternativeto.net/software/fastapi/about/" class="external-link" target="_blank">Vote for **FastAPI** in AlternativeTo</a>.
* <a href="https://stackshare.io/pypi-fastapi" class="external-link" target="_blank">Say you use **FastAPI** on StackShare</a>.
## Help others with questions in GitHub

6
docs/en/docs/index.md

@ -128,6 +128,8 @@ FastAPI stands on the shoulders of giants:
## Installation
Create and activate a <a href="https://fastapi.tiangolo.com/virtual-environments/" class="external-link" target="_blank">virtual environment</a> and then install FastAPI:
<div class="termy">
```console
@ -388,7 +390,7 @@ Coming back to the previous code example, **FastAPI** will:
* Check if there is an optional query parameter named `q` (as in `http://127.0.0.1:8000/items/foo?q=somequery`) for `GET` requests.
* As the `q` parameter is declared with `= None`, it is optional.
* Without the `None` it would be required (as is the body in the case with `PUT`).
* For `PUT` requests to `/items/{item_id}`, Read the body as JSON:
* For `PUT` requests to `/items/{item_id}`, read the body as JSON:
* Check that it has a required attribute `name` that should be a `str`.
* Check that it has a required attribute `price` that has to be a `float`.
* Check that it has an optional attribute `is_offer`, that should be a `bool`, if present.
@ -458,7 +460,7 @@ When you install FastAPI with `pip install "fastapi[standard]"` it comes the `st
Used by Pydantic:
* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email_validator</code></a> - for email validation.
* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email-validator</code></a> - for email validation.
Used by Starlette:

2
docs/en/docs/management-tasks.md

@ -113,7 +113,7 @@ For the other languages, confirm that:
* The title is correct following the instructions above.
* It has the labels `lang-all` and `lang-{lang code}`.
* The PR changes only one Markdown file adding a translation.
* Or in some cases, at most two files, if they are small and people reviewed them.
* Or in some cases, at most two files, if they are small, for the same language, and people reviewed them.
* If it's the first translation for that language, it will have additional `mkdocs.yml` files, for those cases follow the instructions below.
* The PR doesn't add any additional or extraneous files.
* The translation seems to have a similar structure as the original English file.

1
docs/en/docs/project-generation.md

@ -16,6 +16,7 @@ GitHub Repository: <a href="https://github.com/tiangolo/full-stack-fastapi-templ
- 💃 Using TypeScript, hooks, Vite, and other parts of a modern frontend stack.
- 🎨 [Chakra UI](https://chakra-ui.com) for the frontend components.
- 🤖 An automatically generated frontend client.
- 🧪 Playwright for End-to-End testing.
- 🦇 Dark mode support.
- 🐋 [Docker Compose](https://www.docker.com) for development and production.
- 🔒 Secure password hashing by default.

4
docs/en/docs/python-types.md

@ -324,7 +324,7 @@ In Python 3.6 and above (including Python 3.10) you can declare it by importing
{!../../../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.
Using `Optional[str]` 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.
`Optional[Something]` is actually a shortcut for `Union[Something, None]`, they are equivalent.
@ -519,7 +519,7 @@ You will see a lot more of all this in practice in the [Tutorial - User Guide](t
/// 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 <a href="https://docs.pydantic.dev/latest/concepts/models/#required-optional-fields" class="external-link" target="_blank">Required Optional fields</a>.
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 <a href="https://docs.pydantic.dev/2.3/usage/models/#required-fields" class="external-link" target="_blank">Required Optional fields</a>.
///

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

@ -9,10 +9,88 @@ hide:
### Docs
* 📝 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
* 🌐 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 [#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
### 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
### 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).
@ -23,6 +101,19 @@ hide:
### 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).

2
docs/en/docs/tutorial/background-tasks.md

@ -9,7 +9,7 @@ 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`

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

@ -1,6 +1,6 @@
# 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.
@ -478,7 +478,7 @@ We can declare all that without having to modify the original `APIRouter` by pas
{!../../../docs_src/bigger_applications/app/main.py!}
```
That way, the original `APIRouter` will keep unmodified, so we can still share that same `app/internal/admin.py` file with other projects in the organization.
That way, the original `APIRouter` will stay unmodified, so we can still share that same `app/internal/admin.py` file with other projects in the organization.
The result is that in our app, each of the *path operations* from the `admin` module will have:
@ -519,12 +519,12 @@ As we cannot just isolate them and "mount" them independently of the rest, the *
## Check the automatic API docs
Now, run `uvicorn`, using the module `app.main` and the variable `app`:
Now, run your app:
<div class="termy">
```console
$ uvicorn app.main:app --reload
$ fastapi dev app/main.py
<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
```

12
docs/en/docs/tutorial/body-multiple-params.md

@ -97,7 +97,7 @@ But you can also declare multiple body parameters, e.g. `item` and `user`:
////
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:
@ -228,7 +228,7 @@ For example:
//// tab | Python 3.10+
```Python hl_lines="27"
```Python hl_lines="28"
{!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!}
```
@ -236,7 +236,7 @@ For example:
//// tab | Python 3.9+
```Python hl_lines="27"
```Python hl_lines="28"
{!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!}
```
@ -244,7 +244,7 @@ For example:
//// tab | Python 3.8+
```Python hl_lines="28"
```Python hl_lines="29"
{!> ../../../docs_src/body_multiple_params/tutorial004_an.py!}
```
@ -258,7 +258,7 @@ Prefer to use the `Annotated` version if possible.
///
```Python hl_lines="25"
```Python hl_lines="26"
{!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!}
```
@ -272,7 +272,7 @@ Prefer to use the `Annotated` version if possible.
///
```Python hl_lines="27"
```Python hl_lines="28"
{!> ../../../docs_src/body_multiple_params/tutorial004.py!}
```

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

@ -220,7 +220,7 @@ Again, doing just that declaration, with **FastAPI** you get:
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 <a href="https://docs.pydantic.dev/latest/concepts/types/" class="external-link" target="_blank">Pydantic's exotic types</a>. You will see some examples in the next chapter.
To see all the options you have, checkout <a href="https://docs.pydantic.dev/latest/concepts/types/" class="external-link" target="_blank">Pydantic's Type Overview</a>. 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 an instance of Pydantic's `HttpUrl` instead of a `str`:

2
docs/en/docs/tutorial/body-updates.md

@ -155,7 +155,7 @@ 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 `.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.

8
docs/en/docs/tutorial/body.md

@ -4,7 +4,7 @@ When you need to send data from a client (let's say, a browser) to your API, you
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 <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> models with all their power and benefits.
@ -123,7 +123,7 @@ The JSON Schemas of your models will be part of your OpenAPI generated schema, a
<img src="/img/tutorial/body/image01.png">
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:
<img src="/img/tutorial/body/image02.png">
@ -237,7 +237,9 @@ The function parameters will be recognized as follows:
FastAPI will know that the value of `q` is not required because of the default value `= None`.
The `Union` in `Union[str, None]` is not used by FastAPI, but will allow your editor to give you better support and detect errors.
The `str | None` (Python 3.10+) or `Union` in `Union[str, None]` (Python 3.8+) 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.
///

2
docs/en/docs/tutorial/cookie-params.md

@ -62,7 +62,7 @@ Prefer to use the `Annotated` version if possible.
Then declare the cookie parameters using the same structure as with `Path` and `Query`.
The first value is the default value, you can pass all the extra validation or annotation parameters:
You can define the default value as well as all the extra validation or annotation parameters:
//// tab | Python 3.10+

8
docs/en/docs/tutorial/cors.md

@ -18,11 +18,11 @@ Even if they are all in `localhost`, they use different protocols or ports, so,
So, let's say you have a frontend running in your browser at `http://localhost:8080`, and its JavaScript is trying to communicate with a backend running at `http://localhost` (because we don't specify a port, the browser will assume the default port `80`).
Then, the browser will send an HTTP `OPTIONS` request to the backend, and if the backend sends the appropriate headers authorizing the communication from this different origin (`http://localhost:8080`) then the browser will let the JavaScript in the frontend send its request to the backend.
Then, the browser will send an HTTP `OPTIONS` request to the `:80`-backend, and if the backend sends the appropriate headers authorizing the communication from this different origin (`http://localhost:8080`) then the `:8080`-browser will let the JavaScript in the frontend send its request to the `:80`-backend.
To achieve this, the backend must have a list of "allowed origins".
To achieve this, the `:80`-backend must have a list of "allowed origins".
In this case, it would have to include `http://localhost:8080` for the frontend to work correctly.
In this case, the list would have to include `http://localhost:8080` for the `:8080`-frontend to work correctly.
## Wildcards
@ -40,7 +40,7 @@ You can configure it in your **FastAPI** application using the `CORSMiddleware`.
* Create a list of allowed origins (as strings).
* Add it as a "middleware" to your **FastAPI** application.
You can also specify if your backend allows:
You can also specify whether your backend allows:
* Credentials (Authorization headers, Cookies, etc).
* Specific HTTP methods (`POST`, `PUT`) or all of them with the wildcard `"*"`.

2
docs/en/docs/tutorial/dependencies/classes-as-dependencies.md

@ -381,7 +381,7 @@ The last `CommonQueryParams`, in:
...is what **FastAPI** will actually use to know what is the dependency.
From it is that FastAPI will extract the declared parameters and that is what FastAPI will actually call.
It is from this one that FastAPI will extract the declared parameters and that is what FastAPI will actually call.
---

2
docs/en/docs/tutorial/dependencies/dependencies-with-yield.md

@ -6,7 +6,7 @@ To do this, use `yield` instead of `return`, and write the extra steps (code) af
/// tip
Make sure to use `yield` one single time.
Make sure to use `yield` one single time per dependency.
///

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

@ -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", <a href="https://docs.pydantic.dev/latest/concepts/serialization/#json_encoders" class="external-link" target="_blank">see the docs for more info</a>.
* Pydantic also allows representing it as a "ISO 8601 time diff encoding", <a href="https://docs.pydantic.dev/latest/concepts/serialization/#custom-serializers" class="external-link" target="_blank">see the docs for more info</a>.
* `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,7 +49,7 @@ 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: <a href="https://docs.pydantic.dev/latest/usage/types/types/" class="external-link" target="_blank">Pydantic data types</a>.
* You can check all the valid Pydantic data types here: <a href="https://docs.pydantic.dev/latest/usage/types/types/" class="external-link" target="_blank">Pydantic data types</a>.
## Example

6
docs/en/docs/tutorial/extra-models.md

@ -156,7 +156,7 @@ 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.
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.
///
@ -194,7 +194,7 @@ That way, we can declare just the differences between the models (with plaintext
## `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`.
@ -234,7 +234,7 @@ 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

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

@ -176,7 +176,7 @@ These are technical details that you might skip if it's not important for you no
**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.
But the client/user will not see it. Instead, the client will receive an "Internal Server Error" with a HTTP status code `500`.
But the client/user will not see it. Instead, the client will receive an "Internal Server Error" with an HTTP status code `500`.
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.
@ -262,7 +262,7 @@ from starlette.exceptions import HTTPException as StarletteHTTPException
### Reuse **FastAPI**'s 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`:
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!}

2
docs/en/docs/tutorial/header-params.md

@ -62,7 +62,7 @@ Prefer to use the `Annotated` version if possible.
Then declare the header parameters using the same structure as with `Path`, `Query` and `Cookie`.
The first value is the default value, you can pass all the extra validation or annotation parameters:
You can define the default value as well as all the extra validation or annotation parameters:
//// tab | Python 3.10+

10
docs/en/docs/tutorial/index.md

@ -4,9 +4,7 @@ This tutorial shows you how to use **FastAPI** with most of its features, step b
Each section gradually builds on the previous ones, but it's structured to separate topics, so that you can go directly to any specific one to solve your specific API needs.
It is also built to work as a future reference.
So you can come back and see exactly what you need.
It is also built to work as a future reference so you can come back and see exactly what you need.
## Run the code
@ -71,7 +69,9 @@ Using it in your editor is what really shows you the benefits of FastAPI, seeing
## Install FastAPI
The first step is to install FastAPI:
The first step is to install FastAPI.
Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then **install FastAPI**:
<div class="termy">
@ -95,7 +95,7 @@ If you don't want to have those optional dependencies, you can instead install `
There is also an **Advanced User Guide** that you can read later after this **Tutorial - User guide**.
The **Advanced User Guide**, builds on this, uses the same concepts, and teaches you some extra features.
The **Advanced User Guide** builds on this one, uses the same concepts, and teaches you some extra features.
But you should first read the **Tutorial - User Guide** (what you are reading right now).

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

@ -29,7 +29,7 @@ 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!}

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

@ -155,7 +155,7 @@ FastAPI will now:
* Show a **clear error** for the client when the data is not valid
* **Document** the parameter in the OpenAPI schema *path operation* (so it will show up in the **automatic docs UI**)
## Alternative (old) `Query` as the default value
## Alternative (old): `Query` as the default value
Previous versions of FastAPI (before <abbr title="before 2023-03">0.95.0</abbr>) required you to use `Query` as the default value of your parameter, instead of putting it in `Annotated`, there's a high chance that you will see code using it around, so I'll explain it to you.
@ -209,7 +209,7 @@ q: str | None = Query(default=None)
q: str | None = None
```
But it declares it explicitly as being a query parameter.
But the `Query` versions declare it explicitly as being a query parameter.
/// info
@ -273,7 +273,7 @@ The **default** value of the **function parameter** is the **actual default** va
You could **call** that same function in **other places** without FastAPI, and it would **work as expected**. If there's a **required** parameter (without a default value), your **editor** will let you know with an error, **Python** will also complain if you run it without passing the required parameter.
When you don't use `Annotated` and instead use the **(old) default value style**, if you call that function without FastAPI in **other place**, you have to **remember** to pass the arguments to the function for it to work correctly, otherwise the values will be different from what you expect (e.g. `QueryInfo` or something similar instead of `str`). And your editor won't complain, and Python won't complain running that function, only when the operations inside error out.
When you don't use `Annotated` and instead use the **(old) default value style**, if you call that function without FastAPI in **other places**, you have to **remember** to pass the arguments to the function for it to work correctly, otherwise the values will be different from what you expect (e.g. `QueryInfo` or something similar instead of `str`). And your editor won't complain, and Python won't complain running that function, only when the operations inside error out.
Because `Annotated` can have more than one metadata annotation, you could now even use the same function with other tools, like <a href="https://typer.tiangolo.com/" class="external-link" target="_blank">Typer</a>. 🚀
@ -457,7 +457,7 @@ Having a default value of any type, including `None`, makes the parameter option
///
## Make it required
## Required parameters
When we don't need to declare more validations or metadata, we can make the `q` query parameter required just by not declaring a default value, like:
@ -573,7 +573,7 @@ It is used by Pydantic and FastAPI to explicitly declare that a value is require
This will let **FastAPI** know that this parameter is required.
### Required with `None`
### Required, can be `None`
You can declare that a parameter can accept `None`, but that it's still required. This would force clients to send a value, even if the value is `None`.
@ -633,7 +633,7 @@ Prefer to use the `Annotated` version if possible.
/// tip
Pydantic, which is what powers all the data validation and serialization in FastAPI, has a special behavior when you use `Optional` or `Union[Something, None]` without a default value, you can read more about it in the Pydantic docs about <a href="https://docs.pydantic.dev/latest/concepts/models/#required-optional-fields" class="external-link" target="_blank">Required Optional fields</a>.
Pydantic, which is what powers all the data validation and serialization in FastAPI, has a special behavior when you use `Optional` or `Union[Something, None]` without a default value, you can read more about it in the Pydantic docs about <a href="https://docs.pydantic.dev/2.3/usage/models/#required-optional-fields" class="external-link" target="_blank">Required fields</a>.
///
@ -645,7 +645,7 @@ Remember that in most of the cases, when something is required, you can simply o
## Query parameter list / multiple values
When you define a query parameter explicitly with `Query` you can also declare it to receive a list of values, or said in other way, to receive multiple values.
When you define a query parameter explicitly with `Query` you can also declare it to receive a list of values, or said in another way, to receive multiple values.
For example, to declare a query parameter `q` that can appear multiple times in the URL, you can write:
@ -809,7 +809,7 @@ the default of `q` will be: `["foo", "bar"]` and your response will be:
}
```
#### Using `list`
#### Using just `list`
You can also use `list` directly instead of `List[str]` (or `list[str]` in Python 3.9+):
@ -1107,7 +1107,7 @@ The docs will show it like this:
<img src="/img/tutorial/query-params-str-validations/image01.png">
## Exclude from OpenAPI
## Exclude parameters from OpenAPI
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`:
@ -1182,4 +1182,4 @@ Validations specific for strings:
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.

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

@ -6,7 +6,11 @@ You can define files to be uploaded by the client using `File`.
To receive uploaded files, first install <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>.
E.g. `pip install python-multipart`.
Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install it, for example:
```console
$ pip install python-multipart
```
This is because uploaded files are sent as "form data".
@ -152,7 +156,7 @@ Using `UploadFile` has several advantages over `bytes`:
* `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 <a href="https://docs.python.org/3/library/tempfile.html#tempfile.SpooledTemporaryFile" class="external-link" target="_blank">`SpooledTemporaryFile`</a> (a <a href="https://docs.python.org/3/glossary.html#term-file-like-object" class="external-link" target="_blank">file-like</a> 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 <a href="https://docs.python.org/3/library/tempfile.html#tempfile.SpooledTemporaryFile" class="external-link" target="_blank">`SpooledTemporaryFile`</a> (a <a href="https://docs.python.org/3/glossary.html#term-file-like-object" class="external-link" target="_blank">file-like</a> 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`).

6
docs/en/docs/tutorial/request-forms-and-files.md

@ -6,7 +6,11 @@ You can define files and form fields at the same time using `File` and `Form`.
To receive uploaded files and/or form data, first install <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>.
E.g. `pip install python-multipart`.
Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install it, for example:
```console
$ pip install python-multipart
```
///

6
docs/en/docs/tutorial/request-forms.md

@ -6,7 +6,11 @@ When you need to receive form fields instead of JSON, you can use `Form`.
To use forms, first install <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>.
E.g. `pip install python-multipart`.
Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install it, for example:
```console
$ pip install python-multipart
```
///

25
docs/en/docs/tutorial/response-model.md

@ -131,10 +131,19 @@ Here we are declaring a `UserIn` model, it will contain a plaintext password:
/// info
To use `EmailStr`, first install <a href="https://github.com/JoshData/python-email-validator" class="external-link" target="_blank">`email_validator`</a>.
To use `EmailStr`, first install <a href="https://github.com/JoshData/python-email-validator" class="external-link" target="_blank">`email-validator`</a>.
E.g. `pip install email-validator`
or `pip install pydantic[email]`.
Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install it, for example:
```console
$ pip install email-validator
```
or with:
```console
$ pip install "pydantic[email]"
```
///
@ -236,9 +245,9 @@ That's why in this example we have to declare it in the `response_model` paramet
## 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.
@ -306,7 +315,7 @@ The most common case would be [returning a Response directly as explained later
{!> ../../../docs_src/response_model/tutorial003_02.py!}
```
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.
@ -455,7 +464,7 @@ The examples here use `.dict()` for compatibility with Pydantic v1, but you shou
/// info
FastAPI uses Pydantic model's `.dict()` with <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">its `exclude_unset` parameter</a> to achieve this.
FastAPI uses Pydantic model's `.dict()` with <a href="https://docs.pydantic.dev/1.10/usage/exporting_models/#modeldict" class="external-link" target="_blank">its `exclude_unset` parameter</a> to achieve this.
///
@ -466,7 +475,7 @@ You can also use:
* `response_model_exclude_defaults=True`
* `response_model_exclude_none=True`
as described in <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">the Pydantic docs</a> for `exclude_defaults` and `exclude_none`.
as described in <a href="https://docs.pydantic.dev/1.10/usage/exporting_models/#modeldict" class="external-link" target="_blank">the Pydantic docs</a> for `exclude_defaults` and `exclude_none`.
///

4
docs/en/docs/tutorial/schema-extra-example.md

@ -44,7 +44,7 @@ That extra info will be added as-is to the output **JSON Schema** for that model
//// tab | Pydantic v2
In Pydantic version 2, you would use the attribute `model_config`, that takes a `dict` as described in <a href="https://docs.pydantic.dev/latest/usage/model_config/" class="external-link" target="_blank">Pydantic's docs: Model Config</a>.
In Pydantic version 2, you would use the attribute `model_config`, that takes a `dict` as described in <a href="https://docs.pydantic.dev/latest/api/config/" class="external-link" target="_blank">Pydantic's docs: Configuration</a>.
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`.
@ -347,7 +347,7 @@ If the ideas above already work for you, that might be enough, and you probably
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:

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

Loading…
Cancel
Save