diff --git a/.github/ISSUE_TEMPLATE/feature-request.yml b/.github/ISSUE_TEMPLATE/feature-request.yml
index 8176602a75f40..322b6536a760c 100644
--- a/.github/ISSUE_TEMPLATE/feature-request.yml
+++ b/.github/ISSUE_TEMPLATE/feature-request.yml
@@ -8,9 +8,9 @@ body:
Thanks for your interest in FastAPI! 🚀
Please follow these instructions, fill every question, and do every step. 🙏
-
+
I'm asking this because answering questions and solving problems in GitHub issues is what consumes most of the time.
-
+
I end up not being able to add new features, fix bugs, review pull requests, etc. as fast as I wish because I have to spend too much time handling issues.
All that, on top of all the incredible help provided by a bunch of community members, the [FastAPI Experts](https://fastapi.tiangolo.com/fastapi-people/#experts), that give a lot of their time to come here and help others.
@@ -18,7 +18,7 @@ body:
That's a lot of work they are doing, but if more FastAPI users came to help others like them just a little bit more, it would be much less effort for them (and you and me 😅).
By asking questions in a structured way (following this) it will be much easier to help you.
-
+
And there's a high chance that you will find the solution along the way and you won't even have to submit it and wait for an answer. 😎
As there are too many issues with questions, I'll have to close the incomplete ones. That will allow me (and others) to focus on helping people like you that follow the whole process and help us help you. 🤓
@@ -50,7 +50,7 @@ body:
label: Commit to Help
description: |
After submitting this, I commit to one of:
-
+
* Read open issues with questions until I find 2 issues where I can help someone and add a comment to help there.
* I already hit the "watch" button in this repository to receive notifications and I commit to help at least 2 people that ask questions in the future.
* Implement a Pull Request for a confirmed bug.
diff --git a/.github/ISSUE_TEMPLATE/question.yml b/.github/ISSUE_TEMPLATE/question.yml
index 5c76fd17eff15..3b16b4ad0c156 100644
--- a/.github/ISSUE_TEMPLATE/question.yml
+++ b/.github/ISSUE_TEMPLATE/question.yml
@@ -8,9 +8,9 @@ body:
Thanks for your interest in FastAPI! 🚀
Please follow these instructions, fill every question, and do every step. 🙏
-
+
I'm asking this because answering questions and solving problems in GitHub issues is what consumes most of the time.
-
+
I end up not being able to add new features, fix bugs, review pull requests, etc. as fast as I wish because I have to spend too much time handling issues.
All that, on top of all the incredible help provided by a bunch of community members, the [FastAPI Experts](https://fastapi.tiangolo.com/fastapi-people/#experts), that give a lot of their time to come here and help others.
@@ -18,7 +18,7 @@ body:
That's a lot of work they are doing, but if more FastAPI users came to help others like them just a little bit more, it would be much less effort for them (and you and me 😅).
By asking questions in a structured way (following this) it will be much easier to help you.
-
+
And there's a high chance that you will find the solution along the way and you won't even have to submit it and wait for an answer. 😎
As there are too many issues with questions, I'll have to close the incomplete ones. That will allow me (and others) to focus on helping people like you that follow the whole process and help us help you. 🤓
@@ -50,7 +50,7 @@ body:
label: Commit to Help
description: |
After submitting this, I commit to one of:
-
+
* Read open issues with questions until I find 2 issues where I can help someone and add a comment to help there.
* I already hit the "watch" button in this repository to receive notifications and I commit to help at least 2 people that ask questions in the future.
* Implement a Pull Request for a confirmed bug.
diff --git a/.github/actions/comment-docs-preview-in-pr/app/main.py b/.github/actions/comment-docs-preview-in-pr/app/main.py
index 3b10e0ee089e1..68914fdb9a818 100644
--- a/.github/actions/comment-docs-preview-in-pr/app/main.py
+++ b/.github/actions/comment-docs-preview-in-pr/app/main.py
@@ -1,7 +1,7 @@
import logging
import sys
from pathlib import Path
-from typing import Optional
+from typing import Union
import httpx
from github import Github
@@ -14,7 +14,7 @@
class Settings(BaseSettings):
github_repository: str
github_event_path: Path
- github_event_name: Optional[str] = None
+ github_event_name: Union[str, None] = None
input_token: SecretStr
input_deploy_url: str
@@ -42,15 +42,13 @@ class PartialGithubEvent(BaseModel):
except ValidationError as e:
logging.error(f"Error parsing event file: {e.errors()}")
sys.exit(0)
- use_pr: Optional[PullRequest] = None
+ use_pr: Union[PullRequest, None] = None
for pr in repo.get_pulls():
if pr.head.sha == event.workflow_run.head_commit.id:
use_pr = pr
break
if not use_pr:
- logging.error(
- f"No PR found for hash: {event.workflow_run.head_commit.id}"
- )
+ logging.error(f"No PR found for hash: {event.workflow_run.head_commit.id}")
sys.exit(0)
github_headers = {
"Authorization": f"token {settings.input_token.get_secret_value()}"
diff --git a/.github/actions/notify-translations/app/main.py b/.github/actions/notify-translations/app/main.py
index 7d6c1a4d20a7f..d4ba0ecfce090 100644
--- a/.github/actions/notify-translations/app/main.py
+++ b/.github/actions/notify-translations/app/main.py
@@ -1,8 +1,8 @@
import logging
+import random
import time
from pathlib import Path
-import random
-from typing import Dict, Optional
+from typing import Dict, Union
import yaml
from github import Github
@@ -18,8 +18,8 @@ class Settings(BaseSettings):
github_repository: str
input_token: SecretStr
github_event_path: Path
- github_event_name: Optional[str] = None
- input_debug: Optional[bool] = False
+ github_event_name: Union[str, None] = None
+ input_debug: Union[bool, None] = False
class PartialGitHubEventIssue(BaseModel):
@@ -54,7 +54,7 @@ class PartialGitHubEvent(BaseModel):
)
if pr.state == "open":
logging.debug(f"PR is open: {pr.number}")
- label_strs = set([label.name for label in pr.get_labels()])
+ label_strs = {label.name for label in pr.get_labels()}
if lang_all_label in label_strs and awaiting_label in label_strs:
logging.info(
f"This PR seems to be a language translation and awaiting reviews: {pr.number}"
diff --git a/.github/actions/notify-translations/app/translations.yml b/.github/actions/notify-translations/app/translations.yml
index 0e5093f3acd0b..d283ef9f7f280 100644
--- a/.github/actions/notify-translations/app/translations.yml
+++ b/.github/actions/notify-translations/app/translations.yml
@@ -8,10 +8,12 @@ uk: 1748
tr: 1892
fr: 1972
ko: 2017
-sq: 2041
+fa: 2041
pl: 3169
de: 3716
id: 3717
az: 3994
nl: 4701
uz: 4883
+sv: 5146
+he: 5157
diff --git a/.github/actions/people/app/main.py b/.github/actions/people/app/main.py
index 0b6ff4063c898..1455d01caeee5 100644
--- a/.github/actions/people/app/main.py
+++ b/.github/actions/people/app/main.py
@@ -4,7 +4,7 @@
from collections import Counter, defaultdict
from datetime import datetime, timedelta, timezone
from pathlib import Path
-from typing import Container, DefaultDict, Dict, List, Optional, Set
+from typing import Container, DefaultDict, Dict, List, Set, Union
import httpx
import yaml
@@ -14,7 +14,7 @@
github_graphql_url = "https://api.github.com/graphql"
issues_query = """
-query Q($after: String) {
+query Q($after: String) {
repository(name: "fastapi", owner: "tiangolo") {
issues(first: 100, after: $after) {
edges {
@@ -47,7 +47,7 @@
"""
prs_query = """
-query Q($after: String) {
+query Q($after: String) {
repository(name: "fastapi", owner: "tiangolo") {
pullRequests(first: 100, after: $after) {
edges {
@@ -133,7 +133,7 @@ class Author(BaseModel):
class CommentsNode(BaseModel):
createdAt: datetime
- author: Optional[Author] = None
+ author: Union[Author, None] = None
class Comments(BaseModel):
@@ -142,7 +142,7 @@ class Comments(BaseModel):
class IssuesNode(BaseModel):
number: int
- author: Optional[Author] = None
+ author: Union[Author, None] = None
title: str
createdAt: datetime
state: str
@@ -179,7 +179,7 @@ class Labels(BaseModel):
class ReviewNode(BaseModel):
- author: Optional[Author] = None
+ author: Union[Author, None] = None
state: str
@@ -190,7 +190,7 @@ class Reviews(BaseModel):
class PullRequestNode(BaseModel):
number: int
labels: Labels
- author: Optional[Author] = None
+ author: Union[Author, None] = None
title: str
createdAt: datetime
state: str
@@ -263,7 +263,7 @@ class Settings(BaseSettings):
def get_graphql_response(
- *, settings: Settings, query: str, after: Optional[str] = None
+ *, settings: Settings, query: str, after: Union[str, None] = None
):
headers = {"Authorization": f"token {settings.input_token.get_secret_value()}"}
variables = {"after": after}
@@ -280,19 +280,19 @@ def get_graphql_response(
return data
-def get_graphql_issue_edges(*, settings: Settings, after: Optional[str] = None):
+def get_graphql_issue_edges(*, settings: Settings, after: Union[str, None] = None):
data = get_graphql_response(settings=settings, query=issues_query, after=after)
graphql_response = IssuesResponse.parse_obj(data)
return graphql_response.data.repository.issues.edges
-def get_graphql_pr_edges(*, settings: Settings, after: Optional[str] = None):
+def get_graphql_pr_edges(*, settings: Settings, after: Union[str, None] = None):
data = get_graphql_response(settings=settings, query=prs_query, after=after)
graphql_response = PRsResponse.parse_obj(data)
return graphql_response.data.repository.pullRequests.edges
-def get_graphql_sponsor_edges(*, settings: Settings, after: Optional[str] = None):
+def get_graphql_sponsor_edges(*, settings: Settings, after: Union[str, None] = None):
data = get_graphql_response(settings=settings, query=sponsors_query, after=after)
graphql_response = SponsorsResponse.parse_obj(data)
return graphql_response.data.user.sponsorshipsAsMaintainer.edges
diff --git a/.github/actions/watch-previews/app/main.py b/.github/actions/watch-previews/app/main.py
index 3b3520599c797..51285d02b879d 100644
--- a/.github/actions/watch-previews/app/main.py
+++ b/.github/actions/watch-previews/app/main.py
@@ -1,7 +1,7 @@
import logging
from datetime import datetime
from pathlib import Path
-from typing import List, Optional
+from typing import List, Union
import httpx
from github import Github
@@ -16,7 +16,7 @@ class Settings(BaseSettings):
input_token: SecretStr
github_repository: str
github_event_path: Path
- github_event_name: Optional[str] = None
+ github_event_name: Union[str, None] = None
class Artifact(BaseModel):
@@ -74,7 +74,7 @@ def get_message(commit: str) -> str:
logging.info(f"Docs preview was notified: {notified}")
if not notified:
artifact_name = f"docs-zip-{commit}"
- use_artifact: Optional[Artifact] = None
+ use_artifact: Union[Artifact, None] = None
for artifact in artifacts_response.artifacts:
if artifact.name == artifact_name:
use_artifact = artifact
diff --git a/.github/dependabot.yml b/.github/dependabot.yml
new file mode 100644
index 0000000000000..cd972a0ba4722
--- /dev/null
+++ b/.github/dependabot.yml
@@ -0,0 +1,16 @@
+version: 2
+updates:
+ # GitHub Actions
+ - package-ecosystem: "github-actions"
+ directory: "/"
+ schedule:
+ interval: "daily"
+ commit-message:
+ prefix: ⬆
+ # Python
+ - package-ecosystem: "pip"
+ directory: "/"
+ schedule:
+ interval: "daily"
+ commit-message:
+ prefix: ⬆
diff --git a/.github/workflows/build-docs.yml b/.github/workflows/build-docs.yml
index 2482660f3bdca..0d666b82a8a45 100644
--- a/.github/workflows/build-docs.yml
+++ b/.github/workflows/build-docs.yml
@@ -13,16 +13,16 @@ jobs:
env:
GITHUB_CONTEXT: ${{ toJson(github) }}
run: echo "$GITHUB_CONTEXT"
- - uses: actions/checkout@v2
+ - uses: actions/checkout@v3
- name: Set up Python
- uses: actions/setup-python@v2
+ uses: actions/setup-python@v4
with:
python-version: "3.7"
- - uses: actions/cache@v2
+ - uses: actions/cache@v3
id: cache
with:
path: ${{ env.pythonLocation }}
- key: ${{ runner.os }}-python-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml') }}-docs-v2
+ key: ${{ runner.os }}-python-docs-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml') }}-v03
- name: Install Flit
if: steps.cache.outputs.cache-hit != 'true'
run: python3.7 -m pip install flit
@@ -30,18 +30,18 @@ jobs:
if: steps.cache.outputs.cache-hit != 'true'
run: python3.7 -m flit install --deps production --extras doc
- name: Install Material for MkDocs Insiders
- if: github.event.pull_request.head.repo.fork == false && steps.cache.outputs.cache-hit != 'true'
+ if: ( github.event_name != 'pull_request' || github.event.pull_request.head.repo.fork == false ) && steps.cache.outputs.cache-hit != 'true'
run: pip install git+https://${{ secrets.ACTIONS_TOKEN }}@github.com/squidfunk/mkdocs-material-insiders.git
- name: Build Docs
run: python3.7 ./scripts/docs.py build-all
- name: Zip docs
run: bash ./scripts/zip-docs.sh
- - uses: actions/upload-artifact@v2
+ - uses: actions/upload-artifact@v3
with:
name: docs-zip
path: ./docs.zip
- name: Deploy to Netlify
- uses: nwtgck/actions-netlify@v1.1.5
+ uses: nwtgck/actions-netlify@v1.2.3
with:
publish-dir: './site'
production-branch: master
diff --git a/.github/workflows/latest-changes.yml b/.github/workflows/latest-changes.yml
index 42236bebaa585..4aa8475b62daf 100644
--- a/.github/workflows/latest-changes.yml
+++ b/.github/workflows/latest-changes.yml
@@ -12,7 +12,7 @@ on:
description: PR number
required: true
debug_enabled:
- description: 'Run the build with tmate debugging enabled (https://github.com/marketplace/actions/debugging-with-tmate)'
+ description: 'Run the build with tmate debugging enabled (https://github.com/marketplace/actions/debugging-with-tmate)'
required: false
default: false
@@ -20,7 +20,7 @@ jobs:
latest-changes:
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@v2
+ - uses: actions/checkout@v3
with:
# To allow latest-changes to commit to master
token: ${{ secrets.ACTIONS_TOKEN }}
diff --git a/.github/workflows/notify-translations.yml b/.github/workflows/notify-translations.yml
index 7e414ab95e27a..2fcb7595e6714 100644
--- a/.github/workflows/notify-translations.yml
+++ b/.github/workflows/notify-translations.yml
@@ -9,7 +9,7 @@ jobs:
notify-translations:
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@v2
+ - uses: actions/checkout@v3
# Allow debugging with tmate
- name: Setup tmate session
uses: mxschmitt/action-tmate@v3
diff --git a/.github/workflows/people.yml b/.github/workflows/people.yml
index 970813da7b107..4b47b4072f6b8 100644
--- a/.github/workflows/people.yml
+++ b/.github/workflows/people.yml
@@ -6,7 +6,7 @@ on:
workflow_dispatch:
inputs:
debug_enabled:
- description: 'Run the build with tmate debugging enabled (https://github.com/marketplace/actions/debugging-with-tmate)'
+ description: 'Run the build with tmate debugging enabled (https://github.com/marketplace/actions/debugging-with-tmate)'
required: false
default: false
@@ -14,7 +14,7 @@ jobs:
fastapi-people:
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@v2
+ - uses: actions/checkout@v3
# Allow debugging with tmate
- name: Setup tmate session
uses: mxschmitt/action-tmate@v3
diff --git a/.github/workflows/preview-docs.yml b/.github/workflows/preview-docs.yml
index 0c0d2ac59a9e6..9e71a461a7faf 100644
--- a/.github/workflows/preview-docs.yml
+++ b/.github/workflows/preview-docs.yml
@@ -3,16 +3,16 @@ on:
workflow_run:
workflows:
- Build Docs
- types:
+ types:
- completed
jobs:
preview-docs:
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@v2
+ - uses: actions/checkout@v3
- name: Download Artifact Docs
- uses: dawidd6/action-download-artifact@v2.9.0
+ uses: dawidd6/action-download-artifact@v2.21.1
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
workflow: build-docs.yml
@@ -25,7 +25,7 @@ jobs:
rm -f docs.zip
- name: Deploy to Netlify
id: netlify
- uses: nwtgck/actions-netlify@v1.1.5
+ uses: nwtgck/actions-netlify@v1.2.3
with:
publish-dir: './site'
production-deploy: false
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml
index 9dde4e066c59f..02846cefdbdb3 100644
--- a/.github/workflows/publish.yml
+++ b/.github/workflows/publish.yml
@@ -13,12 +13,12 @@ jobs:
env:
GITHUB_CONTEXT: ${{ toJson(github) }}
run: echo "$GITHUB_CONTEXT"
- - uses: actions/checkout@v2
+ - uses: actions/checkout@v3
- name: Set up Python
- uses: actions/setup-python@v2
+ uses: actions/setup-python@v4
with:
python-version: "3.6"
- - uses: actions/cache@v2
+ - uses: actions/cache@v3
id: cache
with:
path: ${{ env.pythonLocation }}
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index f0a82344e43ad..14dc141d93b2f 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -16,12 +16,12 @@ jobs:
fail-fast: false
steps:
- - uses: actions/checkout@v2
+ - uses: actions/checkout@v3
- name: Set up Python
- uses: actions/setup-python@v2
+ uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}
- - uses: actions/cache@v2
+ - uses: actions/cache@v3
id: cache
with:
path: ${{ env.pythonLocation }}
@@ -38,4 +38,4 @@ jobs:
- name: Test
run: bash scripts/test.sh
- name: Upload coverage
- uses: codecov/codecov-action@v2
+ uses: codecov/codecov-action@v3
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
new file mode 100644
index 0000000000000..6944e4a25f8ed
--- /dev/null
+++ b/.pre-commit-config.yaml
@@ -0,0 +1,51 @@
+# See https://pre-commit.com for more information
+# See https://pre-commit.com/hooks.html for more hooks
+repos:
+- repo: https://github.com/pre-commit/pre-commit-hooks
+ rev: v4.3.0
+ hooks:
+ - id: check-added-large-files
+ - id: check-toml
+ - id: check-yaml
+ args:
+ - --unsafe
+ - id: end-of-file-fixer
+ - id: trailing-whitespace
+- repo: https://github.com/asottile/pyupgrade
+ rev: v2.37.1
+ hooks:
+ - id: pyupgrade
+ args:
+ - --py3-plus
+ - --keep-runtime-typing
+- repo: https://github.com/myint/autoflake
+ rev: v1.4
+ hooks:
+ - id: autoflake
+ args:
+ - --recursive
+ - --in-place
+ - --remove-all-unused-imports
+ - --remove-unused-variables
+ - --expand-star-imports
+ - --exclude
+ - __init__.py
+ - --remove-duplicate-keys
+- repo: https://github.com/pycqa/isort
+ rev: 5.10.1
+ hooks:
+ - id: isort
+ name: isort (python)
+ - id: isort
+ name: isort (cython)
+ types: [cython]
+ - id: isort
+ name: isort (pyi)
+ types: [pyi]
+- repo: https://github.com/psf/black
+ rev: 22.6.0
+ hooks:
+ - id: black
+ci:
+ autofix_commit_msg: 🎨 [pre-commit.ci] Auto format from pre-commit.com hooks
+ autoupdate_commit_msg: ⬆ [pre-commit.ci] pre-commit autoupdate
diff --git a/README.md b/README.md
index 9ad50f271f220..326ad22795343 100644
--- a/README.md
+++ b/README.md
@@ -47,10 +47,11 @@ The key features are:
-
+
+
-
-
+
+
@@ -151,7 +152,7 @@ $ pip install "uvicorn[standard]"
* Create a file `main.py` with:
```Python
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
@@ -164,7 +165,7 @@ def read_root():
@app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
```
@@ -174,7 +175,7 @@ def read_item(item_id: int, q: Optional[str] = None):
If your code uses `async` / `await`, use `async def`:
```Python hl_lines="9 14"
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
@@ -187,7 +188,7 @@ async def read_root():
@app.get("/items/{item_id}")
-async def read_item(item_id: int, q: Optional[str] = None):
+async def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
```
@@ -266,7 +267,7 @@ Now modify the file `main.py` to receive a body from a `PUT` request.
Declare the body using standard Python types, thanks to Pydantic.
```Python hl_lines="4 9-12 25-27"
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
from pydantic import BaseModel
@@ -277,7 +278,7 @@ app = FastAPI()
class Item(BaseModel):
name: str
price: float
- is_offer: Optional[bool] = None
+ is_offer: Union[bool, None] = None
@app.get("/")
@@ -286,7 +287,7 @@ def read_root():
@app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
diff --git a/docs/az/mkdocs.yml b/docs/az/mkdocs.yml
index 58bbb07588ae9..d549f37a396b2 100644
--- a/docs/az/mkdocs.yml
+++ b/docs/az/mkdocs.yml
@@ -5,13 +5,15 @@ theme:
name: material
custom_dir: overrides
palette:
- - scheme: default
+ - media: '(prefers-color-scheme: light)'
+ scheme: default
primary: teal
accent: amber
toggle:
icon: material/lightbulb
name: Switch to light mode
- - scheme: slate
+ - media: '(prefers-color-scheme: dark)'
+ scheme: slate
primary: teal
accent: amber
toggle:
@@ -42,6 +44,7 @@ nav:
- es: /es/
- fa: /fa/
- fr: /fr/
+ - he: /he/
- id: /id/
- it: /it/
- ja: /ja/
@@ -51,6 +54,7 @@ nav:
- pt: /pt/
- ru: /ru/
- sq: /sq/
+ - sv: /sv/
- tr: /tr/
- uk: /uk/
- zh: /zh/
@@ -71,6 +75,8 @@ markdown_extensions:
format: !!python/name:pymdownx.superfences.fence_code_format ''
- pymdownx.tabbed:
alternate_style: true
+- attr_list
+- md_in_html
extra:
analytics:
provider: google
@@ -103,6 +109,8 @@ extra:
name: fa
- link: /fr/
name: fr - français
+ - link: /he/
+ name: he
- link: /id/
name: id
- link: /it/
@@ -121,6 +129,8 @@ extra:
name: ru - русский язык
- link: /sq/
name: sq - shqip
+ - link: /sv/
+ name: sv - svenska
- link: /tr/
name: tr - Türkçe
- link: /uk/
diff --git a/docs/de/docs/features.md b/docs/de/docs/features.md
index a92a2bfebe499..f825472a9a940 100644
--- a/docs/de/docs/features.md
+++ b/docs/de/docs/features.md
@@ -27,7 +27,7 @@ Mit einer interaktiven API-Dokumentation und explorativen webbasierten Benutzers
Alles basiert auf **Python 3.6 Typ**-Deklarationen (dank Pydantic). Es muss keine neue Syntax gelernt werden, nur standardisiertes modernes Python.
-
+
Wenn Sie eine kurze, zweiminütige, Auffrischung in der Benutzung von Python Typ-Deklarationen benötigen (auch wenn Sie FastAPI nicht nutzen), schauen Sie sich diese kurze Einführung an (Englisch): Python Types{.internal-link target=_blank}.
@@ -97,7 +97,7 @@ Hierdurch werden Sie nie wieder einen falschen Schlüsselnamen benutzen und spar
### Kompakt
-FastAPI nutzt für alles sinnvolle **Standard-Einstellungen**, welche optional überall konfiguriert werden können. Alle Parameter können ganz genau an Ihre Bedürfnisse angepasst werden, sodass sie genau die API definieren können, die sie brauchen.
+FastAPI nutzt für alles sensible **Standard-Einstellungen**, welche optional überall konfiguriert werden können. Alle Parameter können ganz genau an Ihre Bedürfnisse angepasst werden, sodass sie genau die API definieren können, die sie brauchen.
Aber standardmäßig, **"funktioniert einfach"** alles.
@@ -119,9 +119,9 @@ Die gesamte Validierung übernimmt das etablierte und robuste **Pydantic**.
### Sicherheit und Authentifizierung
-Sicherheit und Authentifizierung integriert. Ohne einen Kompromiss aufgrund einer Datenbank oder den Datenentitäten.
+Integrierte Sicherheit und Authentifizierung. Ohne Kompromisse bei Datenbanken oder Datenmodellen.
-Unterstützt alle von OpenAPI definierten Sicherheitsschemata, hierzu gehören:
+Unterstützt werden alle von OpenAPI definierten Sicherheitsschemata, hierzu gehören:
* HTTP Basis Authentifizierung.
* **OAuth2** (auch mit **JWT Zugriffstokens**). Schauen Sie sich hierzu dieses Tutorial an: [OAuth2 mit JWT](tutorial/security/oauth2-jwt.md){.internal-link target=_blank}.
@@ -142,8 +142,8 @@ FastAPI enthält ein extrem einfaches, aber extrem mächtiges eines der schnellsten Python frameworks, auf Augenhöhe mit **NodeJS** und **Go**.
+* Stark beeindruckende Performanz. Es ist eines der schnellsten Python Frameworks, auf Augenhöhe mit **NodeJS** und **Go**.
* **WebSocket**-Unterstützung.
* Hintergrundaufgaben im selben Prozess.
* Ereignisse für das Starten und Herunterfahren.
@@ -193,11 +193,11 @@ Mit **FastAPI** bekommen Sie alle Funktionen von **Pydantic** (da FastAPI für d
* Gutes Zusammenspiel mit Ihrer/Ihrem **IDE/linter/Gehirn**:
* Weil Datenstrukturen von Pydantic einfach nur Instanzen ihrer definierten Klassen sind, sollten Autovervollständigung, Linting, mypy und ihre Intuition einwandfrei funktionieren.
* **Schnell**:
- * In Vergleichen ist Pydantic schneller als jede andere getestete Bibliothek.
+ * In Vergleichen ist Pydantic schneller als jede andere getestete Bibliothek.
* Validierung von **komplexen Strukturen**:
* Benutzung von hierachischen Pydantic Schemata, Python `typing`’s `List` und `Dict`, etc.
- * Validierungen erlauben klare und einfache Datenschemadefinition, überprüft und dokumentiert als JSON Schema.
+ * Validierungen erlauben eine klare und einfache Datenschemadefinition, überprüft und dokumentiert als JSON Schema.
* Sie können stark **verschachtelte JSON** Objekte haben und diese sind trotzdem validiert und annotiert.
* **Erweiterbar**:
- * Pydantic erlaubt die Definition von eigenen Datentypen oder Sie können die Validierung mit einer `validator` dekorierten Methode erweitern..
+ * Pydantic erlaubt die Definition von eigenen Datentypen oder sie können die Validierung mit einer `validator` dekorierten Methode erweitern.
* 100% Testabdeckung.
diff --git a/docs/de/docs/index.md b/docs/de/docs/index.md
index cdce662238b52..287c79cff6e1a 100644
--- a/docs/de/docs/index.md
+++ b/docs/de/docs/index.md
@@ -135,7 +135,7 @@ You will also need an ASGI server, for production such as
```console
-$ pip install uvicorn[standard]
+$ pip install "uvicorn[standard]"
---> 100%
```
@@ -149,7 +149,7 @@ $ pip install uvicorn[standard]
* Create a file `main.py` with:
```Python
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
@@ -162,7 +162,7 @@ def read_root():
@app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
```
@@ -172,7 +172,7 @@ def read_item(item_id: int, q: Optional[str] = None):
If your code uses `async` / `await`, use `async def`:
```Python hl_lines="9 14"
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
@@ -185,7 +185,7 @@ async def read_root():
@app.get("/items/{item_id}")
-async def read_item(item_id: int, q: Optional[str] = None):
+async def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
```
@@ -264,7 +264,7 @@ Now modify the file `main.py` to receive a body from a `PUT` request.
Declare the body using standard Python types, thanks to Pydantic.
```Python hl_lines="4 9-12 25-27"
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
from pydantic import BaseModel
@@ -275,7 +275,7 @@ app = FastAPI()
class Item(BaseModel):
name: str
price: float
- is_offer: Optional[bool] = None
+ is_offer: Union[bool, None] = None
@app.get("/")
@@ -284,7 +284,7 @@ def read_root():
@app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
@@ -321,7 +321,7 @@ And now, go to `swagger-ui-bundle.js`
-* `swagger-ui.css`
+* `swagger-ui-bundle.js`
+* `swagger-ui.css`
And **ReDoc** uses the file:
diff --git a/docs/en/docs/advanced/openapi-callbacks.md b/docs/en/docs/advanced/openapi-callbacks.md
index 138c90dd7c435..656ddbb3f5abe 100644
--- a/docs/en/docs/advanced/openapi-callbacks.md
+++ b/docs/en/docs/advanced/openapi-callbacks.md
@@ -31,7 +31,7 @@ It will have a *path operation* that will receive an `Invoice` body, and a query
This part is pretty normal, most of the code is probably already familiar to you:
-```Python hl_lines="10-14 37-54"
+```Python hl_lines="9-13 36-53"
{!../../../docs_src/openapi_callbacks/tutorial001.py!}
```
@@ -83,7 +83,7 @@ So we are going to use that same knowledge to document how the *external API* sh
First create a new `APIRouter` that will contain one or more callbacks.
-```Python hl_lines="5 26"
+```Python hl_lines="3 25"
{!../../../docs_src/openapi_callbacks/tutorial001.py!}
```
@@ -96,7 +96,7 @@ It should look just like a normal FastAPI *path operation*:
* It should probably have a declaration of the body it should receive, e.g. `body: InvoiceEvent`.
* And it could also have a declaration of the response it should return, e.g. `response_model=InvoiceEventReceived`.
-```Python hl_lines="17-19 22-23 29-33"
+```Python hl_lines="16-18 21-22 28-32"
{!../../../docs_src/openapi_callbacks/tutorial001.py!}
```
@@ -163,7 +163,7 @@ At this point you have the *callback path operation(s)* needed (the one(s) that
Now use the parameter `callbacks` in *your API's path operation decorator* to pass the attribute `.routes` (that's actually just a `list` of routes/*path operations*) from that callback router:
-```Python hl_lines="36"
+```Python hl_lines="35"
{!../../../docs_src/openapi_callbacks/tutorial001.py!}
```
diff --git a/docs/en/docs/advanced/security/http-basic-auth.md b/docs/en/docs/advanced/security/http-basic-auth.md
index 6c589cd9afe32..90c516808fc41 100644
--- a/docs/en/docs/advanced/security/http-basic-auth.md
+++ b/docs/en/docs/advanced/security/http-basic-auth.md
@@ -34,13 +34,19 @@ Here's a more complete example.
Use a dependency to check if the username and password are correct.
-For this, use the Python standard module `secrets` to check the username and password:
+For this, use the Python standard module `secrets` to check the username and password.
-```Python hl_lines="1 11-13"
+`secrets.compare_digest()` needs to take `bytes` or a `str` that only contains ASCII characters (the ones in English), this means it wouldn't work with characters like `á`, as in `Sebastián`.
+
+To handle that, we first convert the `username` and `password` to `bytes` encoding them with UTF-8.
+
+Then we can use `secrets.compare_digest()` to ensure that `credentials.username` is `"stanleyjobson"`, and that `credentials.password` is `"swordfish"`.
+
+```Python hl_lines="1 11-21"
{!../../../docs_src/security/tutorial007.py!}
```
-This will ensure that `credentials.username` is `"stanleyjobson"`, and that `credentials.password` is `"swordfish"`. This would be similar to:
+This would be similar to:
```Python
if not (credentials.username == "stanleyjobson") or not (credentials.password == "swordfish"):
@@ -102,6 +108,6 @@ That way, using `secrets.compare_digest()` in your application code, it will be
After detecting that the credentials are incorrect, return an `HTTPException` with a status code 401 (the same returned when no credentials are provided) and add the header `WWW-Authenticate` to make the browser show the login prompt again:
-```Python hl_lines="15-19"
+```Python hl_lines="23-27"
{!../../../docs_src/security/tutorial007.py!}
```
diff --git a/docs/en/docs/advanced/security/oauth2-scopes.md b/docs/en/docs/advanced/security/oauth2-scopes.md
index 4bd9cfd0470cc..be51325cdbdbd 100644
--- a/docs/en/docs/advanced/security/oauth2-scopes.md
+++ b/docs/en/docs/advanced/security/oauth2-scopes.md
@@ -16,11 +16,11 @@ In this section you will see how to manage authentication and authorization with
You don't necessarily need OAuth2 scopes, and you can handle authentication and authorization however you want.
But OAuth2 with scopes can be nicely integrated into your API (with OpenAPI) and your API docs.
-
+
Nevertheless, you still enforce those scopes, or any other security/authorization requirement, however you need, in your code.
In many cases, OAuth2 with scopes can be an overkill.
-
+
But if you know you need it, or you are curious, keep reading.
## OAuth2 scopes and OpenAPI
@@ -47,7 +47,7 @@ They are normally used to declare specific security permissions, for example:
In OAuth2 a "scope" is just a string that declares a specific permission required.
It doesn't matter if it has other characters like `:` or if it is a URL.
-
+
Those details are implementation specific.
For OAuth2 they are just strings.
@@ -115,7 +115,7 @@ In this case, it requires the scope `me` (it could require more than one scope).
!!! note
You don't necessarily need to add different scopes in different places.
-
+
We are doing it here to demonstrate how **FastAPI** handles scopes declared at different levels.
```Python hl_lines="4 139 166"
diff --git a/docs/en/docs/advanced/sql-databases-peewee.md b/docs/en/docs/advanced/sql-databases-peewee.md
index 48514d1e29c1e..b4ea61367e820 100644
--- a/docs/en/docs/advanced/sql-databases-peewee.md
+++ b/docs/en/docs/advanced/sql-databases-peewee.md
@@ -182,7 +182,7 @@ Now let's check the file `sql_app/schemas.py`.
To avoid confusion between the Peewee *models* and the Pydantic *models*, we will have the file `models.py` with the Peewee models, and the file `schemas.py` with the Pydantic models.
These Pydantic models define more or less a "schema" (a valid data shape).
-
+
So this will help us avoiding confusion while using both.
### Create the Pydantic *models* / schemas
diff --git a/docs/en/docs/advanced/testing-dependencies.md b/docs/en/docs/advanced/testing-dependencies.md
index 79208e8dc8625..7bba82fb7fe50 100644
--- a/docs/en/docs/advanced/testing-dependencies.md
+++ b/docs/en/docs/advanced/testing-dependencies.md
@@ -28,7 +28,7 @@ To override a dependency for testing, you put as a key the original dependency (
And then **FastAPI** will call that override instead of the original dependency.
-```Python hl_lines="26-27 30"
+```Python hl_lines="28-29 32"
{!../../../docs_src/dependency_testing/tutorial001.py!}
```
diff --git a/docs/en/docs/advanced/websockets.md b/docs/en/docs/advanced/websockets.md
index 878ad37ddc31b..0e9bc5b06b378 100644
--- a/docs/en/docs/advanced/websockets.md
+++ b/docs/en/docs/advanced/websockets.md
@@ -2,6 +2,20 @@
You can use WebSockets with **FastAPI**.
+## Install `WebSockets`
+
+First you need to install `WebSockets`:
+
+
+
## WebSockets client
### In production
diff --git a/docs/en/docs/alternatives.md b/docs/en/docs/alternatives.md
index 28d0be8cc0802..68aa3150d7194 100644
--- a/docs/en/docs/alternatives.md
+++ b/docs/en/docs/alternatives.md
@@ -235,7 +235,7 @@ It was one of the first extremely fast Python frameworks based on `asyncio`. It
!!! check "Inspired **FastAPI** to"
Find a way to have a crazy performance.
-
+
That's why **FastAPI** is based on Starlette, as it is the fastest framework available (tested by third-party benchmarks).
### Falcon
@@ -333,7 +333,7 @@ Now APIStar is a set of tools to validate OpenAPI specifications, not a web fram
Exist.
The idea of declaring multiple things (data validation, serialization and documentation) with the same Python types, that at the same time provided great editor support, was something I considered a brilliant idea.
-
+
And after searching for a long time for a similar framework and testing many different alternatives, APIStar was the best option available.
Then APIStar stopped to exist as a server and Starlette was created, and was a new better foundation for such a system. That was the final inspiration to build **FastAPI**.
@@ -391,7 +391,7 @@ That's one of the main things that **FastAPI** adds on top, all based on Python
Handle all the core web parts. Adding features on top.
The class `FastAPI` itself inherits directly from the class `Starlette`.
-
+
So, anything that you can do with Starlette, you can do it directly with **FastAPI**, as it is basically Starlette on steroids.
### Uvicorn
diff --git a/docs/en/docs/async.md b/docs/en/docs/async.md
index 71f2e75025f2c..dc8e10bb840d1 100644
--- a/docs/en/docs/async.md
+++ b/docs/en/docs/async.md
@@ -102,87 +102,117 @@ To see the difference, imagine the following story about burgers:
### Concurrent Burgers
-
+You go with your crush to get fast food, you stand in line while the cashier takes the orders from the people in front of you. 😍
-You go with your crush 😍 to get fast food 🍔, you stand in line while the cashier 💁 takes the orders from the people in front of you.
+
-Then it's your turn, you place your order of 2 very fancy burgers 🍔 for your crush 😍 and you.
+Then it's your turn, you place your order of 2 very fancy burgers for your crush and you. 🍔🍔
-You pay 💸.
+
+
+The cashier says something to the cook in the kitchen so they know they have to prepare your burgers (even though they are currently preparing the ones for the previous clients).
+
+
+
+You pay. 💸
+
+The cashier gives you the number of your turn.
-The cashier 💁 says something to the cook in the kitchen 👨🍳 so they know they have to prepare your burgers 🍔 (even though they are currently preparing the ones for the previous clients).
+
-The cashier 💁 gives you the number of your turn.
+While you are waiting, you go with your crush and pick a table, you sit and talk with your crush for a long time (as your burgers are very fancy and take some time to prepare).
-While you are waiting, you go with your crush 😍 and pick a table, you sit and talk with your crush 😍 for a long time (as your burgers are very fancy and take some time to prepare ✨🍔✨).
+As you are sitting at the table with your crush, while you wait for the burgers, you can spend that time admiring how awesome, cute and smart your crush is ✨😍✨.
-As you are sitting at the table with your crush 😍, while you wait for the burgers 🍔, you can spend that time admiring how awesome, cute and smart your crush is ✨😍✨.
+
-While waiting and talking to your crush 😍, from time to time, you check the number displayed on the counter to see if it's your turn already.
+While waiting and talking to your crush, from time to time, you check the number displayed on the counter to see if it's your turn already.
-Then at some point, it finally is your turn. You go to the counter, get your burgers 🍔 and come back to the table.
+Then at some point, it finally is your turn. You go to the counter, get your burgers and come back to the table.
-You and your crush 😍 eat the burgers 🍔 and have a nice time ✨.
+
+
+You and your crush eat the burgers and have a nice time. ✨
+
+
+
+!!! info
+ Beautiful illustrations by Ketrina Thompson. 🎨
---
Imagine you are the computer / program 🤖 in that story.
-While you are at the line, you are just idle 😴, waiting for your turn, not doing anything very "productive". But the line is fast because the cashier 💁 is only taking the orders (not preparing them), so that's fine.
+While you are at the line, you are just idle 😴, waiting for your turn, not doing anything very "productive". But the line is fast because the cashier is only taking the orders (not preparing them), so that's fine.
-Then, when it's your turn, you do actual "productive" work 🤓, you process the menu, decide what you want, get your crush's 😍 choice, pay 💸, check that you give the correct bill or card, check that you are charged correctly, check that the order has the correct items, etc.
+Then, when it's your turn, you do actual "productive" work, you process the menu, decide what you want, get your crush's choice, pay, check that you give the correct bill or card, check that you are charged correctly, check that the order has the correct items, etc.
-But then, even though you still don't have your burgers 🍔, your work with the cashier 💁 is "on pause" ⏸, because you have to wait 🕙 for your burgers to be ready.
+But then, even though you still don't have your burgers, your work with the cashier is "on pause" ⏸, because you have to wait 🕙 for your burgers to be ready.
-But as you go away from the counter and sit at the table with a number for your turn, you can switch 🔀 your attention to your crush 😍, and "work" ⏯ 🤓 on that. Then you are again doing something very "productive" 🤓, as is flirting with your crush 😍.
+But as you go away from the counter and sit at the table with a number for your turn, you can switch 🔀 your attention to your crush, and "work" ⏯ 🤓 on that. Then you are again doing something very "productive" as is flirting with your crush 😍.
-Then the cashier 💁 says "I'm finished with doing the burgers" 🍔 by putting your number on the counter's display, but you don't jump like crazy immediately when the displayed number changes to your turn number. You know no one will steal your burgers 🍔 because you have the number of your turn, and they have theirs.
+Then the cashier 💁 says "I'm finished with doing the burgers" by putting your number on the counter's display, but you don't jump like crazy immediately when the displayed number changes to your turn number. You know no one will steal your burgers because you have the number of your turn, and they have theirs.
-So you wait for your crush 😍 to finish the story (finish the current work ⏯ / task being processed 🤓), smile gently and say that you are going for the burgers ⏸.
+So you wait for your crush to finish the story (finish the current work ⏯ / task being processed 🤓), smile gently and say that you are going for the burgers ⏸.
-Then you go to the counter 🔀, to the initial task that is now finished ⏯, pick the burgers 🍔, say thanks and take them to the table. That finishes that step / task of interaction with the counter ⏹. That in turn, creates a new task, of "eating burgers" 🔀 ⏯, but the previous one of "getting burgers" is finished ⏹.
+Then you go to the counter 🔀, to the initial task that is now finished ⏯, pick the burgers, say thanks and take them to the table. That finishes that step / task of interaction with the counter ⏹. That in turn, creates a new task, of "eating burgers" 🔀 ⏯, but the previous one of "getting burgers" is finished ⏹.
### Parallel Burgers
Now let's imagine these aren't "Concurrent Burgers", but "Parallel Burgers".
-You go with your crush 😍 to get parallel fast food 🍔.
+You go with your crush to get parallel fast food.
+
+You stand in line while several (let's say 8) cashiers that at the same time are cooks take the orders from the people in front of you.
-You stand in line while several (let's say 8) cashiers that at the same time are cooks 👩🍳👨🍳👩🍳👨🍳👩🍳👨🍳👩🍳👨🍳 take the orders from the people in front of you.
+Everyone before you is waiting for their burgers to be ready before leaving the counter because each of the 8 cashiers goes and prepares the burger right away before getting the next order.
-Everyone before you is waiting 🕙 for their burgers 🍔 to be ready before leaving the counter because each of the 8 cashiers goes and prepares the burger right away before getting the next order.
+
-Then it's finally your turn, you place your order of 2 very fancy burgers 🍔 for your crush 😍 and you.
+Then it's finally your turn, you place your order of 2 very fancy burgers for your crush and you.
You pay 💸.
-The cashier goes to the kitchen 👨🍳.
+
-You wait, standing in front of the counter 🕙, so that no one else takes your burgers 🍔 before you do, as there are no numbers for turns.
+The cashier goes to the kitchen.
-As you and your crush 😍 are busy not letting anyone get in front of you and take your burgers whenever they arrive 🕙, you cannot pay attention to your crush 😞.
+You wait, standing in front of the counter 🕙, so that no one else takes your burgers before you do, as there are no numbers for turns.
-This is "synchronous" work, you are "synchronized" with the cashier/cook 👨🍳. You have to wait 🕙 and be there at the exact moment that the cashier/cook 👨🍳 finishes the burgers 🍔 and gives them to you, or otherwise, someone else might take them.
+
-Then your cashier/cook 👨🍳 finally comes back with your burgers 🍔, after a long time waiting 🕙 there in front of the counter.
+As you and your crush are busy not letting anyone get in front of you and take your burgers whenever they arrive, you cannot pay attention to your crush. 😞
-You take your burgers 🍔 and go to the table with your crush 😍.
+This is "synchronous" work, you are "synchronized" with the cashier/cook 👨🍳. You have to wait 🕙 and be there at the exact moment that the cashier/cook 👨🍳 finishes the burgers and gives them to you, or otherwise, someone else might take them.
-You just eat them, and you are done 🍔 ⏹.
+
-There was not much talk or flirting as most of the time was spent waiting 🕙 in front of the counter 😞.
+Then your cashier/cook 👨🍳 finally comes back with your burgers, after a long time waiting 🕙 there in front of the counter.
+
+
+
+You take your burgers and go to the table with your crush.
+
+You just eat them, and you are done. ⏹
+
+
+
+There was not much talk or flirting as most of the time was spent waiting 🕙 in front of the counter. 😞
+
+!!! info
+ Beautiful illustrations by Ketrina Thompson. 🎨
---
-In this scenario of the parallel burgers, you are a computer / program 🤖 with two processors (you and your crush 😍), both waiting 🕙 and dedicating their attention ⏯ to be "waiting on the counter" 🕙 for a long time.
+In this scenario of the parallel burgers, you are a computer / program 🤖 with two processors (you and your crush), both waiting 🕙 and dedicating their attention ⏯ to be "waiting on the counter" 🕙 for a long time.
-The fast food store has 8 processors (cashiers/cooks) 👩🍳👨🍳👩🍳👨🍳👩🍳👨🍳👩🍳👨🍳. While the concurrent burgers store might have had only 2 (one cashier and one cook) 💁 👨🍳.
+The fast food store has 8 processors (cashiers/cooks). While the concurrent burgers store might have had only 2 (one cashier and one cook).
-But still, the final experience is not the best 😞.
+But still, the final experience is not the best. 😞
---
-This would be the parallel equivalent story for burgers 🍔.
+This would be the parallel equivalent story for burgers. 🍔
For a more "real life" example of this, imagine a bank.
@@ -208,11 +238,7 @@ This "waiting" 🕙 is measured in microseconds, but still, summing it all, it's
That's why it makes a lot of sense to use asynchronous ⏸🔀⏯ code for web APIs.
-Most of the existing popular Python frameworks (including Flask and Django) were created before the new asynchronous features in Python existed. So, the ways they can be deployed support parallel execution and an older form of asynchronous execution that is not as powerful as the new capabilities.
-
-Even though the main specification for asynchronous web Python (ASGI) was developed at Django, to add support for WebSockets.
-
-That kind of asynchronicity is what made NodeJS popular (even though NodeJS is not parallel) and that's the strength of Go as a programming language.
+This kind of asynchronicity is what made NodeJS popular (even though NodeJS is not parallel) and that's the strength of Go as a programming language.
And that's the same level of performance you get with **FastAPI**.
@@ -238,7 +264,7 @@ You could have turns as in the burgers example, first the living room, then the
It would take the same amount of time to finish with or without turns (concurrency) and you would have done the same amount of work.
-But in this case, if you could bring the 8 ex-cashier/cooks/now-cleaners 👩🍳👨🍳👩🍳👨🍳👩🍳👨🍳👩🍳👨🍳, and each one of them (plus you) could take a zone of the house to clean it, you could do all the work in **parallel**, with the extra help, and finish much sooner.
+But in this case, if you could bring the 8 ex-cashier/cooks/now-cleaners, and each one of them (plus you) could take a zone of the house to clean it, you could do all the work in **parallel**, with the extra help, and finish much sooner.
In this scenario, each one of the cleaners (including you) would be a processor, doing their part of the job.
diff --git a/docs/en/docs/css/custom.css b/docs/en/docs/css/custom.css
index 7d3503e492b86..066b51725ecce 100644
--- a/docs/en/docs/css/custom.css
+++ b/docs/en/docs/css/custom.css
@@ -4,10 +4,21 @@
display: block;
}
+.termy {
+ /* For right to left languages */
+ direction: ltr;
+}
+
.termy [data-termynal] {
white-space: pre-wrap;
}
+a.external-link {
+ /* For right to left languages */
+ direction: ltr;
+ display: inline-block;
+}
+
a.external-link::after {
/* \00A0 is a non-breaking space
to make the mark be on the same line as the link
@@ -94,7 +105,7 @@ a.announce-link:hover {
.announce-wrapper .sponsor-badge {
display: block;
position: absolute;
- top: -5px;
+ top: -10px;
right: 0;
font-size: 0.5rem;
color: #999;
@@ -118,3 +129,18 @@ a.announce-link:hover {
.twitter {
color: #00acee;
}
+
+/* Right to left languages */
+code {
+ direction: ltr;
+ display: inline-block;
+}
+
+.md-content__inner h1 {
+ direction: ltr !important;
+}
+
+.illustration {
+ margin-top: 2em;
+ margin-bottom: 2em;
+}
diff --git a/docs/en/docs/deployment/docker.md b/docs/en/docs/deployment/docker.md
index 3f86efcced275..8a542622e408a 100644
--- a/docs/en/docs/deployment/docker.md
+++ b/docs/en/docs/deployment/docker.md
@@ -142,7 +142,7 @@ Successfully installed fastapi pydantic uvicorn
* Create a `main.py` file with:
```Python
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
@@ -155,7 +155,7 @@ def read_root():
@app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
```
@@ -350,7 +350,7 @@ If your FastAPI is a single file, for example, `main.py` without an `./app` dire
Then you would just have to change the corresponding paths to copy the file inside the `Dockerfile`:
```{ .dockerfile .annotate hl_lines="10 13" }
-FROM python:3.9
+FROM python:3.9
WORKDIR /code
diff --git a/docs/en/docs/deployment/manually.md b/docs/en/docs/deployment/manually.md
index 16286533ab600..d6892b2c14ad6 100644
--- a/docs/en/docs/deployment/manually.md
+++ b/docs/en/docs/deployment/manually.md
@@ -38,7 +38,7 @@ You can install an ASGI compatible server with:
!!! tip
By adding the `standard`, Uvicorn will install and use some recommended extra dependencies.
-
+
That including `uvloop`, the high-performance drop-in replacement for `asyncio`, that provides the big concurrency performance boost.
=== "Hypercorn"
@@ -89,7 +89,7 @@ You can then run your application the same way you have done in the tutorials, b
Remember to remove the `--reload` option if you were using it.
The `--reload` option consumes much more resources, is more unstable, etc.
-
+
It helps a lot during **development**, but you **shouldn't** use it in **production**.
## Hypercorn with Trio
diff --git a/docs/en/docs/features.md b/docs/en/docs/features.md
index 36f80783a6104..e4672d5329347 100644
--- a/docs/en/docs/features.md
+++ b/docs/en/docs/features.md
@@ -190,7 +190,7 @@ With **FastAPI** you get all of **Pydantic**'s features (as FastAPI is based on
* Plays nicely with your **IDE/linter/brain**:
* Because pydantic data structures are just instances of classes you define; auto-completion, linting, mypy and your intuition should all work properly with your validated data.
* **Fast**:
- * in benchmarks Pydantic is faster than all other tested libraries.
+ * in benchmarks Pydantic is faster than all other tested libraries.
* Validate **complex structures**:
* Use of hierarchical Pydantic models, Python `typing`’s `List` and `Dict`, etc.
* And validators allow complex data schemas to be clearly and easily defined, checked and documented as JSON Schema.
diff --git a/docs/en/docs/img/async/concurrent-burgers/concurrent-burgers-01.png b/docs/en/docs/img/async/concurrent-burgers/concurrent-burgers-01.png
new file mode 100644
index 0000000000000..e0e77d3fcec50
Binary files /dev/null and b/docs/en/docs/img/async/concurrent-burgers/concurrent-burgers-01.png differ
diff --git a/docs/en/docs/img/async/concurrent-burgers/concurrent-burgers-02.png b/docs/en/docs/img/async/concurrent-burgers/concurrent-burgers-02.png
new file mode 100644
index 0000000000000..27f6e127179cb
Binary files /dev/null and b/docs/en/docs/img/async/concurrent-burgers/concurrent-burgers-02.png differ
diff --git a/docs/en/docs/img/async/concurrent-burgers/concurrent-burgers-03.png b/docs/en/docs/img/async/concurrent-burgers/concurrent-burgers-03.png
new file mode 100644
index 0000000000000..27472a8e02e5a
Binary files /dev/null and b/docs/en/docs/img/async/concurrent-burgers/concurrent-burgers-03.png differ
diff --git a/docs/en/docs/img/async/concurrent-burgers/concurrent-burgers-04.png b/docs/en/docs/img/async/concurrent-burgers/concurrent-burgers-04.png
new file mode 100644
index 0000000000000..cf1d8dd454f91
Binary files /dev/null and b/docs/en/docs/img/async/concurrent-burgers/concurrent-burgers-04.png differ
diff --git a/docs/en/docs/img/async/concurrent-burgers/concurrent-burgers-05.png b/docs/en/docs/img/async/concurrent-burgers/concurrent-burgers-05.png
new file mode 100644
index 0000000000000..ab6e036694bc8
Binary files /dev/null and b/docs/en/docs/img/async/concurrent-burgers/concurrent-burgers-05.png differ
diff --git a/docs/en/docs/img/async/concurrent-burgers/concurrent-burgers-06.png b/docs/en/docs/img/async/concurrent-burgers/concurrent-burgers-06.png
new file mode 100644
index 0000000000000..4bbf247c0f3b5
Binary files /dev/null and b/docs/en/docs/img/async/concurrent-burgers/concurrent-burgers-06.png differ
diff --git a/docs/en/docs/img/async/concurrent-burgers/concurrent-burgers-07.png b/docs/en/docs/img/async/concurrent-burgers/concurrent-burgers-07.png
new file mode 100644
index 0000000000000..7a0f4092d9a38
Binary files /dev/null and b/docs/en/docs/img/async/concurrent-burgers/concurrent-burgers-07.png differ
diff --git a/docs/en/docs/img/async/parallel-burgers/parallel-burgers-01.png b/docs/en/docs/img/async/parallel-burgers/parallel-burgers-01.png
new file mode 100644
index 0000000000000..92fc1a8a0d89c
Binary files /dev/null and b/docs/en/docs/img/async/parallel-burgers/parallel-burgers-01.png differ
diff --git a/docs/en/docs/img/async/parallel-burgers/parallel-burgers-02.png b/docs/en/docs/img/async/parallel-burgers/parallel-burgers-02.png
new file mode 100644
index 0000000000000..9583b84dc239e
Binary files /dev/null and b/docs/en/docs/img/async/parallel-burgers/parallel-burgers-02.png differ
diff --git a/docs/en/docs/img/async/parallel-burgers/parallel-burgers-03.png b/docs/en/docs/img/async/parallel-burgers/parallel-burgers-03.png
new file mode 100644
index 0000000000000..bea9ff0d8039d
Binary files /dev/null and b/docs/en/docs/img/async/parallel-burgers/parallel-burgers-03.png differ
diff --git a/docs/en/docs/img/async/parallel-burgers/parallel-burgers-04.png b/docs/en/docs/img/async/parallel-burgers/parallel-burgers-04.png
new file mode 100644
index 0000000000000..b5c8a60bbeb4a
Binary files /dev/null and b/docs/en/docs/img/async/parallel-burgers/parallel-burgers-04.png differ
diff --git a/docs/en/docs/img/async/parallel-burgers/parallel-burgers-05.png b/docs/en/docs/img/async/parallel-burgers/parallel-burgers-05.png
new file mode 100644
index 0000000000000..45aca8e217fee
Binary files /dev/null and b/docs/en/docs/img/async/parallel-burgers/parallel-burgers-05.png differ
diff --git a/docs/en/docs/img/async/parallel-burgers/parallel-burgers-06.png b/docs/en/docs/img/async/parallel-burgers/parallel-burgers-06.png
new file mode 100644
index 0000000000000..c91c4b472e3d8
Binary files /dev/null and b/docs/en/docs/img/async/parallel-burgers/parallel-burgers-06.png differ
diff --git a/docs/en/docs/img/deployment/concepts/process-ram.drawio b/docs/en/docs/img/deployment/concepts/process-ram.drawio
index 51fc30ed32f68..b29c8a3424519 100644
--- a/docs/en/docs/img/deployment/concepts/process-ram.drawio
+++ b/docs/en/docs/img/deployment/concepts/process-ram.drawio
@@ -103,4 +103,4 @@
-
\ No newline at end of file
+
diff --git a/docs/en/docs/img/deployment/concepts/process-ram.svg b/docs/en/docs/img/deployment/concepts/process-ram.svg
index cd086c36b87a5..c1bf0d5890034 100644
--- a/docs/en/docs/img/deployment/concepts/process-ram.svg
+++ b/docs/en/docs/img/deployment/concepts/process-ram.svg
@@ -56,4 +56,4 @@
}
1 GBViewer does not support full SVG 1.1
diff --git a/docs/en/docs/img/deployment/https/https.drawio b/docs/en/docs/img/deployment/https/https.drawio
index 31cfab96bce3a..c4c8a362816ce 100644
--- a/docs/en/docs/img/deployment/https/https.drawio
+++ b/docs/en/docs/img/deployment/https/https.drawio
@@ -274,4 +274,4 @@
-
\ No newline at end of file
+
diff --git a/docs/en/docs/img/deployment/https/https.svg b/docs/en/docs/img/deployment/https/https.svg
index e63345eba3204..69497518a5517 100644
--- a/docs/en/docs/img/deployment/https/https.svg
+++ b/docs/en/docs/img/deployment/https/https.svg
@@ -59,4 +59,4 @@
TLS HandshakeViewer does not support full SVG 1.1
diff --git a/docs/en/docs/img/deployment/https/https03.drawio b/docs/en/docs/img/deployment/https/https03.drawio
index c5766086c082d..c178fd36314e5 100644
--- a/docs/en/docs/img/deployment/https/https03.drawio
+++ b/docs/en/docs/img/deployment/https/https03.drawio
@@ -128,4 +128,4 @@
-
\ No newline at end of file
+
diff --git a/docs/en/docs/img/deployment/https/https03.svg b/docs/en/docs/img/deployment/https/https03.svg
index e68e1c45964ac..2badd1c7d27ac 100644
--- a/docs/en/docs/img/deployment/https/https03.svg
+++ b/docs/en/docs/img/deployment/https/https03.svg
@@ -59,4 +59,4 @@
IP:...Viewer does not support full SVG 1.1
diff --git a/docs/en/docs/img/deployment/https/https04.drawio b/docs/en/docs/img/deployment/https/https04.drawio
index ea357a6c1b475..78a6e919a04bd 100644
--- a/docs/en/docs/img/deployment/https/https04.drawio
+++ b/docs/en/docs/img/deployment/https/https04.drawio
@@ -149,4 +149,4 @@
-
\ No newline at end of file
+
diff --git a/docs/en/docs/img/deployment/https/https04.svg b/docs/en/docs/img/deployment/https/https04.svg
index 4c9b7999bc0dd..4513ac76b555c 100644
--- a/docs/en/docs/img/deployment/https/https04.svg
+++ b/docs/en/docs/img/deployment/https/https04.svg
@@ -59,4 +59,4 @@
IP:...Viewer does not support full SVG 1.1
diff --git a/docs/en/docs/img/deployment/https/https05.drawio b/docs/en/docs/img/deployment/https/https05.drawio
index 9b8b7c6f710df..236ecd841f471 100644
--- a/docs/en/docs/img/deployment/https/https05.drawio
+++ b/docs/en/docs/img/deployment/https/https05.drawio
@@ -163,4 +163,4 @@
-
\ No newline at end of file
+
diff --git a/docs/en/docs/img/deployment/https/https05.svg b/docs/en/docs/img/deployment/https/https05.svg
index d11647b9b3174..ddcd2760a8068 100644
--- a/docs/en/docs/img/deployment/https/https05.svg
+++ b/docs/en/docs/img/deployment/https/https05.svg
@@ -59,4 +59,4 @@
IP:...Viewer does not support full SVG 1.1
diff --git a/docs/en/docs/img/deployment/https/https06.drawio b/docs/en/docs/img/deployment/https/https06.drawio
index 5bb85813fd5ed..9dec131846f01 100644
--- a/docs/en/docs/img/deployment/https/https06.drawio
+++ b/docs/en/docs/img/deployment/https/https06.drawio
@@ -180,4 +180,4 @@
-
\ No newline at end of file
+
diff --git a/docs/en/docs/img/deployment/https/https06.svg b/docs/en/docs/img/deployment/https/https06.svg
index 10e03b7c5642e..3695de40c725e 100644
--- a/docs/en/docs/img/deployment/https/https06.svg
+++ b/docs/en/docs/img/deployment/https/https06.svg
@@ -59,4 +59,4 @@
IP:...Viewer does not support full SVG 1.1
diff --git a/docs/en/docs/img/deployment/https/https07.drawio b/docs/en/docs/img/deployment/https/https07.drawio
index 1ca994b2236ae..aa8f4d6bedb9c 100644
--- a/docs/en/docs/img/deployment/https/https07.drawio
+++ b/docs/en/docs/img/deployment/https/https07.drawio
@@ -200,4 +200,4 @@
-
\ No newline at end of file
+
diff --git a/docs/en/docs/img/deployment/https/https07.svg b/docs/en/docs/img/deployment/https/https07.svg
index e409d8871332e..551354cef81f7 100644
--- a/docs/en/docs/img/deployment/https/https07.svg
+++ b/docs/en/docs/img/deployment/https/https07.svg
@@ -59,4 +59,4 @@
IP:...Viewer does not support full SVG 1.1
diff --git a/docs/en/docs/img/deployment/https/https08.drawio b/docs/en/docs/img/deployment/https/https08.drawio
index 8a4f41056ca69..794b192dfe10b 100644
--- a/docs/en/docs/img/deployment/https/https08.drawio
+++ b/docs/en/docs/img/deployment/https/https08.drawio
@@ -214,4 +214,4 @@
-
\ No newline at end of file
+
diff --git a/docs/en/docs/img/deployment/https/https08.svg b/docs/en/docs/img/deployment/https/https08.svg
index 3047dd821759b..2d4680dcc23e1 100644
--- a/docs/en/docs/img/deployment/https/https08.svg
+++ b/docs/en/docs/img/deployment/https/https08.svg
@@ -59,4 +59,4 @@
IP:...Viewer does not support full SVG 1.1
diff --git a/docs/en/docs/img/sponsors/docarray-top-banner.svg b/docs/en/docs/img/sponsors/docarray-top-banner.svg
new file mode 100644
index 0000000000000..b2eca354437e6
--- /dev/null
+++ b/docs/en/docs/img/sponsors/docarray-top-banner.svg
@@ -0,0 +1 @@
+
diff --git a/docs/en/docs/img/sponsors/docarray.svg b/docs/en/docs/img/sponsors/docarray.svg
new file mode 100644
index 0000000000000..f18df247e833f
--- /dev/null
+++ b/docs/en/docs/img/sponsors/docarray.svg
@@ -0,0 +1 @@
+
diff --git a/docs/en/docs/img/sponsors/doist-banner.svg b/docs/en/docs/img/sponsors/doist-banner.svg
new file mode 100644
index 0000000000000..3a4d9a2954e37
--- /dev/null
+++ b/docs/en/docs/img/sponsors/doist-banner.svg
@@ -0,0 +1,46 @@
+
diff --git a/docs/en/docs/img/sponsors/doist.svg b/docs/en/docs/img/sponsors/doist.svg
new file mode 100644
index 0000000000000..b55855f0673d0
--- /dev/null
+++ b/docs/en/docs/img/sponsors/doist.svg
@@ -0,0 +1,54 @@
+
diff --git a/docs/en/docs/img/sponsors/imgwhale-banner.svg b/docs/en/docs/img/sponsors/imgwhale-banner.svg
new file mode 100644
index 0000000000000..db87cc4c99329
--- /dev/null
+++ b/docs/en/docs/img/sponsors/imgwhale-banner.svg
@@ -0,0 +1,14 @@
+
diff --git a/docs/en/docs/img/sponsors/imgwhale.svg b/docs/en/docs/img/sponsors/imgwhale.svg
new file mode 100644
index 0000000000000..46aefd9305adb
--- /dev/null
+++ b/docs/en/docs/img/sponsors/imgwhale.svg
@@ -0,0 +1,28 @@
+
diff --git a/docs/en/docs/img/sponsors/jina-ai-banner.png b/docs/en/docs/img/sponsors/jina-ai-banner.png
new file mode 100644
index 0000000000000..3ac6b44adcf4b
Binary files /dev/null and b/docs/en/docs/img/sponsors/jina-ai-banner.png differ
diff --git a/docs/en/docs/img/sponsors/jina-ai.png b/docs/en/docs/img/sponsors/jina-ai.png
new file mode 100644
index 0000000000000..d6b0bfb4ec24a
Binary files /dev/null and b/docs/en/docs/img/sponsors/jina-ai.png differ
diff --git a/docs/en/docs/img/sponsors/jina-top-banner.svg b/docs/en/docs/img/sponsors/jina-top-banner.svg
new file mode 100644
index 0000000000000..8b62cd61978d2
--- /dev/null
+++ b/docs/en/docs/img/sponsors/jina-top-banner.svg
@@ -0,0 +1 @@
+
diff --git a/docs/en/docs/img/sponsors/jina2.svg b/docs/en/docs/img/sponsors/jina2.svg
new file mode 100644
index 0000000000000..6a48677baa98e
--- /dev/null
+++ b/docs/en/docs/img/sponsors/jina2.svg
@@ -0,0 +1 @@
+
diff --git a/docs/en/docs/img/sponsors/striveworks2.png b/docs/en/docs/img/sponsors/striveworks2.png
new file mode 100644
index 0000000000000..bed9cb0a773a4
Binary files /dev/null and b/docs/en/docs/img/sponsors/striveworks2.png differ
diff --git a/docs/en/docs/img/sponsors/testdriven.svg b/docs/en/docs/img/sponsors/testdriven.svg
index 97741b9e03d7a..6ba2daa3b9d4d 100644
--- a/docs/en/docs/img/sponsors/testdriven.svg
+++ b/docs/en/docs/img/sponsors/testdriven.svg
@@ -1 +1 @@
-
\ No newline at end of file
+
diff --git a/docs/en/docs/img/tutorial/bigger-applications/package.drawio b/docs/en/docs/img/tutorial/bigger-applications/package.drawio
index 48f6e76fe035a..cab3de2ca8376 100644
--- a/docs/en/docs/img/tutorial/bigger-applications/package.drawio
+++ b/docs/en/docs/img/tutorial/bigger-applications/package.drawio
@@ -40,4 +40,4 @@
-
\ No newline at end of file
+
diff --git a/docs/en/docs/img/tutorial/bigger-applications/package.svg b/docs/en/docs/img/tutorial/bigger-applications/package.svg
index a9cec926a84aa..44da1dc30dd41 100644
--- a/docs/en/docs/img/tutorial/bigger-applications/package.svg
+++ b/docs/en/docs/img/tutorial/bigger-applications/package.svg
@@ -1 +1 @@
-
\ No newline at end of file
+
diff --git a/docs/en/docs/index.md b/docs/en/docs/index.md
index 7de1e50df5627..17163ba014673 100644
--- a/docs/en/docs/index.md
+++ b/docs/en/docs/index.md
@@ -148,7 +148,7 @@ $ pip install "uvicorn[standard]"
* Create a file `main.py` with:
```Python
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
@@ -161,7 +161,7 @@ def read_root():
@app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
```
@@ -171,7 +171,7 @@ def read_item(item_id: int, q: Optional[str] = None):
If your code uses `async` / `await`, use `async def`:
```Python hl_lines="9 14"
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
@@ -184,7 +184,7 @@ async def read_root():
@app.get("/items/{item_id}")
-async def read_item(item_id: int, q: Optional[str] = None):
+async def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
```
@@ -263,7 +263,7 @@ Now modify the file `main.py` to receive a body from a `PUT` request.
Declare the body using standard Python types, thanks to Pydantic.
```Python hl_lines="4 9-12 25-27"
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
from pydantic import BaseModel
@@ -274,7 +274,7 @@ app = FastAPI()
class Item(BaseModel):
name: str
price: float
- is_offer: Optional[bool] = None
+ is_offer: Union[bool, None] = None
@app.get("/")
@@ -283,7 +283,7 @@ def read_root():
@app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
diff --git a/docs/en/docs/js/termynal.js b/docs/en/docs/js/termynal.js
index 8b0e9339e8772..4ac32708a31a0 100644
--- a/docs/en/docs/js/termynal.js
+++ b/docs/en/docs/js/termynal.js
@@ -72,14 +72,14 @@ class Termynal {
* Initialise the widget, get lines, clear container and start animation.
*/
init() {
- /**
+ /**
* Calculates width and height of Termynal container.
* If container is empty and lines are dynamically loaded, defaults to browser `auto` or CSS.
- */
+ */
const containerStyle = getComputedStyle(this.container);
- this.container.style.width = containerStyle.width !== '0px' ?
+ this.container.style.width = containerStyle.width !== '0px' ?
containerStyle.width : undefined;
- this.container.style.minHeight = containerStyle.height !== '0px' ?
+ this.container.style.minHeight = containerStyle.height !== '0px' ?
containerStyle.height : undefined;
this.container.setAttribute('data-termynal', '');
@@ -138,7 +138,7 @@ class Termynal {
restart.innerHTML = "restart ↻"
return restart
}
-
+
generateFinish() {
const finish = document.createElement('a')
finish.onclick = (e) => {
@@ -215,7 +215,7 @@ class Termynal {
/**
* Converts line data objects into line elements.
- *
+ *
* @param {Object[]} lineData - Dynamically loaded lines.
* @param {Object} line - Line data object.
* @returns {Element[]} - Array of line elements.
@@ -231,7 +231,7 @@ class Termynal {
/**
* Helper function for generating attributes string.
- *
+ *
* @param {Object} line - Line data object.
* @returns {string} - String of attributes.
*/
diff --git a/docs/en/docs/python-types.md b/docs/en/docs/python-types.md
index b86a0fa0ed059..87fdd6d8d15cc 100644
--- a/docs/en/docs/python-types.md
+++ b/docs/en/docs/python-types.md
@@ -29,7 +29,7 @@ Calling this program outputs:
John Doe
```
-The function does the following:
+The function does the following:
* Takes a `first_name` and `last_name`.
* Converts the first letter of each one to upper case with `title()`.
@@ -267,7 +267,7 @@ You can declare that a variable can be any of **several types**, for example, an
In Python 3.6 and above (including Python 3.10) you can use the `Union` type from `typing` and put inside the square brackets the possible types to accept.
-In Python 3.10 there's also an **alternative syntax** were you can put the possible types separated by a vertical bar (`|`).
+In Python 3.10 there's also an **alternative syntax** where you can put the possible types separated by a vertical bar (`|`).
=== "Python 3.6 and above"
@@ -317,6 +317,45 @@ This also means that in Python 3.10, you can use `Something | None`:
{!> ../../../docs_src/python_types/tutorial009_py310.py!}
```
+#### Using `Union` or `Optional`
+
+If you are using a Python version below 3.10, here's a tip from my very **subjective** point of view:
+
+* 🚨 Avoid using `Optional[SomeType]`
+* Instead ✨ **use `Union[SomeType, None]`** ✨.
+
+Both are equivalent and underneath they are the same, but I would recommend `Union` instead of `Optional` because the word "**optional**" would seem to imply that the value is optional, and it actually means "it can be `None`", even if it's not optional and is still required.
+
+I think `Union[SomeType, None]` is more explicit about what it means.
+
+It's just about the words and names. But those words can affect how you and your teammates think about the code.
+
+As an example, let's take this function:
+
+```Python hl_lines="1 4"
+{!../../../docs_src/python_types/tutorial009c.py!}
+```
+
+The parameter `name` is defined as `Optional[str]`, but it is **not optional**, you cannot call the function without the parameter:
+
+```Python
+say_hi() # Oh, no, this throws an error! 😱
+```
+
+The `name` parameter is **still required** (not *optional*) because it doesn't have a default value. Still, `name` accepts `None` as the value:
+
+```Python
+say_hi(name=None) # This works, None is valid 🎉
+```
+
+The good news is, once you are on Python 3.10 you won't have to worry about that, as you will be able to simply use `|` to define unions of types:
+
+```Python hl_lines="1 4"
+{!../../../docs_src/python_types/tutorial009c_py310.py!}
+```
+
+And then you won't have to worry about names like `Optional` and `Union`. 😎
+
#### Generic types
These types that take type parameters in square brackets are called **Generic types** or **Generics**, for example:
@@ -334,14 +373,14 @@ These types that take type parameters in square brackets are called **Generic ty
=== "Python 3.9 and above"
You can use the same builtin types as generics (with square brakets and types inside):
-
+
* `list`
* `tuple`
* `set`
* `dict`
And the same as with Python 3.6, from the `typing` module:
-
+
* `Union`
* `Optional`
* ...and others.
@@ -354,7 +393,7 @@ These types that take type parameters in square brackets are called **Generic ty
* `tuple`
* `set`
* `dict`
-
+
And the same as with Python 3.6, from the `typing` module:
* `Union`
@@ -422,6 +461,9 @@ An example from the official Pydantic docs:
You will see a lot more of all this in practice in the [Tutorial - User Guide](tutorial/index.md){.internal-link target=_blank}.
+!!! tip
+ Pydantic has a special behavior when you use `Optional` or `Union[Something, None]` without a default value, you can read more about it in the Pydantic docs about Required Optional fields.
+
## Type hints in **FastAPI**
**FastAPI** takes advantage of these type hints to do several things.
diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md
index 4d8bacf4c7aa0..74efd542ffc20 100644
--- a/docs/en/docs/release-notes.md
+++ b/docs/en/docs/release-notes.md
@@ -2,6 +2,280 @@
## Latest Changes
+* ♻ Move internal variable for errors in `jsonable_encoder` to put related code closer. PR [#4560](https://github.com/tiangolo/fastapi/pull/4560) by [@GuilleQP](https://github.com/GuilleQP).
+* ♻ Simplify conditional assignment in `fastapi/dependencies/utils.py`. PR [#4597](https://github.com/tiangolo/fastapi/pull/4597) by [@cikay](https://github.com/cikay).
+* 🎨 Fix syntax highlighting in docs for OpenAPI Callbacks. PR [#4368](https://github.com/tiangolo/fastapi/pull/4368) by [@xncbf](https://github.com/xncbf).
+* ⬆ Upgrade version pin accepted for Flake8, for internal code, to `flake8 >=3.8.3,<6.0.0`. PR [#4097](https://github.com/tiangolo/fastapi/pull/4097) by [@jamescurtin](https://github.com/jamescurtin).
+* 🐛 Fix support for extending `openapi_extras` with parameter lists. PR [#4267](https://github.com/tiangolo/fastapi/pull/4267) by [@orilevari](https://github.com/orilevari).
+* ✨ Add support for `FrozenSet` in parameters (e.g. query). PR [#2938](https://github.com/tiangolo/fastapi/pull/2938) by [@juntatalor](https://github.com/juntatalor).
+* ✨ Allow custom middlewares to raise `HTTPException`s and propagate them. PR [#2036](https://github.com/tiangolo/fastapi/pull/2036) by [@ghandic](https://github.com/ghandic).
+* ✨ Preserve `json.JSONDecodeError` information when handling invalid JSON in request body, to support custom exception handlers that use its information. PR [#4057](https://github.com/tiangolo/fastapi/pull/4057) by [@UKnowWhoIm](https://github.com/UKnowWhoIm).
+* ✏ Reword confusing sentence in docs file `typo-fix-path-params-numeric-validations.md`. PR [#3219](https://github.com/tiangolo/fastapi/pull/3219) by [@ccrenfroe](https://github.com/ccrenfroe).
+* 📝 Update docs for handling HTTP Basic Auth with `secrets.compare_digest()` to account for non-ASCII characters. PR [#3536](https://github.com/tiangolo/fastapi/pull/3536) by [@lewoudar](https://github.com/lewoudar).
+* 📝 Update docs for testing, fix examples with relative imports. PR [#5302](https://github.com/tiangolo/fastapi/pull/5302) by [@tiangolo](https://github.com/tiangolo).
+* 🍱 Update Jina banner, fix typo. PR [#5301](https://github.com/tiangolo/fastapi/pull/5301) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.80.0
+
+### Breaking Changes - Fixes
+
+* 🐛 Fix `response_model` not invalidating `None`. PR [#2725](https://github.com/tiangolo/fastapi/pull/2725) by [@hukkin](https://github.com/hukkin).
+
+If you are using `response_model` with some type that doesn't include `None` but the function is returning `None`, it will now raise an internal server error, because you are returning invalid data that violates the contract in `response_model`. Before this release it would allow breaking that contract returning `None`.
+
+For example, if you have an app like this:
+
+```Python
+from fastapi import FastAPI
+from pydantic import BaseModel
+
+class Item(BaseModel):
+ name: str
+ price: Optional[float] = None
+ owner_ids: Optional[List[int]] = None
+
+app = FastAPI()
+
+@app.get("/items/invalidnone", response_model=Item)
+def get_invalid_none():
+ return None
+```
+
+...calling the path `/items/invalidnone` will raise an error, because `None` is not a valid type for the `response_model` declared with `Item`.
+
+You could also be implicitly returning `None` without realizing, for example:
+
+```Python
+from fastapi import FastAPI
+from pydantic import BaseModel
+
+class Item(BaseModel):
+ name: str
+ price: Optional[float] = None
+ owner_ids: Optional[List[int]] = None
+
+app = FastAPI()
+
+@app.get("/items/invalidnone", response_model=Item)
+def get_invalid_none():
+ if flag:
+ return {"name": "foo"}
+ # if flag is False, at this point the function will implicitly return None
+```
+
+If you have *path operations* using `response_model` that need to be allowed to return `None`, make it explicit in `response_model` using `Union[Something, None]`:
+
+```Python
+from typing import Union
+
+from fastapi import FastAPI
+from pydantic import BaseModel
+
+class Item(BaseModel):
+ name: str
+ price: Optional[float] = None
+ owner_ids: Optional[List[int]] = None
+
+app = FastAPI()
+
+@app.get("/items/invalidnone", response_model=Union[Item, None])
+def get_invalid_none():
+ return None
+```
+
+This way the data will be correctly validated, you won't have an internal server error, and the documentation will also reflect that this *path operation* could return `None` (or `null` in JSON).
+
+### Fixes
+
+* ⬆ Upgrade Swagger UI copy of `oauth2-redirect.html` to include fixes for flavors of authorization code flows in Swagger UI. PR [#3439](https://github.com/tiangolo/fastapi/pull/3439) initial PR by [@koonpeng](https://github.com/koonpeng).
+* ♻ Strip empty whitespace from description extracted from docstrings. PR [#2821](https://github.com/tiangolo/fastapi/pull/2821) by [@and-semakin](https://github.com/and-semakin).
+* 🐛 Fix cached dependencies when using a dependency in `Security()` and other places (e.g. `Depends()`) with different OAuth2 scopes. PR [#2945](https://github.com/tiangolo/fastapi/pull/2945) by [@laggardkernel](https://github.com/laggardkernel).
+* 🎨 Update type annotations for `response_model`, allow things like `Union[str, None]`. PR [#5294](https://github.com/tiangolo/fastapi/pull/5294) by [@tiangolo](https://github.com/tiangolo).
+
+### Translations
+
+* 🌐 Fix typos in German translation for `docs/de/docs/features.md`. PR [#4533](https://github.com/tiangolo/fastapi/pull/4533) by [@0xflotus](https://github.com/0xflotus).
+* 🌐 Add missing navigator for `encoder.md` in Korean translation. PR [#5238](https://github.com/tiangolo/fastapi/pull/5238) by [@joonas-yoon](https://github.com/joonas-yoon).
+* (Empty PR merge by accident) [#4913](https://github.com/tiangolo/fastapi/pull/4913).
+
+## 0.79.1
+
+### Fixes
+
+* 🐛 Fix `jsonable_encoder` using `include` and `exclude` parameters for non-Pydantic objects. PR [#2606](https://github.com/tiangolo/fastapi/pull/2606) by [@xaviml](https://github.com/xaviml).
+* 🐛 Fix edge case with repeated aliases names not shown in OpenAPI. PR [#2351](https://github.com/tiangolo/fastapi/pull/2351) by [@klaa97](https://github.com/klaa97).
+* 📝 Add misc dependency installs to tutorial docs. PR [#2126](https://github.com/tiangolo/fastapi/pull/2126) by [@TeoZosa](https://github.com/TeoZosa).
+
+### Docs
+
+* 📝 Add note giving credit for illustrations to [Ketrina Thompson](https://www.instagram.com/ketrinadrawsalot/). PR [#5284](https://github.com/tiangolo/fastapi/pull/5284) by [@tiangolo](https://github.com/tiangolo).
+* ✏ Fix typo in `python-types.md`. PR [#5116](https://github.com/tiangolo/fastapi/pull/5116) by [@Kludex](https://github.com/Kludex).
+* ✏ Fix typo in `docs/en/docs/python-types.md`. PR [#5007](https://github.com/tiangolo/fastapi/pull/5007) by [@atiabbz](https://github.com/atiabbz).
+* 📝 Remove unneeded Django/Flask references from async topic intro. PR [#5280](https://github.com/tiangolo/fastapi/pull/5280) by [@carltongibson](https://github.com/carltongibson).
+* ✨ Add illustrations for Concurrent burgers and Parallel burgers. PR [#5277](https://github.com/tiangolo/fastapi/pull/5277) by [@tiangolo](https://github.com/tiangolo). Updated docs at: [Concurrency and Burgers](https://fastapi.tiangolo.com/async/#concurrency-and-burgers).
+
+### Translations
+
+* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/query-params.md`. PR [#4775](https://github.com/tiangolo/fastapi/pull/4775) by [@batlopes](https://github.com/batlopes).
+* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/security/first-steps.md`. PR [#4954](https://github.com/tiangolo/fastapi/pull/4954) by [@FLAIR7](https://github.com/FLAIR7).
+* 🌐 Add translation for `docs/zh/docs/advanced/response-cookies.md`. PR [#4638](https://github.com/tiangolo/fastapi/pull/4638) by [@zhangbo2012](https://github.com/zhangbo2012).
+* 🌐 Add French translation for `docs/fr/docs/deployment/index.md`. PR [#3689](https://github.com/tiangolo/fastapi/pull/3689) by [@rjNemo](https://github.com/rjNemo).
+* 🌐 Add Portuguese translation for `tutorial/handling-errors.md`. PR [#4769](https://github.com/tiangolo/fastapi/pull/4769) by [@frnsimoes](https://github.com/frnsimoes).
+* 🌐 Add French translation for `docs/fr/docs/history-design-future.md`. PR [#3451](https://github.com/tiangolo/fastapi/pull/3451) by [@rjNemo](https://github.com/rjNemo).
+* 🌐 Add Russian translation for `docs/ru/docs/tutorial/background-tasks.md`. PR [#4854](https://github.com/tiangolo/fastapi/pull/4854) by [@AdmiralDesu](https://github.com/AdmiralDesu).
+* 🌐 Add Chinese translation for `docs/tutorial/security/first-steps.md`. PR [#3841](https://github.com/tiangolo/fastapi/pull/3841) by [@jaystone776](https://github.com/jaystone776).
+* 🌐 Add Japanese translation for `docs/ja/docs/advanced/nosql-databases.md`. PR [#4205](https://github.com/tiangolo/fastapi/pull/4205) by [@sUeharaE4](https://github.com/sUeharaE4).
+* 🌐 Add Indonesian translation for `docs/id/docs/tutorial/index.md`. PR [#4705](https://github.com/tiangolo/fastapi/pull/4705) by [@bas-baskara](https://github.com/bas-baskara).
+* 🌐 Add Persian translation for `docs/fa/docs/index.md` and tweak right-to-left CSS. PR [#2395](https://github.com/tiangolo/fastapi/pull/2395) by [@mohsen-mahmoodi](https://github.com/mohsen-mahmoodi).
+
+### Internal
+
+* 🔧 Update Jina sponsorship. PR [#5283](https://github.com/tiangolo/fastapi/pull/5283) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update Jina sponsorship. PR [#5272](https://github.com/tiangolo/fastapi/pull/5272) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update sponsors, Striveworks badge. PR [#5179](https://github.com/tiangolo/fastapi/pull/5179) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.79.0
+
+### Fixes - Breaking Changes
+
+* 🐛 Fix removing body from status codes that do not support it. PR [#5145](https://github.com/tiangolo/fastapi/pull/5145) by [@tiangolo](https://github.com/tiangolo).
+ * Setting `status_code` to `204`, `304`, or any code below `200` (1xx) will remove the body from the response.
+ * This fixes an error in Uvicorn that otherwise would be thrown: `RuntimeError: Response content longer than Content-Length`.
+ * This removes `fastapi.openapi.constants.STATUS_CODES_WITH_NO_BODY`, it is replaced by a function in utils.
+
+### Translations
+
+* 🌐 Start of Hebrew translation. PR [#5050](https://github.com/tiangolo/fastapi/pull/5050) by [@itay-raveh](https://github.com/itay-raveh).
+* 🔧 Add config for Swedish translations notification. PR [#5147](https://github.com/tiangolo/fastapi/pull/5147) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Start of Swedish translation. PR [#5062](https://github.com/tiangolo/fastapi/pull/5062) by [@MrRawbin](https://github.com/MrRawbin).
+* 🌐 Add Japanese translation for `docs/ja/docs/advanced/index.md`. PR [#5043](https://github.com/tiangolo/fastapi/pull/5043) by [@wakabame](https://github.com/wakabame).
+* 🌐🇵🇱 Add Polish translation for `docs/pl/docs/tutorial/first-steps.md`. PR [#5024](https://github.com/tiangolo/fastapi/pull/5024) by [@Valaraucoo](https://github.com/Valaraucoo).
+
+### Internal
+
+* 🔧 Update translations notification for Hebrew. PR [#5158](https://github.com/tiangolo/fastapi/pull/5158) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update Dependabot commit message. PR [#5156](https://github.com/tiangolo/fastapi/pull/5156) by [@tiangolo](https://github.com/tiangolo).
+* ⬆ Bump actions/upload-artifact from 2 to 3. PR [#5148](https://github.com/tiangolo/fastapi/pull/5148) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump actions/cache from 2 to 3. PR [#5149](https://github.com/tiangolo/fastapi/pull/5149) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* 🔧 Update sponsors badge configs. PR [#5155](https://github.com/tiangolo/fastapi/pull/5155) by [@tiangolo](https://github.com/tiangolo).
+* 👥 Update FastAPI People. PR [#5154](https://github.com/tiangolo/fastapi/pull/5154) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update Jina sponsor badges. PR [#5151](https://github.com/tiangolo/fastapi/pull/5151) by [@tiangolo](https://github.com/tiangolo).
+* ⬆ Bump actions/checkout from 2 to 3. PR [#5133](https://github.com/tiangolo/fastapi/pull/5133) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#5030](https://github.com/tiangolo/fastapi/pull/5030) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
+* ⬆ Bump nwtgck/actions-netlify from 1.1.5 to 1.2.3. PR [#5132](https://github.com/tiangolo/fastapi/pull/5132) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump codecov/codecov-action from 2 to 3. PR [#5131](https://github.com/tiangolo/fastapi/pull/5131) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump dawidd6/action-download-artifact from 2.9.0 to 2.21.1. PR [#5130](https://github.com/tiangolo/fastapi/pull/5130) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump actions/setup-python from 2 to 4. PR [#5129](https://github.com/tiangolo/fastapi/pull/5129) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* 👷 Add Dependabot. PR [#5128](https://github.com/tiangolo/fastapi/pull/5128) by [@tiangolo](https://github.com/tiangolo).
+* ♻️ Move from `Optional[X]` to `Union[X, None]` for internal utils. PR [#5124](https://github.com/tiangolo/fastapi/pull/5124) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update sponsors, remove Dropbase, add Doist. PR [#5096](https://github.com/tiangolo/fastapi/pull/5096) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update sponsors, remove Classiq, add ImgWhale. PR [#5079](https://github.com/tiangolo/fastapi/pull/5079) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.78.0
+
+### Features
+
+* ✨ Add support for omitting `...` as default value when declaring required parameters with:
+
+* `Path()`
+* `Query()`
+* `Header()`
+* `Cookie()`
+* `Body()`
+* `Form()`
+* `File()`
+
+New docs at [Tutorial - Query Parameters and String Validations - Make it required](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#make-it-required). PR [#4906](https://github.com/tiangolo/fastapi/pull/4906) by [@tiangolo](https://github.com/tiangolo).
+
+Up to now, declaring a required parameter while adding additional validation or metadata needed using `...` (Ellipsis).
+
+For example:
+
+```Python
+from fastapi import Cookie, FastAPI, Header, Path, Query
+
+app = FastAPI()
+
+
+@app.get("/items/{item_id}")
+def main(
+ item_id: int = Path(default=..., gt=0),
+ query: str = Query(default=..., max_length=10),
+ session: str = Cookie(default=..., min_length=3),
+ x_trace: str = Header(default=..., title="Tracing header"),
+):
+ return {"message": "Hello World"}
+```
+
+...all these parameters are required because the default value is `...` (Ellipsis).
+
+But now it's possible and supported to just omit the default value, as would be done with Pydantic fields, and the parameters would still be required.
+
+✨ For example, this is now supported:
+
+```Python
+from fastapi import Cookie, FastAPI, Header, Path, Query
+
+app = FastAPI()
+
+
+@app.get("/items/{item_id}")
+def main(
+ item_id: int = Path(gt=0),
+ query: str = Query(max_length=10),
+ session: str = Cookie(min_length=3),
+ x_trace: str = Header(title="Tracing header"),
+):
+ return {"message": "Hello World"}
+```
+
+To declare parameters as optional (not required), you can set a default value as always, for example using `None`:
+
+```Python
+from typing import Union
+from fastapi import Cookie, FastAPI, Header, Path, Query
+
+app = FastAPI()
+
+
+@app.get("/items/{item_id}")
+def main(
+ item_id: int = Path(gt=0),
+ query: Union[str, None] = Query(default=None, max_length=10),
+ session: Union[str, None] = Cookie(default=None, min_length=3),
+ x_trace: Union[str, None] = Header(default=None, title="Tracing header"),
+):
+ return {"message": "Hello World"}
+```
+
+### Docs
+
+* 📝 Add docs recommending `Union` over `Optional` and migrate source examples. New docs at [Python Types Intro - Using `Union` or `Optional`](https://fastapi.tiangolo.com/python-types/#using-union-or-optional). PR [#4908](https://github.com/tiangolo/fastapi/pull/4908) by [@tiangolo](https://github.com/tiangolo).
+* 🎨 Fix default value as set in tutorial for Path Operations Advanced Configurations. PR [#4899](https://github.com/tiangolo/fastapi/pull/4899) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Add documentation for redefined path operations. PR [#4864](https://github.com/tiangolo/fastapi/pull/4864) by [@madkinsz](https://github.com/madkinsz).
+* 📝 Updates links for Celery documentation. PR [#4736](https://github.com/tiangolo/fastapi/pull/4736) by [@sammyzord](https://github.com/sammyzord).
+* ✏ Fix example code with sets in tutorial for body nested models. PR [#3030](https://github.com/tiangolo/fastapi/pull/3030) by [@hitrust](https://github.com/hitrust).
+* ✏ Fix links to Pydantic docs. PR [#4670](https://github.com/tiangolo/fastapi/pull/4670) by [@kinuax](https://github.com/kinuax).
+* 📝 Update docs about Swagger UI self-hosting with newer source links. PR [#4813](https://github.com/tiangolo/fastapi/pull/4813) by [@Kastakin](https://github.com/Kastakin).
+* 📝 Add link to external article: Building the Poll App From Django Tutorial With FastAPI And React. PR [#4778](https://github.com/tiangolo/fastapi/pull/4778) by [@jbrocher](https://github.com/jbrocher).
+* 📝 Add OpenAPI warning to "Body - Fields" docs with extra schema extensions. PR [#4846](https://github.com/tiangolo/fastapi/pull/4846) by [@ml-evs](https://github.com/ml-evs).
+
+### Translations
+
+* 🌐 Fix code examples in Japanese translation for `docs/ja/docs/tutorial/testing.md`. PR [#4623](https://github.com/tiangolo/fastapi/pull/4623) by [@hirotoKirimaru](https://github.com/hirotoKirimaru).
+
+### Internal
+
+* ♻ Refactor dict value extraction to minimize key lookups `fastapi/utils.py`. PR [#3139](https://github.com/tiangolo/fastapi/pull/3139) by [@ShahriyarR](https://github.com/ShahriyarR).
+* ✅ Add tests for required nonable parameters and body fields. PR [#4907](https://github.com/tiangolo/fastapi/pull/4907) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Fix installing Material for MkDocs Insiders in CI. PR [#4897](https://github.com/tiangolo/fastapi/pull/4897) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Add pre-commit CI instead of custom GitHub Action. PR [#4896](https://github.com/tiangolo/fastapi/pull/4896) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Add pre-commit GitHub Action workflow. PR [#4895](https://github.com/tiangolo/fastapi/pull/4895) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Add dark mode auto switch to docs based on OS preference. PR [#4869](https://github.com/tiangolo/fastapi/pull/4869) by [@ComicShrimp](https://github.com/ComicShrimp).
+* 🔥 Remove un-used old pending tests, already covered in other places. PR [#4891](https://github.com/tiangolo/fastapi/pull/4891) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Add Python formatting hooks to pre-commit. PR [#4890](https://github.com/tiangolo/fastapi/pull/4890) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Add pre-commit with first config and first formatting pass. PR [#4888](https://github.com/tiangolo/fastapi/pull/4888) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Disable CI installing Material for MkDocs in forks. PR [#4410](https://github.com/tiangolo/fastapi/pull/4410) by [@dolfinus](https://github.com/dolfinus).
## 0.77.1
diff --git a/docs/en/docs/tutorial/background-tasks.md b/docs/en/docs/tutorial/background-tasks.md
index 69aeb6712c70a..191a4ca0fbce0 100644
--- a/docs/en/docs/tutorial/background-tasks.md
+++ b/docs/en/docs/tutorial/background-tasks.md
@@ -89,7 +89,7 @@ You can see more details in Celery.
+If you need to perform heavy background computation and you don't necessarily need it to be run by the same process (for example, you don't need to share memory, variables, etc), you might benefit from using other bigger tools like Celery.
They tend to require more complex configurations, a message/job queue manager, like RabbitMQ or Redis, but they allow you to run background tasks in multiple processes, and especially, in multiple servers.
diff --git a/docs/en/docs/tutorial/bigger-applications.md b/docs/en/docs/tutorial/bigger-applications.md
index 2a2e764b5988d..d201953df4eb1 100644
--- a/docs/en/docs/tutorial/bigger-applications.md
+++ b/docs/en/docs/tutorial/bigger-applications.md
@@ -334,7 +334,7 @@ from app.routers import items, users
```Python
from .routers import items, users
```
-
+
The second version is an "absolute import":
```Python
diff --git a/docs/en/docs/tutorial/body-fields.md b/docs/en/docs/tutorial/body-fields.md
index 1f38a0c5c566f..0cfe576d68d72 100644
--- a/docs/en/docs/tutorial/body-fields.md
+++ b/docs/en/docs/tutorial/body-fields.md
@@ -57,6 +57,10 @@ You can declare extra information in `Field`, `Query`, `Body`, etc. And it will
You will learn more about adding extra information later in the docs, when learning to declare examples.
+!!! warning
+ Extra keys passed to `Field` will also be present in the resulting OpenAPI schema for your application.
+ As these keys may not necessarily be part of the OpenAPI specification, some OpenAPI tools, for example [the OpenAPI validator](https://validator.swagger.io/), may not work with your generated schema.
+
## Recap
You can use Pydantic's `Field` to declare extra validations and metadata for model attributes.
diff --git a/docs/en/docs/tutorial/body-multiple-params.md b/docs/en/docs/tutorial/body-multiple-params.md
index 13de4c8eab531..31dd27fed45a4 100644
--- a/docs/en/docs/tutorial/body-multiple-params.md
+++ b/docs/en/docs/tutorial/body-multiple-params.md
@@ -89,13 +89,13 @@ But you can instruct **FastAPI** to treat it as another body key using `Body`:
=== "Python 3.6 and above"
- ```Python hl_lines="23"
+ ```Python hl_lines="22"
{!> ../../../docs_src/body_multiple_params/tutorial003.py!}
```
=== "Python 3.10 and above"
- ```Python hl_lines="21"
+ ```Python hl_lines="20"
{!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!}
```
@@ -126,7 +126,7 @@ Of course, you can also declare additional query parameters whenever you need, a
As, by default, singular values are interpreted as query parameters, you don't have to explicitly add a `Query`, you can just do:
```Python
-q: Optional[str] = None
+q: Union[str, None] = None
```
Or in Python 3.10 and above:
@@ -139,7 +139,7 @@ For example:
=== "Python 3.6 and above"
- ```Python hl_lines="28"
+ ```Python hl_lines="27"
{!> ../../../docs_src/body_multiple_params/tutorial004.py!}
```
@@ -152,7 +152,6 @@ For example:
!!! info
`Body` also has all the same extra validation and metadata parameters as `Query`,`Path` and others you will see later.
-
## Embed a single body parameter
Let's say you only have a single `item` body parameter from a Pydantic model `Item`.
@@ -162,7 +161,7 @@ By default, **FastAPI** will then expect its body directly.
But if you want it to expect a JSON with a key `item` and inside of it the model contents, as it does when you declare extra body parameters, you can use the special `Body` parameter `embed`:
```Python
-item: Item = Body(..., embed=True)
+item: Item = Body(embed=True)
```
as in:
diff --git a/docs/en/docs/tutorial/body-nested-models.md b/docs/en/docs/tutorial/body-nested-models.md
index fa38cfc4883f5..bfc948f4fadc2 100644
--- a/docs/en/docs/tutorial/body-nested-models.md
+++ b/docs/en/docs/tutorial/body-nested-models.md
@@ -366,7 +366,7 @@ In this case, you would accept any `dict` as long as it has `int` keys with `flo
But Pydantic has automatic data conversion.
This means that, even though your API clients can only send strings as keys, as long as those strings contain pure integers, Pydantic will convert them and validate them.
-
+
And the `dict` you receive as `weights` will actually have `int` keys and `float` values.
## Recap
diff --git a/docs/en/docs/tutorial/body.md b/docs/en/docs/tutorial/body.md
index 81441b41eb2aa..5090059360ba7 100644
--- a/docs/en/docs/tutorial/body.md
+++ b/docs/en/docs/tutorial/body.md
@@ -138,7 +138,7 @@ But you would get the same editor support with PyCharm as your editor, you can use the Pydantic PyCharm Plugin.
It improves editor support for Pydantic models, with:
-
+
* auto-completion
* type checks
* refactoring
@@ -206,7 +206,7 @@ The function parameters will be recognized as follows:
!!! note
FastAPI will know that the value of `q` is not required because of the default value `= None`.
- The `Optional` in `Optional[str]` is not used by FastAPI, but will allow your editor to give you better support and detect errors.
+ The `Union` in `Union[str, None]` is not used by FastAPI, but will allow your editor to give you better support and detect errors.
## Without Pydantic
diff --git a/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md
index 663fff15bf3f5..fb41ba1f67e2f 100644
--- a/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md
+++ b/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md
@@ -109,7 +109,7 @@ Pay attention to the `__init__` method used to create the instance of the class:
=== "Python 3.6 and above"
- ```Python hl_lines="8"
+ ```Python hl_lines="9"
{!> ../../../docs_src/dependencies/tutorial001.py!}
```
diff --git a/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md
index ac2e9cb8cb4c4..a7300f0b7a68d 100644
--- a/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md
+++ b/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md
@@ -10,7 +10,7 @@ To do this, use `yield` instead of `return`, and write the extra steps after.
!!! note "Technical Details"
Any function that is valid to use with:
- * `@contextlib.contextmanager` or
+ * `@contextlib.contextmanager` or
* `@contextlib.asynccontextmanager`
would be valid to use as a **FastAPI** dependency.
@@ -207,7 +207,7 @@ You can also use them inside of **FastAPI** dependencies with `yield` by using
!!! tip
Another way to create a context manager is with:
- * `@contextlib.contextmanager` or
+ * `@contextlib.contextmanager` or
* `@contextlib.asynccontextmanager`
using them to decorate a function with a single `yield`.
diff --git a/docs/en/docs/tutorial/dependencies/index.md b/docs/en/docs/tutorial/dependencies/index.md
index fe10facfbc365..5078c00968362 100644
--- a/docs/en/docs/tutorial/dependencies/index.md
+++ b/docs/en/docs/tutorial/dependencies/index.md
@@ -33,7 +33,7 @@ It is just a function that can take all the same parameters that a *path operati
=== "Python 3.6 and above"
- ```Python hl_lines="8-9"
+ ```Python hl_lines="8-11"
{!> ../../../docs_src/dependencies/tutorial001.py!}
```
@@ -81,7 +81,7 @@ The same way you use `Body`, `Query`, etc. with your *path operation function* p
=== "Python 3.6 and above"
- ```Python hl_lines="13 18"
+ ```Python hl_lines="15 20"
{!> ../../../docs_src/dependencies/tutorial001.py!}
```
diff --git a/docs/en/docs/tutorial/dependencies/sub-dependencies.md b/docs/en/docs/tutorial/dependencies/sub-dependencies.md
index 51531228da54d..a5b40c9ad743b 100644
--- a/docs/en/docs/tutorial/dependencies/sub-dependencies.md
+++ b/docs/en/docs/tutorial/dependencies/sub-dependencies.md
@@ -55,7 +55,7 @@ Then we can use the dependency with:
=== "Python 3.6 and above"
- ```Python hl_lines="21"
+ ```Python hl_lines="22"
{!> ../../../docs_src/dependencies/tutorial005.py!}
```
diff --git a/docs/en/docs/tutorial/extra-data-types.md b/docs/en/docs/tutorial/extra-data-types.md
index a00bd32122509..fb3efd318438c 100644
--- a/docs/en/docs/tutorial/extra-data-types.md
+++ b/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", see the docs for more info.
+ * Pydantic also allows representing it as a "ISO 8601 time diff encoding", see the docs for more info.
* `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`.
diff --git a/docs/en/docs/tutorial/handling-errors.md b/docs/en/docs/tutorial/handling-errors.md
index 82e1662663852..8c30326cede92 100644
--- a/docs/en/docs/tutorial/handling-errors.md
+++ b/docs/en/docs/tutorial/handling-errors.md
@@ -163,7 +163,7 @@ path -> item_id
!!! warning
These are technical details that you might skip if it's not important for you now.
-`RequestValidationError` is a sub-class of Pydantic's `ValidationError`.
+`RequestValidationError` is a sub-class of Pydantic's `ValidationError`.
**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.
diff --git a/docs/en/docs/tutorial/path-params-numeric-validations.md b/docs/en/docs/tutorial/path-params-numeric-validations.md
index 31bf91a0ea6e6..4b2e3f973813d 100644
--- a/docs/en/docs/tutorial/path-params-numeric-validations.md
+++ b/docs/en/docs/tutorial/path-params-numeric-validations.md
@@ -59,7 +59,7 @@ It doesn't matter for **FastAPI**. It will detect the parameters by their names,
So, you can declare your function as:
-```Python hl_lines="8"
+```Python hl_lines="7"
{!../../../docs_src/path_params_numeric_validations/tutorial002.py!}
```
@@ -71,7 +71,7 @@ Pass `*`, as the first parameter of the function.
Python won't do anything with that `*`, but it will know that all the following parameters should be called as keyword arguments (key-value pairs), also known as kwargs. Even if they don't have a default value.
-```Python hl_lines="8"
+```Python hl_lines="7"
{!../../../docs_src/path_params_numeric_validations/tutorial003.py!}
```
@@ -122,9 +122,9 @@ And you can also declare numeric validations:
* `le`: `l`ess than or `e`qual
!!! info
- `Query`, `Path`, and others you will see later are subclasses of a common `Param` class (that you don't need to use).
+ `Query`, `Path`, and other classes you will see later are subclasses of a common `Param` class.
- And all of them share the same all these same parameters of additional validation and metadata you have seen.
+ All of them share the same parameters for additional validation and metadata you have seen.
!!! note "Technical Details"
When you import `Query`, `Path` and others from `fastapi`, they are actually functions.
diff --git a/docs/en/docs/tutorial/path-params.md b/docs/en/docs/tutorial/path-params.md
index 9c458844d37cb..a0d70692e556b 100644
--- a/docs/en/docs/tutorial/path-params.md
+++ b/docs/en/docs/tutorial/path-params.md
@@ -115,6 +115,14 @@ Because *path operations* are evaluated in order, you need to make sure that the
Otherwise, the path for `/users/{user_id}` would match also for `/users/me`, "thinking" that it's receiving a parameter `user_id` with a value of `"me"`.
+Similarly, you cannot redefine a path operation:
+
+```Python hl_lines="6 11"
+{!../../../docs_src/path_params/tutorial003b.py!}
+```
+
+The first one will always be used since the path matches first.
+
## Predefined values
If you have a *path operation* that receives a *path parameter*, but you want the possible valid *path parameter* values to be predefined, you can use a standard Python `Enum`.
diff --git a/docs/en/docs/tutorial/query-params-str-validations.md b/docs/en/docs/tutorial/query-params-str-validations.md
index ee62b97181028..c5fc35b88aeff 100644
--- a/docs/en/docs/tutorial/query-params-str-validations.md
+++ b/docs/en/docs/tutorial/query-params-str-validations.md
@@ -16,12 +16,12 @@ Let's take this application as example:
{!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!}
```
-The query parameter `q` is of type `Optional[str]` (or `str | None` in Python 3.10), that means that it's of type `str` but could also be `None`, and indeed, the default value is `None`, so FastAPI will know it's not required.
+The query parameter `q` is of type `Union[str, None]` (or `str | None` in Python 3.10), that means that it's of type `str` but could also be `None`, and indeed, the default value is `None`, so FastAPI will know it's not required.
!!! note
FastAPI will know that the value of `q` is not required because of the default value `= None`.
- The `Optional` in `Optional[str]` is not used by FastAPI, but will allow your editor to give you better support and detect errors.
+ The `Union` in `Union[str, None]` will allow your editor to give you better support and detect errors.
## Additional validation
@@ -59,24 +59,24 @@ And now use it as the default value of your parameter, setting the parameter `ma
{!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!}
```
-As we have to replace the default value `None` with `Query(None)`, the first parameter to `Query` serves the same purpose of defining that default value.
+As we have to replace the default value `None` in the function with `Query()`, we can now set the default value with the parameter `Query(default=None)`, it serves the same purpose of defining that default value.
So:
```Python
-q: Optional[str] = Query(None)
+q: Union[str, None] = Query(default=None)
```
...makes the parameter optional, the same as:
```Python
-q: Optional[str] = None
+q: Union[str, None] = None
```
And in Python 3.10 and above:
```Python
-q: str | None = Query(None)
+q: str | None = Query(default=None)
```
...makes the parameter optional, the same as:
@@ -97,17 +97,17 @@ But it declares it explicitly as being a query parameter.
or the:
```Python
- = Query(None)
+ = Query(default=None)
```
as it will use that `None` as the default value, and that way make the parameter **not required**.
- The `Optional` part allows your editor to provide better support, but it is not what tells FastAPI that this parameter is not required.
+ The `Union[str, None]` part allows your editor to provide better support, but it is not what tells FastAPI that this parameter is not required.
Then, we can pass more parameters to `Query`. In this case, the `max_length` parameter that applies to strings:
```Python
-q: str = Query(None, max_length=50)
+q: Union[str, None] = Query(default=None, max_length=50)
```
This will validate the data, show a clear error when the data is not valid, and document the parameter in the OpenAPI schema *path operation*.
@@ -118,7 +118,7 @@ You can also add a parameter `min_length`:
=== "Python 3.6 and above"
- ```Python hl_lines="9"
+ ```Python hl_lines="10"
{!> ../../../docs_src/query_params_str_validations/tutorial003.py!}
```
@@ -134,13 +134,13 @@ You can define a ../../../docs_src/query_params_str_validations/tutorial004.py!}
```
=== "Python 3.10 and above"
- ```Python hl_lines="8"
+ ```Python hl_lines="9"
{!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!}
```
@@ -156,7 +156,7 @@ But whenever you need them and go and learn them, know that you can already use
## Default values
-The same way that you can pass `None` as the first argument to be used as the default value, you can pass other values.
+The same way that you can pass `None` as the value for the `default` parameter, you can pass other values.
Let's say that you want to declare the `q` query parameter to have a `min_length` of `3`, and to have a default value of `"fixedquery"`:
@@ -178,26 +178,68 @@ q: str
instead of:
```Python
-q: Optional[str] = None
+q: Union[str, None] = None
```
But we are now declaring it with `Query`, for example like:
```Python
-q: Optional[str] = Query(None, min_length=3)
+q: Union[str, None] = Query(default=None, min_length=3)
```
-So, when you need to declare a value as required while using `Query`, you can use `...` as the first argument:
+So, when you need to declare a value as required while using `Query`, you can simply not declare a default value:
```Python hl_lines="7"
{!../../../docs_src/query_params_str_validations/tutorial006.py!}
```
+### Required with Ellipsis (`...`)
+
+There's an alternative way to explicitly declare that a value is required. You can set the `default` parameter to the literal value `...`:
+
+```Python hl_lines="7"
+{!../../../docs_src/query_params_str_validations/tutorial006b.py!}
+```
+
!!! info
If you hadn't seen that `...` before: it is a special single value, it is part of Python and is called "Ellipsis".
+ It is used by Pydantic and FastAPI to explicitly declare that a value is required.
+
This will let **FastAPI** know that this parameter is required.
+### Required with `None`
+
+You can declare that a parameter can accept `None`, but that it's still required. This would force clients to send a value, even if the value is `None`.
+
+To do that, you can declare that `None` is a valid type but still use `default=...`:
+
+=== "Python 3.6 and above"
+
+ ```Python hl_lines="8"
+ {!> ../../../docs_src/query_params_str_validations/tutorial006c.py!}
+ ```
+
+=== "Python 3.10 and above"
+
+ ```Python hl_lines="7"
+ {!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!}
+ ```
+
+!!! 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 Required Optional fields.
+
+### Use Pydantic's `Required` instead of Ellipsis (`...`)
+
+If you feel uncomfortable using `...`, you can also import and use `Required` from Pydantic:
+
+```Python hl_lines="2 8"
+{!../../../docs_src/query_params_str_validations/tutorial006d.py!}
+```
+
+!!! tip
+ Remember that in most of the cases, when something is required, you can simply omit the `default` parameter, so you normally don't have to use `...` nor `Required`.
+
## Query parameter list / multiple values
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.
@@ -315,7 +357,7 @@ You can add a `title`:
=== "Python 3.10 and above"
- ```Python hl_lines="7"
+ ```Python hl_lines="8"
{!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!}
```
@@ -399,7 +441,7 @@ To exclude a query parameter from the generated OpenAPI schema (and thus, from t
=== "Python 3.10 and above"
- ```Python hl_lines="7"
+ ```Python hl_lines="8"
{!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!}
```
diff --git a/docs/en/docs/tutorial/request-files.md b/docs/en/docs/tutorial/request-files.md
index 3ca471a91b866..664a1102f161f 100644
--- a/docs/en/docs/tutorial/request-files.md
+++ b/docs/en/docs/tutorial/request-files.md
@@ -106,7 +106,7 @@ The way HTML forms (``) sends the data to the server normally uses
Data from forms is normally encoded using the "media type" `application/x-www-form-urlencoded` when it doesn't include files.
But when the form includes files, it is encoded as `multipart/form-data`. If you use `File`, **FastAPI** will know it has to get the files from the correct part of the body.
-
+
If you want to read more about these encodings and form fields, head to the MDN web docs for POST.
!!! warning
diff --git a/docs/en/docs/tutorial/request-forms.md b/docs/en/docs/tutorial/request-forms.md
index b5495a4005610..2021a098f928a 100644
--- a/docs/en/docs/tutorial/request-forms.md
+++ b/docs/en/docs/tutorial/request-forms.md
@@ -45,7 +45,7 @@ The way HTML forms (``) sends the data to the server normally uses
Data from forms is normally encoded using the "media type" `application/x-www-form-urlencoded`.
But when the form includes files, it is encoded as `multipart/form-data`. You'll read about handling files in the next chapter.
-
+
If you want to read more about these encodings and form fields, head to the MDN web docs for POST.
!!! warning
diff --git a/docs/en/docs/tutorial/response-model.md b/docs/en/docs/tutorial/response-model.md
index c751a9256be90..2bbd4d4fd5090 100644
--- a/docs/en/docs/tutorial/response-model.md
+++ b/docs/en/docs/tutorial/response-model.md
@@ -61,6 +61,12 @@ Here we are declaring a `UserIn` model, it will contain a plaintext password:
{!> ../../../docs_src/response_model/tutorial002_py310.py!}
```
+!!! info
+ To use `EmailStr`, first install `email_validator`.
+
+ E.g. `pip install email-validator`
+ or `pip install pydantic[email]`.
+
And we are using this model to declare our input and the same model to declare our output:
=== "Python 3.6 and above"
@@ -162,7 +168,7 @@ Your response model could have default values, like:
{!> ../../../docs_src/response_model/tutorial004_py310.py!}
```
-* `description: Optional[str] = None` has a default of `None`.
+* `description: Union[str, None] = None` has a default of `None`.
* `tax: float = 10.5` has a default of `10.5`.
* `tags: List[str] = []` as a default of an empty list: `[]`.
diff --git a/docs/en/docs/tutorial/schema-extra-example.md b/docs/en/docs/tutorial/schema-extra-example.md
index c69df51dc9e0e..94347018d08dd 100644
--- a/docs/en/docs/tutorial/schema-extra-example.md
+++ b/docs/en/docs/tutorial/schema-extra-example.md
@@ -68,13 +68,13 @@ Here we pass an `example` of the data expected in `Body()`:
=== "Python 3.6 and above"
- ```Python hl_lines="21-26"
+ ```Python hl_lines="20-25"
{!> ../../../docs_src/schema_extra_example/tutorial003.py!}
```
=== "Python 3.10 and above"
- ```Python hl_lines="19-24"
+ ```Python hl_lines="18-23"
{!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!}
```
@@ -99,13 +99,13 @@ Each specific example `dict` in the `examples` can contain:
=== "Python 3.6 and above"
- ```Python hl_lines="22-48"
+ ```Python hl_lines="21-47"
{!> ../../../docs_src/schema_extra_example/tutorial004.py!}
```
=== "Python 3.10 and above"
- ```Python hl_lines="20-46"
+ ```Python hl_lines="19-45"
{!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!}
```
diff --git a/docs/en/docs/tutorial/sql-databases.md b/docs/en/docs/tutorial/sql-databases.md
index 60c7fb0665f5f..5ccaf05ecec96 100644
--- a/docs/en/docs/tutorial/sql-databases.md
+++ b/docs/en/docs/tutorial/sql-databases.md
@@ -80,6 +80,20 @@ The file `__init__.py` is just an empty file, but it tells Python that `sql_app`
Now let's see what each file/module does.
+## Install `SQLAlchemy`
+
+First you need to install `SQLAlchemy`:
+
+
+
## Create the SQLAlchemy parts
Let's refer to the file `sql_app/database.py`.
@@ -317,7 +331,7 @@ Not only the IDs of those items, but all the data that we defined in the Pydanti
Now, in the Pydantic *models* for reading, `Item` and `User`, add an internal `Config` class.
-This `Config` class is used to provide configurations to Pydantic.
+This `Config` class is used to provide configurations to Pydantic.
In the `Config` class, set the attribute `orm_mode = True`.
@@ -616,7 +630,7 @@ And as the code related to SQLAlchemy and the SQLAlchemy models lives in separat
The same way, you would be able to use the same SQLAlchemy models and utilities in other parts of your code that are not related to **FastAPI**.
-For example, in a background task worker with Celery, RQ, or ARQ.
+For example, in a background task worker with Celery, RQ, or ARQ.
## Review all the files
diff --git a/docs/en/docs/tutorial/testing.md b/docs/en/docs/tutorial/testing.md
index fea5a54f5c2de..d2ccd7dc77d45 100644
--- a/docs/en/docs/tutorial/testing.md
+++ b/docs/en/docs/tutorial/testing.md
@@ -8,6 +8,11 @@ With it, you can use `requests`.
+
+ E.g. `pip install requests`.
+
Import `TestClient`.
Create a `TestClient` by passing your **FastAPI** application to it.
@@ -45,7 +50,17 @@ And your **FastAPI** application might also be composed of several files/modules
### **FastAPI** app file
-Let's say you have a file `main.py` with your **FastAPI** app:
+Let's say you have a file structure as described in [Bigger Applications](./bigger-applications.md){.internal-link target=_blank}:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ └── main.py
+```
+
+In the file `main.py` you have your **FastAPI** app:
+
```Python
{!../../../docs_src/app_testing/main.py!}
@@ -53,18 +68,40 @@ Let's say you have a file `main.py` with your **FastAPI** app:
### Testing file
-Then you could have a file `test_main.py` with your tests, and import your `app` from the `main` module (`main.py`):
+Then you could have a file `test_main.py` with your tests. It could live on the same Python package (the same directory with a `__init__.py` file):
-```Python
+``` hl_lines="5"
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+│ └── test_main.py
+```
+
+Because this file is in the same package, you can use relative imports to import the object `app` from the `main` module (`main.py`):
+
+```Python hl_lines="3"
{!../../../docs_src/app_testing/test_main.py!}
```
+...and have the code for the tests just like before.
+
## Testing: extended example
Now let's extend this example and add more details to see how to test different parts.
### Extended **FastAPI** app file
+Let's continue with the same file structure as before:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+│ └── test_main.py
+```
+
Let's say that now the file `main.py` with your **FastAPI** app has some other **path operations**.
It has a `GET` operation that could return an error.
diff --git a/docs/en/mkdocs.yml b/docs/en/mkdocs.yml
index e7aa40def56ba..69ad29624f5a4 100644
--- a/docs/en/mkdocs.yml
+++ b/docs/en/mkdocs.yml
@@ -5,13 +5,15 @@ theme:
name: material
custom_dir: overrides
palette:
- - scheme: default
+ - media: '(prefers-color-scheme: light)'
+ scheme: default
primary: teal
accent: amber
toggle:
icon: material/lightbulb
name: Switch to light mode
- - scheme: slate
+ - media: '(prefers-color-scheme: dark)'
+ scheme: slate
primary: teal
accent: amber
toggle:
@@ -42,6 +44,7 @@ nav:
- es: /es/
- fa: /fa/
- fr: /fr/
+ - he: /he/
- id: /id/
- it: /it/
- ja: /ja/
@@ -51,6 +54,7 @@ nav:
- pt: /pt/
- ru: /ru/
- sq: /sq/
+ - sv: /sv/
- tr: /tr/
- uk: /uk/
- zh: /zh/
@@ -178,6 +182,8 @@ markdown_extensions:
format: !!python/name:pymdownx.superfences.fence_code_format ''
- pymdownx.tabbed:
alternate_style: true
+- attr_list
+- md_in_html
extra:
analytics:
provider: google
@@ -210,6 +216,8 @@ extra:
name: fa
- link: /fr/
name: fr - français
+ - link: /he/
+ name: he
- link: /id/
name: id
- link: /it/
@@ -228,6 +236,8 @@ extra:
name: ru - русский язык
- link: /sq/
name: sq - shqip
+ - link: /sv/
+ name: sv - svenska
- link: /tr/
name: tr - Türkçe
- link: /uk/
diff --git a/docs/en/overrides/main.html b/docs/en/overrides/main.html
index cac02ca7c31ac..0d5bb037c8fab 100644
--- a/docs/en/overrides/main.html
+++ b/docs/en/overrides/main.html
@@ -29,9 +29,9 @@
- FastAPI framework, high performance, easy to learn, fast to code, ready for production
+ فریمورک FastAPI، کارایی بالا، یادگیری آسان، کدنویسی سریع، آماده برای استفاده در محیط پروداکشن
-
-
+
+
@@ -25,103 +21,99 @@
---
-**Documentation**: https://fastapi.tiangolo.com
+**مستندات**: https://fastapi.tiangolo.com
-**Source Code**: https://github.com/tiangolo/fastapi
+**کد منبع**: https://github.com/tiangolo/fastapi
---
+FastAPI یک وب فریمورک مدرن و سریع (با کارایی بالا) برای ایجاد APIهای متنوع (وب، وبسوکت و غبره) با زبان پایتون نسخه +۳.۶ است. این فریمورک با رعایت کامل راهنمای نوع داده (Type Hint) ایجاد شده است.
-FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints.
+ویژگیهای کلیدی این فریمورک عبارتند از:
-The key features are:
+* **سرعت**: کارایی بسیار بالا و قابل مقایسه با **NodeJS** و **Go** (با تشکر از Starlette و Pydantic). [یکی از سریعترین فریمورکهای پایتونی موجود](#performance).
-* **Fast**: Very high performance, on par with **NodeJS** and **Go** (thanks to Starlette and Pydantic). [One of the fastest Python frameworks available](#performance).
+* **کدنویسی سریع**: افزایش ۲۰۰ تا ۳۰۰ درصدی سرعت توسعه فابلیتهای جدید. *
+* **باگ کمتر**: کاهش ۴۰ درصدی خطاهای انسانی (برنامهنویسی). *
+* **غریزی**: پشتیبانی فوقالعاده در محیطهای توسعه یکپارچه (IDE). تکمیل در همه بخشهای کد. کاهش زمان رفع باگ.
+* **آسان**: طراحی شده برای یادگیری و استفاده آسان. کاهش زمان مورد نیاز برای مراجعه به مستندات.
+* **کوچک**: کاهش تکرار در کد. چندین قابلیت برای هر پارامتر (منظور پارامترهای ورودی تابع هندلر میباشد، به بخش خلاصه در همین صفحه مراجعه شود). باگ کمتر.
+* **استوار**: ایجاد کدی آماده برای استفاده در محیط پروداکشن و تولید خودکار مستندات تعاملی
+* **مبتنی بر استانداردها**: مبتنی بر (و منطبق با) استانداردهای متن باز مربوط به API: OpenAPI (سوگر سابق) و JSON Schema.
-* **Fast to code**: Increase the speed to develop features by about 200% to 300%. *
-* **Fewer bugs**: Reduce about 40% of human (developer) induced errors. *
-* **Intuitive**: Great editor support. Completion everywhere. Less time debugging.
-* **Easy**: Designed to be easy to use and learn. Less time reading docs.
-* **Short**: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.
-* **Robust**: Get production-ready code. With automatic interactive documentation.
-* **Standards-based**: Based on (and fully compatible with) the open standards for APIs: OpenAPI (previously known as Swagger) and JSON Schema.
+* تخمینها بر اساس تستهای انجام شده در یک تیم توسعه داخلی که مشغول ایجاد برنامههای کاربردی واقعی بودند صورت گرفته است.
-* estimation based on tests on an internal development team, building production applications.
-
-## Sponsors
+## اسپانسرهای طلایی
{% if sponsors %}
{% for sponsor in sponsors.gold -%}
-
-{% endfor -%}
-{%- for sponsor in sponsors.silver -%}
-
+
{% endfor %}
{% endif %}
-Other sponsors
+دیگر اسپانسرها
-## Opinions
+## نظر دیگران در مورد FastAPI
-"_[...] I'm using **FastAPI** a ton these days. [...] I'm actually planning to use it for all of my team's **ML services at Microsoft**. Some of them are getting integrated into the core **Windows** product and some **Office** products._"
+
[...] I'm using FastAPI a ton these days. [...] I'm actually planning to use it for all of my team's ML services at Microsoft. Some of them are getting integrated into the core Windows product and some Office products."
---
-"_We adopted the **FastAPI** library to spawn a **REST** server that can be queried to obtain **predictions**. [for Ludwig]_"
+
"We adopted the FastAPI library to spawn a RESTserver that can be queried to obtain predictions. [for Ludwig]"
Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala - Uber(ref)
---
-"_**Netflix** is pleased to announce the open-source release of our **crisis management** orchestration framework: **Dispatch**! [built with **FastAPI**]_"
+
"Netflix is pleased to announce the open-source release of our crisis management orchestration framework: Dispatch! [built with FastAPI]"
Kevin Glisson, Marc Vilanova, Forest Monsen - Netflix(ref)
---
-"_I’m over the moon excited about **FastAPI**. It’s so fun!_"
+
"I’m over the moon excited about FastAPI. It’s so fun!"
---
-"_Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted **Hug** to be - it's really inspiring to see someone build that._"
+
"Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted Hug to be - it's really inspiring to see someone build that."
---
-"_If you're looking to learn one **modern framework** for building REST APIs, check out **FastAPI** [...] It's fast, easy to use and easy to learn [...]_"
+
"If you're looking to learn one modern framework for building REST APIs, check out FastAPI [...] It's fast, easy to use and easy to learn [...]"
-"_We've switched over to **FastAPI** for our **APIs** [...] I think you'll like it [...]_"
+
"We've switched over to FastAPI for our APIs [...] I think you'll like it [...]"
---
-## **Typer**, the FastAPI of CLIs
+## **Typer**, فریمورکی معادل FastAPI برای کار با واسط خط فرمان
-If you are building a CLI app to be used in the terminal instead of a web API, check out **Typer**.
+اگر در حال ساختن برنامهای برای استفاده در CLI (به جای استفاده در وب) هستید، میتوانید از **Typer**. استفاده کنید.
-**Typer** is FastAPI's little sibling. And it's intended to be the **FastAPI of CLIs**. ⌨️ 🚀
+**Typer** دوقلوی کوچکتر FastAPI است و قرار است معادلی برای FastAPI در برنامههای CLI باشد.️ 🚀
-## Requirements
+## نیازمندیها
-Python 3.6+
+پایتون +۳.۶
-FastAPI stands on the shoulders of giants:
+FastAPI مبتنی بر ابزارهای قدرتمند زیر است:
-* Starlette for the web parts.
-* Pydantic for the data parts.
+* فریمورک Starlette برای بخش وب.
+* کتابخانه Pydantic برای بخش داده.
-## Installation
+## نصب
@@ -133,7 +125,7 @@ $ pip install fastapi
-You will also need an ASGI server, for production such as Uvicorn or Hypercorn.
+نصب یک سرور پروداکشن نظیر Uvicorn یا Hypercorn نیز جزء نیازمندیهاست.
-## Example
-
-### Create it
+## مثال
-* Create a file `main.py` with:
+### ایجاد کنید
+* فایلی به نام `main.py` با محتوای زیر ایجاد کنید :
```Python
from typing import Optional
@@ -165,14 +156,14 @@ def read_root():
@app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
```
-Or use async def...
+همچنین میتوانید از async def... نیز استفاده کنید
-If your code uses `async` / `await`, use `async def`:
+اگر در کدتان از `async` / `await` استفاده میکنید, از `async def` برای تعریف تابع خود استفاده کنید:
```Python hl_lines="9 14"
from typing import Optional
@@ -192,15 +183,16 @@ async def read_item(item_id: int, q: Optional[str] = None):
return {"item_id": item_id, "q": q}
```
-**Note**:
+**توجه**:
+
+اگر با `async / await` آشنا نیستید، به بخش _"عجله دارید?"_ در صفحه درباره `async` و `await` در مستندات مراجعه کنید.
-If you don't know, check the _"In a hurry?"_ section about `async` and `await` in the docs.
-### Run it
+### اجرا کنید
-Run the server with:
+با استفاده از دستور زیر سرور را اجرا کنید:
-About the command uvicorn main:app --reload...
+درباره دستور uvicorn main:app --reload...
-The command `uvicorn main:app` refers to:
+دستور `uvicorn main:app` شامل موارد زیر است:
-* `main`: the file `main.py` (the Python "module").
-* `app`: the object created inside of `main.py` with the line `app = FastAPI()`.
-* `--reload`: make the server restart after code changes. Only do this for development.
+* `main`: فایل `main.py` (ماژول پایتون ایجاد شده).
+* `app`: شیء ایجاد شده در فایل `main.py` در خط `app = FastAPI()`.
+* `--reload`: ریستارت کردن سرور با تغییر کد. تنها در هنگام توسعه از این گزینه استفاده شود..
-### Check it
+### بررسی کنید
-Open your browser at http://127.0.0.1:8000/items/5?q=somequery.
+آدرس http://127.0.0.1:8000/items/5?q=somequery را در مرورگر خود باز کنید.
-You will see the JSON response as:
+پاسخ JSON زیر را مشاهده خواهید کرد:
```JSON
{"item_id": 5, "q": "somequery"}
```
-You already created an API that:
+تا اینجا شما APIای ساختید که:
-* Receives HTTP requests in the _paths_ `/` and `/items/{item_id}`.
-* Both _paths_ take `GET` operations (also known as HTTP _methods_).
-* The _path_ `/items/{item_id}` has a _path parameter_ `item_id` that should be an `int`.
-* The _path_ `/items/{item_id}` has an optional `str` _query parameter_ `q`.
+* درخواستهای HTTP به _مسیرهای_ `/` و `/items/{item_id}` را دریافت میکند.
+* هردو _مسیر_ عملیات (یا HTTP _متد_) `GET` را پشتیبانی میکنند.
+* _مسیر_ `/items/{item_id}` شامل _پارامتر مسیر_ `item_id` از نوع `int` است.
+* _مسیر_ `/items/{item_id}` شامل _پارامتر پرسمان_ اختیاری `q` از نوع `str` است.
-### Interactive API docs
+### مستندات API تعاملی
-Now go to http://127.0.0.1:8000/docs.
+حال به آدرس http://127.0.0.1:8000/docs بروید.
-You will see the automatic interactive API documentation (provided by Swagger UI):
+مستندات API تعاملی (ایجاد شده به کمک Swagger UI) را مشاهده خواهید کرد:
![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png)
-### Alternative API docs
+### مستندات API جایگزین
-And now, go to http://127.0.0.1:8000/redoc.
+حال به آدرس http://127.0.0.1:8000/redoc بروید.
-You will see the alternative automatic documentation (provided by ReDoc):
+مستندات خودکار دیگری را مشاهده خواهید کرد که به کمک ReDoc ایجاد میشود:
![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png)
-## Example upgrade
+## تغییر مثال
-Now modify the file `main.py` to receive a body from a `PUT` request.
+حال فایل `main.py` را مطابق زیر ویرایش کنید تا بتوانید بدنه یک درخواست `PUT` را دریافت کنید.
-Declare the body using standard Python types, thanks to Pydantic.
+به کمک Pydantic بدنه درخواست را با انواع استاندارد پایتون تعریف کنید.
```Python hl_lines="4 9-12 25-27"
from typing import Optional
@@ -278,7 +270,7 @@ app = FastAPI()
class Item(BaseModel):
name: str
price: float
- is_offer: Optional[bool] = None
+ is_offer: Union[bool, None] = None
@app.get("/")
@@ -287,7 +279,7 @@ def read_root():
@app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
@@ -296,173 +288,175 @@ def update_item(item_id: int, item: Item):
return {"item_name": item.name, "item_id": item_id}
```
-The server should reload automatically (because you added `--reload` to the `uvicorn` command above).
+سرور به صورت خودکار ریاستارت میشود (زیرا پیشتر از گزینه `--reload` در دستور `uvicorn` استفاده کردیم).
-### Interactive API docs upgrade
+### تغییر مستندات API تعاملی
-Now go to http://127.0.0.1:8000/docs.
+مجددا به آدرس http://127.0.0.1:8000/docs بروید.
-* The interactive API documentation will be automatically updated, including the new body:
+* مستندات API تعاملی به صورت خودکار بهروز شده است و شامل بدنه تعریف شده در مرحله قبل است:
![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png)
-* Click on the button "Try it out", it allows you to fill the parameters and directly interact with the API:
+* روی دکمه "Try it out" کلیک کنید, اکنون میتوانید پارامترهای مورد نیاز هر API را مشخص کرده و به صورت مستقیم با آنها تعامل کنید:
![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png)
-* Then click on the "Execute" button, the user interface will communicate with your API, send the parameters, get the results and show them on the screen:
+* سپس روی دکمه "Execute" کلیک کنید, خواهید دید که واسط کاریری با APIهای تعریف شده ارتباط برقرار کرده، پارامترهای مورد نیاز را به آنها ارسال میکند، سپس نتایج را دریافت کرده و در صفحه نشان میدهد:
![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png)
-### Alternative API docs upgrade
+### تغییر مستندات API جایگزین
-And now, go to http://127.0.0.1:8000/redoc.
+حال به آدرس http://127.0.0.1:8000/redoc بروید.
-* The alternative documentation will also reflect the new query parameter and body:
+* خواهید دید که مستندات جایگزین نیز بهروزرسانی شده و شامل پارامتر پرسمان و بدنه تعریف شده میباشد:
![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png)
-### Recap
+### خلاصه
-In summary, you declare **once** the types of parameters, body, etc. as function parameters.
+به طور خلاصه شما **یک بار** انواع پارامترها، بدنه و غیره را به عنوان پارامترهای ورودی تابع خود تعریف میکنید.
-You do that with standard modern Python types.
+ این کار را با استفاده از انواع استاندارد و مدرن موجود در پایتون انجام میدهید.
-You don't have to learn a new syntax, the methods or classes of a specific library, etc.
+نیازی به یادگیری نحو جدید یا متدها و کلاسهای یک کتابخانه بخصوص و غیره نیست.
-Just standard **Python 3.6+**.
+تنها **پایتون +۳.۶**.
-For example, for an `int`:
+به عنوان مثال برای یک پارامتر از نوع `int`:
```Python
item_id: int
```
-or for a more complex `Item` model:
+یا برای یک مدل پیچیدهتر مثل `Item`:
```Python
item: Item
```
-...and with that single declaration you get:
+...و با همین اعلان تمامی قابلیتهای زیر در دسترس قرار میگیرد:
-* Editor support, including:
- * Completion.
- * Type checks.
-* Validation of data:
- * Automatic and clear errors when the data is invalid.
- * Validation even for deeply nested JSON objects.
-* Conversion of input data: coming from the network to Python data and types. Reading from:
+* پشتیبانی ویرایشگر متنی شامل:
+ * تکمیل کد.
+ * بررسی انواع داده.
+* اعتبارسنجی داده:
+ * خطاهای خودکار و مشخص در هنگام نامعتبر بودن داده
+ * اعتبارسنجی، حتی برای اشیاء JSON تو در تو.
+* تبدیل داده ورودی: که از شبکه رسیده به انواع و داده پایتونی. این داده شامل:
* JSON.
- * Path parameters.
- * Query parameters.
- * Cookies.
- * Headers.
- * Forms.
- * Files.
-* Conversion of output data: converting from Python data and types to network data (as JSON):
- * Convert Python types (`str`, `int`, `float`, `bool`, `list`, etc).
- * `datetime` objects.
- * `UUID` objects.
- * Database models.
- * ...and many more.
-* Automatic interactive API documentation, including 2 alternative user interfaces:
+ * پارامترهای مسیر.
+ * پارامترهای پرسمان.
+ * کوکیها.
+ * سرآیندها (هدرها).
+ * فرمها.
+ * فایلها.
+* تبدیل داده خروجی: تبدیل از انواع و داده پایتون به داده شبکه (مانند JSON):
+ * تبدیل انواع داده پایتونی (`str`, `int`, `float`, `bool`, `list` و غیره).
+ * اشیاء `datetime`.
+ * اشیاء `UUID`.
+ * qمدلهای پایگاهداده.
+ * و موارد بیشمار دیگر.
+* دو مدل مستند API تعاملی خودکار :
* Swagger UI.
* ReDoc.
---
-Coming back to the previous code example, **FastAPI** will:
-
-* Validate that there is an `item_id` in the path for `GET` and `PUT` requests.
-* Validate that the `item_id` is of type `int` for `GET` and `PUT` requests.
- * If it is not, the client will see a useful, clear error.
-* 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:
- * Check that it has a required attribute `name` that should be a `str`.
- * Check that it has a required attribute `price` that has to be a `float`.
- * Check that it has an optional attribute `is_offer`, that should be a `bool`, if present.
- * All this would also work for deeply nested JSON objects.
-* Convert from and to JSON automatically.
-* Document everything with OpenAPI, that can be used by:
- * Interactive documentation systems.
- * Automatic client code generation systems, for many languages.
-* Provide 2 interactive documentation web interfaces directly.
+به مثال قبلی باز میگردیم، در این مثال **FastAPI** موارد زیر را انجام میدهد:
+
+* اعتبارسنجی اینکه پارامتر `item_id` در مسیر درخواستهای `GET` و `PUT` موجود است .
+* اعتبارسنجی اینکه پارامتر `item_id` در درخواستهای `GET` و `PUT` از نوع `int` است.
+ * اگر غیر از این موارد باشد، سرویسگیرنده خطای مفید و مشخصی دریافت خواهد کرد.
+* بررسی وجود پارامتر پرسمان اختیاری `q` (مانند `http://127.0.0.1:8000/items/foo?q=somequery`) در درخواستهای `GET`.
+ * از آنجا که پارامتر `q` با `= None` مقداردهی شده است, این پارامتر اختیاری است.
+ * اگر از مقدار اولیه `None` استفاده نکنیم، این پارامتر الزامی خواهد بود (همانند بدنه درخواست در درخواست `PUT`).
+* برای درخواستهای `PUT` به آدرس `/items/{item_id}`, بدنه درخواست باید از نوع JSON تعریف شده باشد:
+ * بررسی اینکه بدنه شامل فیلدی با نام `name` و از نوع `str` است.
+ * بررسی اینکه بدنه شامل فیلدی با نام `price` و از نوع `float` است.
+ * بررسی اینکه بدنه شامل فیلدی اختیاری با نام `is_offer` است, که در صورت وجود باید از نوع `bool` باشد.
+ * تمامی این موارد برای اشیاء JSON در هر عمقی قابل بررسی میباشد.
+* تبدیل از/به JSON به صورت خودکار.
+* مستندسازی همه چیز با استفاده از OpenAPI, که میتوان از آن برای موارد زیر استفاده کرد:
+ * سیستم مستندات تعاملی.
+ * تولید خودکار کد سرویسگیرنده در زبانهای برنامهنویسی بیشمار.
+* فراهم سازی ۲ مستند تعاملی مبتنی بر وب به صورت پیشفرض .
---
-We just scratched the surface, but you already get the idea of how it all works.
+موارد ذکر شده تنها پارهای از ویژگیهای بیشمار FastAPI است اما ایدهای کلی از طرز کار آن در اختیار قرار میدهد.
-Try changing the line with:
+خط زیر را به این صورت تغییر دهید:
```Python
return {"item_name": item.name, "item_id": item_id}
```
-...from:
+از:
```Python
... "item_name": item.name ...
```
-...to:
+به:
```Python
... "item_price": item.price ...
```
-...and see how your editor will auto-complete the attributes and know their types:
+در حین تایپ کردن توجه کنید که چگونه ویرایشگر، ویژگیهای کلاس `Item` را تشخیص داده و به تکمیل خودکار آنها کمک میکند:
![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png)
-For a more complete example including more features, see the Tutorial - User Guide.
+برای مشاهده مثالهای کاملتر که شامل قابلیتهای بیشتری از FastAPI باشد به بخش آموزش - راهنمای کاربر مراجعه کنید.
-**Spoiler alert**: the tutorial - user guide includes:
+**هشدار اسپویل**: بخش آموزش - راهنمای کاربر شامل موارد زیر است:
-* Declaration of **parameters** from other different places as: **headers**, **cookies**, **form fields** and **files**.
-* How to set **validation constraints** as `maximum_length` or `regex`.
-* A very powerful and easy to use **Dependency Injection** system.
-* Security and authentication, including support for **OAuth2** with **JWT tokens** and **HTTP Basic** auth.
-* More advanced (but equally easy) techniques for declaring **deeply nested JSON models** (thanks to Pydantic).
-* **GraphQL** integration with Strawberry and other libraries.
-* Many extra features (thanks to Starlette) as:
- * **WebSockets**
- * extremely easy tests based on `requests` and `pytest`
+* اعلان **پارامترهای** موجود در بخشهای دیگر درخواست، شامل: **سرآیند (هدر)ها**, **کوکیها**, **فیلدهای فرم** و **فایلها**.
+* چگونگی تنظیم **محدودیتهای اعتبارسنجی** به عنوان مثال `maximum_length` یا `regex`.
+* سیستم **Dependency Injection** قوی و کاربردی.
+* امنیت و تایید هویت, شامل پشتیبانی از **OAuth2** مبتنی بر **JWT tokens** و **HTTP Basic**.
+* تکنیک پیشرفته برای تعریف **مدلهای چند سطحی JSON** (بر اساس Pydantic).
+* قابلیتهای اضافی دیگر (بر اساس Starlette) شامل:
+ * **وبسوکت**
+ * **GraphQL**
+ * تستهای خودکار آسان مبتنی بر `requests` و `pytest`
* **CORS**
* **Cookie Sessions**
- * ...and more.
+ * و موارد بیشمار دیگر.
-## Performance
+## کارایی
-Independent TechEmpower benchmarks show **FastAPI** applications running under Uvicorn as one of the fastest Python frameworks available, only below Starlette and Uvicorn themselves (used internally by FastAPI). (*)
+معیار (بنچمارک)های مستقل TechEmpower حاکی از آن است که برنامههای **FastAPI** که تحت Uvicorn اجرا میشود، یکی از سریعترین فریمورکهای مبتنی بر پایتون, است که کمی ضعیفتر از Starlette و Uvicorn عمل میکند (فریمورک و سروری که FastAPI بر اساس آنها ایجاد شده است) (*)
-To understand more about it, see the section Benchmarks.
+برای درک بهتری از این موضوع به بخش بنچمارکها مراجعه کنید.
-## Optional Dependencies
+## نیازمندیهای اختیاری
-Used by Pydantic:
+استفاده شده توسط Pydantic:
-* ujson - for faster JSON "parsing".
-* email_validator - for email validation.
+* ujson - برای "تجزیه (parse)" سریعتر JSON .
+* email_validator - برای اعتبارسنجی آدرسهای ایمیل.
-Used by Starlette:
+استفاده شده توسط Starlette:
-* requests - Required if you want to use the `TestClient`.
-* jinja2 - Required if you want to use the default template configuration.
-* python-multipart - Required if you want to support form "parsing", with `request.form()`.
-* itsdangerous - Required for `SessionMiddleware` support.
-* pyyaml - Required for Starlette's `SchemaGenerator` support (you probably don't need it with FastAPI).
-* ujson - Required if you want to use `UJSONResponse`.
+* requests - در صورتی که میخواهید از `TestClient` استفاده کنید.
+* aiofiles - در صورتی که میخواهید از `FileResponse` و `StaticFiles` استفاده کنید.
+* jinja2 - در صورتی که بخواهید از پیکربندی پیشفرض برای قالبها استفاده کنید.
+* python-multipart - در صورتی که بخواهید با استفاده از `request.form()` از قابلیت "تجزیه (parse)" فرم استفاده کنید.
+* itsdangerous - در صورتی که بخواید از `SessionMiddleware` پشتیبانی کنید.
+* pyyaml - برای پشتیبانی `SchemaGenerator` در Starlet (به احتمال زیاد برای کار کردن با FastAPI به آن نیازی پیدا نمیکنید.).
+* graphene - در صورتی که از `GraphQLApp` پشتیبانی میکنید.
+* ujson - در صورتی که بخواهید از `UJSONResponse` استفاده کنید.
-Used by FastAPI / Starlette:
+استفاده شده توسط FastAPI / Starlette:
-* uvicorn - for the server that loads and serves your application.
-* orjson - Required if you want to use `ORJSONResponse`.
+* uvicorn - برای سرور اجرا کننده برنامه وب.
+* orjson - در صورتی که بخواهید از `ORJSONResponse` استفاده کنید.
-You can install all of these with `pip install "fastapi[all]"`.
+میتوان همه این موارد را با استفاده از دستور `pip install fastapi[all]`. به صورت یکجا نصب کرد.
-## License
+## لایسنس
-This project is licensed under the terms of the MIT license.
+این پروژه مشمول قوانین و مقررات لایسنس MIT است.
diff --git a/docs/fa/mkdocs.yml b/docs/fa/mkdocs.yml
index 6fb3891b7aed4..7c2fe5eab8719 100644
--- a/docs/fa/mkdocs.yml
+++ b/docs/fa/mkdocs.yml
@@ -5,13 +5,15 @@ theme:
name: material
custom_dir: overrides
palette:
- - scheme: default
+ - media: '(prefers-color-scheme: light)'
+ scheme: default
primary: teal
accent: amber
toggle:
icon: material/lightbulb
name: Switch to light mode
- - scheme: slate
+ - media: '(prefers-color-scheme: dark)'
+ scheme: slate
primary: teal
accent: amber
toggle:
@@ -42,6 +44,7 @@ nav:
- es: /es/
- fa: /fa/
- fr: /fr/
+ - he: /he/
- id: /id/
- it: /it/
- ja: /ja/
@@ -51,6 +54,7 @@ nav:
- pt: /pt/
- ru: /ru/
- sq: /sq/
+ - sv: /sv/
- tr: /tr/
- uk: /uk/
- zh: /zh/
@@ -71,6 +75,8 @@ markdown_extensions:
format: !!python/name:pymdownx.superfences.fence_code_format ''
- pymdownx.tabbed:
alternate_style: true
+- attr_list
+- md_in_html
extra:
analytics:
provider: google
@@ -103,6 +109,8 @@ extra:
name: fa
- link: /fr/
name: fr - français
+ - link: /he/
+ name: he
- link: /id/
name: id
- link: /it/
@@ -121,6 +129,8 @@ extra:
name: ru - русский язык
- link: /sq/
name: sq - shqip
+ - link: /sv/
+ name: sv - svenska
- link: /tr/
name: tr - Türkçe
- link: /uk/
diff --git a/docs/fr/docs/alternatives.md b/docs/fr/docs/alternatives.md
index bf3e7bc3c3cea..ee20438c3db2f 100644
--- a/docs/fr/docs/alternatives.md
+++ b/docs/fr/docs/alternatives.md
@@ -133,7 +133,7 @@ permanents qui les rendent inadaptés.
### Marshmallow
-L'une des principales fonctionnalités nécessaires aux systèmes API est la "sérialisation" des données, qui consiste à prendre les données du code (Python) et à
les convertir en quelque chose qui peut être envoyé sur le réseau. Par exemple, convertir un objet contenant des
données provenant d'une base de données en un objet JSON. Convertir des objets `datetime` en strings, etc.
@@ -147,7 +147,7 @@ Sans un système de validation des données, vous devriez effectuer toutes les v
Ces fonctionnalités sont ce pourquoi Marshmallow a été construit. C'est une excellente bibliothèque, et je l'ai déjà beaucoup utilisée.
-Mais elle a été créée avant que les type hints n'existent en Python. Ainsi, pour définir chaque schéma, vous devez utiliser des utilitaires et des classes spécifiques fournies par Marshmallow.
!!! check "A inspiré **FastAPI** à"
@@ -155,7 +155,7 @@ Utilisez du code pour définir des "schémas" qui fournissent automatiquement le
### Webargs
-Une autre grande fonctionnalité requise par les API est le parsing des données provenant des requêtes entrantes.
Webargs est un outil qui a été créé pour fournir cela par-dessus plusieurs frameworks, dont Flask.
diff --git a/docs/fr/docs/async.md b/docs/fr/docs/async.md
index 20f4ee1011b61..db88c4663ce3f 100644
--- a/docs/fr/docs/async.md
+++ b/docs/fr/docs/async.md
@@ -205,10 +205,6 @@ Cette "attente" 🕙 se mesure en microsecondes, mais tout de même, en cumulé
C'est pourquoi il est logique d'utiliser du code asynchrone ⏸🔀⏯ pour des APIs web.
-La plupart des frameworks Python existants (y compris Flask et Django) ont été créés avant que les nouvelles fonctionnalités asynchrones de Python n'existent. Donc, les façons dont ils peuvent être déployés supportent l'exécution parallèle et une ancienne forme d'exécution asynchrone qui n'est pas aussi puissante que les nouvelles fonctionnalités de Python.
-
-Et cela, bien que les spécifications principales du web asynchrone en Python (ou ASGI) ont été développées chez Django, pour ajouter le support des WebSockets.
-
Ce type d'asynchronicité est ce qui a rendu NodeJS populaire (bien que NodeJS ne soit pas parallèle) et c'est la force du Go en tant que langage de programmation.
Et c'est le même niveau de performance que celui obtenu avec **FastAPI**.
@@ -220,7 +216,7 @@ Et comme on peut avoir du parallélisme et de l'asynchronicité en même temps,
Nope ! C'est ça la morale de l'histoire.
La concurrence est différente du parallélisme. C'est mieux sur des scénarios **spécifiques** qui impliquent beaucoup d'attente. À cause de ça, c'est généralement bien meilleur que le parallélisme pour le développement d'applications web. Mais pas pour tout.
-
+
Donc pour équilibrer tout ça, imaginez l'histoire suivante :
> Vous devez nettoyer une grande et sale maison.
@@ -293,7 +289,7 @@ def get_sequential_burgers(number: int):
Avec `async def`, Python sait que dans cette fonction il doit prendre en compte les expressions `await`, et qu'il peut mettre en pause ⏸ l'exécution de la fonction pour aller faire autre chose 🔀 avant de revenir.
-Pour appeler une fonction définie avec `async def`, vous devez utiliser `await`. Donc ceci ne marche pas :
+Pour appeler une fonction définie avec `async def`, vous devez utiliser `await`. Donc ceci ne marche pas :
```Python
# Ceci ne fonctionne pas, car get_burgers a été défini avec async def
@@ -375,7 +371,7 @@ Au final, dans les deux situations, il est fort probable que **FastAPI** soit to
La même chose s'applique aux dépendances. Si une dépendance est définie avec `def` plutôt que `async def`, elle est exécutée dans la threadpool externe.
-### Sous-dépendances
+### Sous-dépendances
Vous pouvez avoir de multiples dépendances et sous-dépendances dépendant les unes des autres (en tant que paramètres de la définition de la *fonction de chemin*), certaines créées avec `async def` et d'autres avec `def`. Cela fonctionnerait aussi, et celles définies avec un simple `def` seraient exécutées sur un thread externe (venant de la threadpool) plutôt que d'être "attendues".
diff --git a/docs/fr/docs/deployment/docker.md b/docs/fr/docs/deployment/docker.md
index e4b59afbfd53d..d2dcae7223fdf 100644
--- a/docs/fr/docs/deployment/docker.md
+++ b/docs/fr/docs/deployment/docker.md
@@ -118,7 +118,7 @@ $ docker run -d --name mycontainer -p 80:80 myimage
-Vous disposez maintenant d'un serveur FastAPI optimisé dans un conteneur Docker. Configuré automatiquement pour votre
+Vous disposez maintenant d'un serveur FastAPI optimisé dans un conteneur Docker. Configuré automatiquement pour votre
serveur actuel (et le nombre de cœurs du CPU).
## Vérifier
@@ -139,7 +139,7 @@ Vous verrez la documentation interactive automatique de l'API (fournie par http://192.168.99.100/redoc ou http://127.0.0.1/redoc (ou équivalent, en utilisant votre hôte Docker).
@@ -149,7 +149,7 @@ Vous verrez la documentation automatique alternative (fournie par Traefik est un reverse proxy/load balancer
+Traefik est un reverse proxy/load balancer
haute performance. Il peut faire office de "Proxy de terminaison TLS" (entre autres fonctionnalités).
Il est intégré à Let's Encrypt. Ainsi, il peut gérer toutes les parties HTTPS, y compris l'acquisition et le renouvellement des certificats.
@@ -164,7 +164,7 @@ Avec ces informations et ces outils, passez à la section suivante pour tout com
Vous pouvez avoir un cluster en mode Docker Swarm configuré en quelques minutes (environ 20 min) avec un processus Traefik principal gérant HTTPS (y compris l'acquisition et le renouvellement des certificats).
-En utilisant le mode Docker Swarm, vous pouvez commencer par un "cluster" d'une seule machine (il peut même s'agir
+En utilisant le mode Docker Swarm, vous pouvez commencer par un "cluster" d'une seule machine (il peut même s'agir
d'un serveur à 5 USD/mois) et ensuite vous pouvez vous développer autant que vous le souhaitez en ajoutant d'autres serveurs.
Pour configurer un cluster en mode Docker Swarm avec Traefik et la gestion de HTTPS, suivez ce guide :
diff --git a/docs/fr/docs/deployment/index.md b/docs/fr/docs/deployment/index.md
new file mode 100644
index 0000000000000..e855adfa3c1ed
--- /dev/null
+++ b/docs/fr/docs/deployment/index.md
@@ -0,0 +1,28 @@
+# Déploiement - Intro
+
+Le déploiement d'une application **FastAPI** est relativement simple.
+
+## Que signifie le déploiement
+
+**Déployer** une application signifie effectuer les étapes nécessaires pour la rendre **disponible pour les
+utilisateurs**.
+
+Pour une **API Web**, cela implique normalement de la placer sur une **machine distante**, avec un **programme serveur**
+qui offre de bonnes performances, une bonne stabilité, _etc._, afin que vos **utilisateurs** puissent **accéder** à
+l'application efficacement et sans interruption ni problème.
+
+Ceci contraste avec les étapes de **développement**, où vous êtes constamment en train de modifier le code, de le casser
+et de le réparer, d'arrêter et de redémarrer le serveur de développement, _etc._
+
+## Stratégies de déploiement
+
+Il existe plusieurs façons de procéder, en fonction de votre cas d'utilisation spécifique et des outils que vous
+utilisez.
+
+Vous pouvez **déployer un serveur** vous-même en utilisant une combinaison d'outils, vous pouvez utiliser un **service
+cloud** qui fait une partie du travail pour vous, ou encore d'autres options possibles.
+
+Je vais vous montrer certains des principaux concepts que vous devriez probablement avoir à l'esprit lors du déploiement
+d'une application **FastAPI** (bien que la plupart de ces concepts s'appliquent à tout autre type d'application web).
+
+Vous verrez plus de détails à avoir en tête et certaines des techniques pour le faire dans les sections suivantes. ✨
diff --git a/docs/fr/docs/features.md b/docs/fr/docs/features.md
index 4d8f18403a0d0..dcc0e39ed77ac 100644
--- a/docs/fr/docs/features.md
+++ b/docs/fr/docs/features.md
@@ -27,7 +27,7 @@ Documentation d'API interactive et interface web d'exploration. Comme le framewo
Tout est basé sur la déclaration de type standard de **Python 3.6** (grâce à Pydantic). Pas de nouvelles syntaxes à apprendre. Juste du Python standard et moderne.
-Si vous souhaitez un rappel de 2 minutes sur l'utilisation des types en Python (même si vous ne comptez pas utiliser FastAPI), jetez un oeil au tutoriel suivant: [Python Types](python-types.md){.internal-link target=_blank}.
+Si vous souhaitez un rappel de 2 minutes sur l'utilisation des types en Python (même si vous ne comptez pas utiliser FastAPI), jetez un oeil au tutoriel suivant: [Python Types](python-types.md){.internal-link target=_blank}.
Vous écrivez du python standard avec des annotations de types:
@@ -190,7 +190,7 @@ Avec **FastAPI** vous aurez toutes les fonctionnalités de **Pydantic** (comme
* Aide votre **IDE/linter/cerveau**:
* Parce que les structures de données de pydantic consistent seulement en une instance de classe que vous définissez; l'auto-complétion, le linting, mypy et votre intuition devrait être largement suffisante pour valider vos données.
* **Rapide**:
- * Dans les benchmarks Pydantic est plus rapide que toutes les autres librairies testées.
+ * Dans les benchmarks Pydantic est plus rapide que toutes les autres librairies testées.
* Valide les **structures complexes**:
* Utilise les modèles hiérarchique de Pydantic, le `typage` Python pour les `Lists`, `Dict`, etc.
* Et les validateurs permettent aux schémas de données complexes d'être clairement et facilement définis, validés et documentés sous forme d'un schéma JSON.
diff --git a/docs/fr/docs/history-design-future.md b/docs/fr/docs/history-design-future.md
new file mode 100644
index 0000000000000..b77664be6c2c0
--- /dev/null
+++ b/docs/fr/docs/history-design-future.md
@@ -0,0 +1,79 @@
+# Histoire, conception et avenir
+
+Il y a quelque temps, un utilisateur de **FastAPI** a demandé :
+
+> Quelle est l'histoire de ce projet ? Il semble être sorti de nulle part et est devenu génial en quelques semaines [...].
+
+Voici un petit bout de cette histoire.
+
+## Alternatives
+
+Je crée des API avec des exigences complexes depuis plusieurs années (Machine Learning, systèmes distribués, jobs asynchrones, bases de données NoSQL, etc), en dirigeant plusieurs équipes de développeurs.
+
+Dans ce cadre, j'ai dû étudier, tester et utiliser de nombreuses alternatives.
+
+L'histoire de **FastAPI** est en grande partie l'histoire de ses prédécesseurs.
+
+Comme dit dans la section [Alternatives](alternatives.md){.internal-link target=\_blank} :
+
+
+
+**FastAPI** n'existerait pas sans le travail antérieur d'autres personnes.
+
+Il y a eu de nombreux outils créés auparavant qui ont contribué à inspirer sa création.
+
+J'ai évité la création d'un nouveau framework pendant plusieurs années. J'ai d'abord essayé de résoudre toutes les fonctionnalités couvertes par **FastAPI** en utilisant de nombreux frameworks, plug-ins et outils différents.
+
+Mais à un moment donné, il n'y avait pas d'autre option que de créer quelque chose qui offre toutes ces fonctionnalités, en prenant les meilleures idées des outils précédents, et en les combinant de la meilleure façon possible, en utilisant des fonctionnalités du langage qui n'étaient même pas disponibles auparavant (annotations de type pour Python 3.6+).
+
+
+
+---
+
+**תיעוד**: https://fastapi.tiangolo.com
+
+**קוד**: https://github.com/tiangolo/fastapi
+
+---
+
+FastAPI היא תשתית רשת מודרנית ומהירה (ביצועים גבוהים) לבניית ממשקי תכנות יישומים (API) עם פייתון 3.6+ בהתבסס על רמזי טיפוסים סטנדרטיים.
+
+תכונות המפתח הן:
+
+- **מהירה**: ביצועים גבוהים מאוד, בקנה אחד עם NodeJS ו - Go (תודות ל - Starlette ו - Pydantic). [אחת מתשתיות הפייתון המהירות ביותר](#performance).
+
+- **מהירה לתכנות**: הגבירו את מהירות פיתוח התכונות החדשות בכ - %200 עד %300. \*
+- **פחות שגיאות**: מנעו כ - %40 משגיאות אנוש (מפתחים). \*
+- **אינטואיטיבית**: תמיכת עורך מעולה. השלמה בכל מקום. פחות זמן ניפוי שגיאות.
+- **קלה**: מתוכננת להיות קלה לשימוש וללמידה. פחות זמן קריאת תיעוד.
+- **קצרה**: מזערו שכפול קוד. מספר תכונות מכל הכרזת פרמטר. פחות שגיאות.
+- **חסונה**: קבלו קוד מוכן לסביבת ייצור. עם תיעוד אינטרקטיבי אוטומטי.
+- **מבוססת סטנדרטים**: מבוססת על (ותואמת לחלוטין ל -) הסטדנרטים הפתוחים לממשקי תכנות יישומים: OpenAPI (ידועים לשעבר כ - Swagger) ו - JSON Schema.
+
+\* הערכה מבוססת על בדיקות של צוות פיתוח פנימי שבונה אפליקציות בסביבת ייצור.
+
+## נותני חסות
+
+
+
+{% if sponsors %}
+{% for sponsor in sponsors.gold -%}
+
+{% endfor -%}
+{%- for sponsor in sponsors.silver -%}
+
+{% endfor %}
+{% endif %}
+
+
+
+נותני חסות אחרים
+
+## דעות
+
+"_[...] I'm using **FastAPI** a ton these days. [...] I'm actually planning to use it for all of my team's **ML services at Microsoft**. Some of them are getting integrated into the core **Windows** product and some **Office** products._"
+
+
+
+---
+
+"_We adopted the **FastAPI** library to spawn a **REST** server that can be queried to obtain **predictions**. [for Ludwig]_"
+
+
Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala - Uber(ref)
+
+---
+
+"_**Netflix** is pleased to announce the open-source release of our **crisis management** orchestration framework: **Dispatch**! [built with **FastAPI**]_"
+
+
Kevin Glisson, Marc Vilanova, Forest Monsen - Netflix(ref)
+
+---
+
+"_I’m over the moon excited about **FastAPI**. It’s so fun!_"
+
+
+
+---
+
+"_Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted **Hug** to be - it's really inspiring to see someone build that._"
+
+
+
+---
+
+"_If you're looking to learn one **modern framework** for building REST APIs, check out **FastAPI** [...] It's fast, easy to use and easy to learn [...]_"
+
+"_We've switched over to **FastAPI** for our **APIs** [...] I think you'll like it [...]_"
+
+
+
+---
+
+## **Typer**, ה - FastAPI של ממשקי שורת פקודה (CLI).
+
+
+
+אם אתם בונים אפליקציית CLI לשימוש במסוף במקום ממשק רשת, העיפו מבט על **Typer**.
+
+**Typer** היא אחותה הקטנה של FastAPI. ומטרתה היא להיות ה - **FastAPI של ממשקי שורת פקודה**. ⌨️ 🚀
+
+## תלויות
+
+פייתון 3.6+
+
+FastAPI עומדת על כתפי ענקיות:
+
+- Starlette לחלקי הרשת.
+- Pydantic לחלקי המידע.
+
+## התקנה
+
+
+
+## דוגמא
+
+### צרו אותה
+
+- צרו קובץ בשם `main.py` עם:
+
+```Python
+from typing import Union
+
+from fastapi import FastAPI
+
+app = FastAPI()
+
+
+@app.get("/")
+def read_root():
+ return {"Hello": "World"}
+
+
+@app.get("/items/{item_id}")
+def read_item(item_id: int, q: Union[str, None] = None):
+ return {"item_id": item_id, "q": q}
+```
+
+
+או השתמשו ב - async def...
+
+אם הקוד שלכם משתמש ב - `async` / `await`, השתמשו ב - `async def`:
+
+```Python hl_lines="9 14"
+from typing import Union
+
+from fastapi import FastAPI
+
+app = FastAPI()
+
+
+@app.get("/")
+async def read_root():
+ return {"Hello": "World"}
+
+
+@app.get("/items/{item_id}")
+async def read_item(item_id: int, q: Union[str, None] = None):
+ return {"item_id": item_id, "q": q}
+```
+
+**שימו לב**:
+
+אם אינכם יודעים, בדקו את פרק "ממהרים?" על `async` ו - `await` בתיעוד.
+
+
+
+### הריצו אותה
+
+התחילו את השרת עם:
+
+
+
+```console
+$ uvicorn main:app --reload
+
+INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
+INFO: Started reloader process [28720]
+INFO: Started server process [28722]
+INFO: Waiting for application startup.
+INFO: Application startup complete.
+```
+
+
+
+
+על הפקודה uvicorn main:app --reload...
+
+הפקודה `uvicorn main:app` מתייחסת ל:
+
+- `main`: הקובץ `main.py` (מודול פייתון).
+- `app`: האובייקט שנוצר בתוך `main.py` עם השורה app = FastAPI().
+- --reload: גרמו לשרת להתאתחל לאחר שינויים בקוד. עשו זאת רק בסביבת פיתוח.
+
+
+
+### בדקו אותה
+
+פתחו את הדפדפן שלכם בכתובת http://127.0.0.1:8000/items/5?q=somequery.
+
+אתם תראו תגובת JSON:
+
+```JSON
+{"item_id": 5, "q": "somequery"}
+```
+
+כבר יצרתם API ש:
+
+- מקבל בקשות HTTP בנתיבים `/` ו - /items/{item_id}.
+- שני ה _נתיבים_ מקבלים _בקשות_ `GET` (ידועות גם כ*מתודות* HTTP).
+- ה _נתיב_ /items/{item_id} כולל \*פרמטר נתיב\_ `item_id` שאמור להיות `int`.
+- ה _נתיב_ /items/{item_id} \*פרמטר שאילתא\_ אופציונלי `q`.
+
+### תיעוד API אינטרקטיבי
+
+כעת פנו לכתובת http://127.0.0.1:8000/docs.
+
+אתם תראו את התיעוד האוטומטי (מסופק על ידי Swagger UI):
+
+![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png)
+
+### תיעוד אלטרנטיבי
+
+כעת פנו לכתובת http://127.0.0.1:8000/redoc.
+
+אתם תראו תיעוד אלטרנטיבי (מסופק על ידי ReDoc):
+
+![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png)
+
+## שדרוג לדוגמא
+
+כעת ערכו את הקובץ `main.py` כך שיוכל לקבל גוף מבקשת `PUT`.
+
+הגדירו את הגוף בעזרת רמזי טיפוסים סטנדרטיים, הודות ל - `Pydantic`.
+
+```Python hl_lines="4 9-12 25-27"
+from typing import Union
+
+from fastapi import FastAPI
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class Item(BaseModel):
+ name: str
+ price: float
+ is_offer: Union[bool, None] = None
+
+
+@app.get("/")
+def read_root():
+ return {"Hello": "World"}
+
+
+@app.get("/items/{item_id}")
+def read_item(item_id: int, q: Union[str, None] = None):
+ return {"item_id": item_id, "q": q}
+
+
+@app.put("/items/{item_id}")
+def update_item(item_id: int, item: Item):
+ return {"item_name": item.name, "item_id": item_id}
+```
+
+השרת אמול להתאתחל אוטומטית (מאחר והוספתם --reload לפקודת `uvicorn` שלמעלה).
+
+### שדרוג התיעוד האינטרקטיבי
+
+כעת פנו לכתובת http://127.0.0.1:8000/docs.
+
+- התיעוד האוטומטי יתעדכן, כולל הגוף החדש:
+
+![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png)
+
+- לחצו על הכפתור "Try it out", הוא יאפשר לכם למלא את הפרמטרים ולעבוד ישירות מול ה - API.
+
+![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png)
+
+- אחר כך לחצו על הכפתור "Execute", האתר יתקשר עם ה - API שלכם, ישלח את הפרמטרים, ישיג את התוצאות ואז יראה אותן על המסך:
+
+![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png)
+
+### שדרוג התיעוד האלטרנטיבי
+
+כעת פנו לכתובת http://127.0.0.1:8000/redoc.
+
+- התיעוד האלטרנטיבי גם יראה את פרמטר השאילתא והגוף החדשים.
+
+![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png)
+
+### סיכום
+
+לסיכום, אתם מכריזים ** פעם אחת** על טיפוסי הפרמטרים, גוף וכו' כפרמטרים לפונקציה.
+
+אתם עושים את זה עם טיפוסי פייתון מודרניים.
+
+אתם לא צריכים ללמוד תחביר חדש, מתודות או מחלקות של ספרייה ספיציפית, וכו'
+
+רק **פייתון 3.6+** סטנדרטי.
+
+לדוגמא, ל - `int`:
+
+```Python
+item_id: int
+```
+
+או למודל `Item` מורכב יותר:
+
+```Python
+item: Item
+```
+
+...ועם הכרזת הטיפוס האחת הזו אתם מקבלים:
+
+- תמיכת עורך, כולל:
+ - השלמות.
+ - בדיקת טיפוסים.
+- אימות מידע:
+ - שגיאות ברורות ואטומטיות כאשר מוכנס מידע לא חוקי .
+ - אימות אפילו לאובייקטי JSON מקוננים.
+- המרה של מידע קלט: המרה של מידע שמגיע מהרשת למידע וטיפוסים של פייתון. קורא מ:
+ - JSON.
+ - פרמטרי נתיב.
+ - פרמטרי שאילתא.
+ - עוגיות.
+ - כותרות.
+ - טפסים.
+ - קבצים.
+- המרה של מידע פלט: המרה של מידע וטיפוסים מפייתון למידע רשת (כ - JSON):
+ - המירו טיפוסי פייתון (`str`, `int`, `float`, `bool`, `list`, etc).
+ - עצמי `datetime`.
+ - עצמי `UUID`.
+ - מודלי בסיסי נתונים.
+ - ...ורבים אחרים.
+- תיעוד API אוטומטי ואינטרקטיבית כולל שתי אלטרנטיבות לממשק המשתמש:
+ - Swagger UI.
+ - ReDoc.
+
+---
+
+בחזרה לדוגמאת הקוד הקודמת, **FastAPI** ידאג:
+
+- לאמת שיש `item_id` בנתיב בבקשות `GET` ו - `PUT`.
+- לאמת שה - `item_id` הוא מטיפוס `int` בבקשות `GET` ו - `PUT`.
+ - אם הוא לא, הלקוח יראה שגיאה ברורה ושימושית.
+- לבדוק האם קיים פרמטר שאילתא בשם `q` (קרי `http://127.0.0.1:8000/items/foo?q=somequery`) לבקשות `GET`.
+ - מאחר והפרמטר `q` מוגדר עם = None, הוא אופציונלי.
+ - לולא ה - `None` הוא היה חובה (כמו הגוף במקרה של `PUT`).
+- לבקשות `PUT` לנתיב /items/{item_id}, לקרוא את גוף הבקשה כ - JSON:
+ - לאמת שהוא כולל את מאפיין החובה `name` שאמור להיות מטיפוס `str`.
+ - לאמת שהוא כולל את מאפיין החובה `price` שחייב להיות מטיפוס `float`.
+ - לבדוק האם הוא כולל את מאפיין הרשות `is_offer` שאמור להיות מטיפוס `bool`, אם הוא נמצא.
+ - כל זה יעבוד גם לאובייקט JSON מקונן.
+- להמיר מ - JSON ול- JSON אוטומטית.
+- לתעד הכל באמצעות OpenAPI, תיעוד שבו יוכלו להשתמש:
+ - מערכות תיעוד אינטרקטיביות.
+ - מערכות ייצור קוד אוטומטיות, להרבה שפות.
+- לספק ישירות שתי מערכות תיעוד רשתיות.
+
+---
+
+רק גרדנו את קצה הקרחון, אבל כבר יש לכם רעיון של איך הכל עובד.
+
+נסו לשנות את השורה:
+
+```Python
+ return {"item_name": item.name, "item_id": item_id}
+```
+
+...מ:
+
+```Python
+ ... "item_name": item.name ...
+```
+
+...ל:
+
+```Python
+ ... "item_price": item.price ...
+```
+
+...וראו איך העורך שלכם משלים את המאפיינים ויודע את הטיפוסים שלהם:
+
+![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png)
+
+לדוגמא יותר שלמה שכוללת עוד תכונות, ראו את המדריך - למשתמש.
+
+**התראת ספוילרים**: המדריך - למשתמש כולל:
+
+- הכרזה על **פרמטרים** ממקורות אחרים ושונים כגון: **כותרות**, **עוגיות**, **טפסים** ו - **קבצים**.
+- איך לקבוע **מגבלות אימות** בעזרת `maximum_length` או `regex`.
+- דרך חזקה וקלה להשתמש ב**הזרקת תלויות**.
+- אבטחה והתאמתות, כולל תמיכה ב - **OAuth2** עם **JWT** והתאמתות **HTTP Basic**.
+- טכניקות מתקדמות (אבל קלות באותה מידה) להכרזת אובייקטי JSON מקוננים (תודות ל - Pydantic).
+- אינטרקציה עם **GraphQL** דרך Strawberry וספריות אחרות.
+- תכונות נוספות רבות (תודות ל - Starlette) כגון:
+ - **WebSockets**
+ - בדיקות קלות במיוחד מבוססות על `requests` ו - `pytest`
+ - **CORS**
+ - **Cookie Sessions**
+ - ...ועוד.
+
+## ביצועים
+
+בדיקות עצמאיות של TechEmpower הראו שאפליקציות **FastAPI** שרצות תחת Uvicorn הן מתשתיות הפייתון המהירות ביותר, רק מתחת ל - Starlette ו - Uvicorn עצמן (ש - FastAPI מבוססת עליהן). (\*)
+
+כדי להבין עוד על הנושא, ראו את הפרק Benchmarks.
+
+## תלויות אופציונליות
+
+בשימוש Pydantic:
+
+- ujson - "פרסור" JSON.
+- email_validator - לאימות כתובות אימייל.
+
+בשימוש Starlette:
+
+- requests - דרוש אם ברצונכם להשתמש ב - `TestClient`.
+- jinja2 - דרוש אם ברצונכם להשתמש בברירת המחדל של תצורת הטמפלייטים.
+- python-multipart - דרוש אם ברצונכם לתמוך ב "פרסור" טפסים, באצמעות request.form().
+- itsdangerous - דרוש אם ברצונכם להשתמש ב - `SessionMiddleware`.
+- pyyaml - דרוש אם ברצונכם להשתמש ב - `SchemaGenerator` של Starlette (כנראה שאתם לא צריכים את זה עם FastAPI).
+- ujson - דרוש אם ברצונכם להשתמש ב - `UJSONResponse`.
+
+בשימוש FastAPI / Starlette:
+
+- uvicorn - לשרת שטוען ומגיש את האפליקציה שלכם.
+- orjson - דרוש אם ברצונכם להשתמש ב - `ORJSONResponse`.
+
+תוכלו להתקין את כל אלו באמצעות pip install "fastapi[all]".
+
+## רשיון
+
+הפרויקט הזה הוא תחת התנאים של רשיון MIT.
diff --git a/docs/he/mkdocs.yml b/docs/he/mkdocs.yml
new file mode 100644
index 0000000000000..3279099b5abd1
--- /dev/null
+++ b/docs/he/mkdocs.yml
@@ -0,0 +1,145 @@
+site_name: FastAPI
+site_description: FastAPI framework, high performance, easy to learn, fast to code, ready for production
+site_url: https://fastapi.tiangolo.com/he/
+theme:
+ name: material
+ custom_dir: overrides
+ palette:
+ - media: '(prefers-color-scheme: light)'
+ scheme: default
+ primary: teal
+ accent: amber
+ toggle:
+ icon: material/lightbulb
+ name: Switch to light mode
+ - media: '(prefers-color-scheme: dark)'
+ scheme: slate
+ primary: teal
+ accent: amber
+ toggle:
+ icon: material/lightbulb-outline
+ name: Switch to dark mode
+ features:
+ - search.suggest
+ - search.highlight
+ - content.tabs.link
+ icon:
+ repo: fontawesome/brands/github-alt
+ logo: https://fastapi.tiangolo.com/img/icon-white.svg
+ favicon: https://fastapi.tiangolo.com/img/favicon.png
+ language: he
+repo_name: tiangolo/fastapi
+repo_url: https://github.com/tiangolo/fastapi
+edit_uri: ''
+plugins:
+- search
+- markdownextradata:
+ data: data
+nav:
+- FastAPI: index.md
+- Languages:
+ - en: /
+ - az: /az/
+ - de: /de/
+ - es: /es/
+ - fa: /fa/
+ - fr: /fr/
+ - he: /he/
+ - id: /id/
+ - it: /it/
+ - ja: /ja/
+ - ko: /ko/
+ - nl: /nl/
+ - pl: /pl/
+ - pt: /pt/
+ - ru: /ru/
+ - sq: /sq/
+ - sv: /sv/
+ - tr: /tr/
+ - uk: /uk/
+ - zh: /zh/
+markdown_extensions:
+- toc:
+ permalink: true
+- markdown.extensions.codehilite:
+ guess_lang: false
+- mdx_include:
+ base_path: docs
+- admonition
+- codehilite
+- extra
+- pymdownx.superfences:
+ custom_fences:
+ - name: mermaid
+ class: mermaid
+ format: !!python/name:pymdownx.superfences.fence_code_format ''
+- pymdownx.tabbed:
+ alternate_style: true
+- attr_list
+- md_in_html
+extra:
+ analytics:
+ provider: google
+ property: UA-133183413-1
+ social:
+ - icon: fontawesome/brands/github-alt
+ link: https://github.com/tiangolo/fastapi
+ - icon: fontawesome/brands/discord
+ link: https://discord.gg/VQjSZaeJmf
+ - icon: fontawesome/brands/twitter
+ link: https://twitter.com/fastapi
+ - icon: fontawesome/brands/linkedin
+ link: https://www.linkedin.com/in/tiangolo
+ - icon: fontawesome/brands/dev
+ link: https://dev.to/tiangolo
+ - icon: fontawesome/brands/medium
+ link: https://medium.com/@tiangolo
+ - icon: fontawesome/solid/globe
+ link: https://tiangolo.com
+ alternate:
+ - link: /
+ name: en - English
+ - link: /az/
+ name: az
+ - link: /de/
+ name: de
+ - link: /es/
+ name: es - español
+ - link: /fa/
+ name: fa
+ - link: /fr/
+ name: fr - français
+ - link: /he/
+ name: he
+ - link: /id/
+ name: id
+ - link: /it/
+ name: it - italiano
+ - link: /ja/
+ name: ja - 日本語
+ - link: /ko/
+ name: ko - 한국어
+ - link: /nl/
+ name: nl
+ - link: /pl/
+ name: pl
+ - link: /pt/
+ name: pt - português
+ - link: /ru/
+ name: ru - русский язык
+ - link: /sq/
+ name: sq - shqip
+ - link: /sv/
+ name: sv - svenska
+ - link: /tr/
+ name: tr - Türkçe
+ - link: /uk/
+ name: uk - українська мова
+ - link: /zh/
+ name: zh - 汉语
+extra_css:
+- https://fastapi.tiangolo.com/css/termynal.css
+- https://fastapi.tiangolo.com/css/custom.css
+extra_javascript:
+- https://fastapi.tiangolo.com/js/termynal.js
+- https://fastapi.tiangolo.com/js/custom.js
diff --git a/docs/he/overrides/.gitignore b/docs/he/overrides/.gitignore
new file mode 100644
index 0000000000000..e69de29bb2d1d
diff --git a/docs/id/docs/index.md b/docs/id/docs/index.md
index a7af14781a731..041e0b754f1c1 100644
--- a/docs/id/docs/index.md
+++ b/docs/id/docs/index.md
@@ -135,7 +135,7 @@ You will also need an ASGI server, for production such as
```console
-$ pip install uvicorn[standard]
+$ pip install "uvicorn[standard]"
---> 100%
```
@@ -321,7 +321,7 @@ And now, go to
+
+```console
+$ uvicorn main:app --reload
+
+INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
+INFO: Started reloader process [28720]
+INFO: Started server process [28722]
+INFO: Waiting for application startup.
+INFO: Application startup complete.
+```
+
+
+
+**SANGAT disarankan** agar kamu menulis atau meng-copy kode, meng-editnya dan menjalankannya secara lokal.
+
+Dengan menggunakannya di dalam editor, benar-benar memperlihatkan manfaat dari FastAPI, melihat bagaimana sedikitnya kode yang harus kamu tulis, semua pengecekan tipe, pelengkapan otomatis, dll.
+
+---
+
+## Install FastAPI
+
+Langkah pertama adalah dengan meng-install FastAPI.
+
+Untuk tutorial, kamu mungkin hendak meng-instalnya dengan semua pilihan fitur dan dependensinya:
+
+
+
+!!! note
+ Polecenie `uvicorn main:app` odnosi się do:
+
+ * `main`: plik `main.py` ("moduł" Python).
+ * `app`: obiekt utworzony w pliku `main.py` w lini `app = FastAPI()`.
+ * `--reload`: sprawia, że serwer uruchamia się ponownie po zmianie kodu. Używany tylko w trakcie tworzenia oprogramowania.
+
+Na wyjściu znajduje się linia z czymś w rodzaju:
+
+```hl_lines="4"
+INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
+```
+
+Ta linia pokazuje adres URL, pod którym Twoja aplikacja jest obsługiwana, na Twoim lokalnym komputerze.
+
+### Sprawdź to
+
+Otwórz w swojej przeglądarce http://127.0.0.1:8000.
+
+Zobaczysz odpowiedź w formacie JSON:
+
+```JSON
+{"message": "Hello World"}
+```
+
+### Interaktywna dokumentacja API
+
+Przejdź teraz do http://127.0.0.1:8000/docs.
+
+Zobaczysz automatyczną i interaktywną dokumentację API (dostarczoną przez Swagger UI):
+
+![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png)
+
+### Alternatywna dokumentacja API
+
+Teraz przejdź do http://127.0.0.1:8000/redoc.
+
+Zobaczysz alternatywną automatycznie wygenerowaną dokumentację API (dostarczoną przez ReDoc):
+
+![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png)
+
+### OpenAPI
+
+**FastAPI** generuje "schemat" z całym Twoim API przy użyciu standardu **OpenAPI** służącego do definiowania API.
+
+#### Schema
+
+"Schema" jest definicją lub opisem czegoś. Nie jest to kod, który go implementuje, ale po prostu abstrakcyjny opis.
+
+#### API "Schema"
+
+W typ przypadku, OpenAPI to specyfikacja, która dyktuje sposób definiowania schematu interfejsu API.
+
+Definicja schematu zawiera ścieżki API, możliwe parametry, które są przyjmowane przez endpointy, itp.
+
+#### "Schemat" danych
+
+Termin "schemat" może również odnosić się do wyglądu niektórych danych, takich jak zawartość JSON.
+
+W takim przypadku będzie to oznaczać atrybuty JSON, ich typy danych itp.
+
+#### OpenAPI i JSON Schema
+
+OpenAPI definiuje API Schema dla Twojego API, który zawiera definicje (lub "schematy") danych wysyłanych i odbieranych przez Twój interfejs API przy użyciu **JSON Schema**, standardu dla schematów danych w formacie JSON.
+
+#### Sprawdź `openapi.json`
+
+Jeśli jesteś ciekawy, jak wygląda surowy schemat OpenAPI, FastAPI automatycznie generuje JSON Schema z opisami wszystkich Twoich API.
+
+Możesz to zobaczyć bezpośrednio pod adresem: http://127.0.0.1:8000/openapi.json.
+
+Zobaczysz JSON zaczynający się od czegoś takiego:
+
+```JSON
+{
+ "openapi": "3.0.2",
+ "info": {
+ "title": "FastAPI",
+ "version": "0.1.0"
+ },
+ "paths": {
+ "/items/": {
+ "get": {
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+
+
+
+...
+```
+
+#### Do czego służy OpenAPI
+
+Schemat OpenAPI jest tym, co zasila dwa dołączone interaktywne systemy dokumentacji.
+
+Istnieją dziesiątki alternatyw, wszystkie oparte na OpenAPI. Możesz łatwo dodać dowolną z nich do swojej aplikacji zbudowanej za pomocą **FastAPI**.
+
+Możesz go również użyć do automatycznego generowania kodu dla klientów, którzy komunikują się z Twoim API. Na przykład aplikacje frontendowe, mobilne lub IoT.
+
+## Przypomnijmy, krok po kroku
+
+### Krok 1: zaimportuj `FastAPI`
+
+```Python hl_lines="1"
+{!../../../docs_src/first_steps/tutorial001.py!}
+```
+
+`FastAPI` jest klasą, która zapewnia wszystkie funkcjonalności Twojego API.
+
+!!! note "Szczegóły techniczne"
+ `FastAPI` jest klasą, która dziedziczy bezpośrednio z `Starlette`.
+
+ Oznacza to, że możesz korzystać ze wszystkich funkcjonalności Starlette również w `FastAPI`.
+
+
+### Krok 2: utwórz instancję `FastAPI`
+
+```Python hl_lines="3"
+{!../../../docs_src/first_steps/tutorial001.py!}
+```
+
+Zmienna `app` będzie tutaj "instancją" klasy `FastAPI`.
+
+Będzie to główny punkt interakcji przy tworzeniu całego interfejsu API.
+
+Ta zmienna `app` jest tą samą zmienną, do której odnosi się `uvicorn` w poleceniu:
+
+
+
+```console
+$ uvicorn main:app --reload
+
+INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
+```
+
+
+
+Jeśli stworzysz swoją aplikację, np.:
+
+```Python hl_lines="3"
+{!../../../docs_src/first_steps/tutorial002.py!}
+```
+
+I umieścisz to w pliku `main.py`, to będziesz mógł tak wywołać `uvicorn`:
+
+
+
+```console
+$ uvicorn main:my_awesome_api --reload
+
+INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
+```
+
+
+
+### Krok 3: wykonaj *operację na ścieżce*
+
+#### Ścieżka
+
+"Ścieżka" tutaj odnosi się do ostatniej części adresu URL, zaczynając od pierwszego `/`.
+
+Więc, w adresie URL takim jak:
+
+```
+https://example.com/items/foo
+```
+
+...ścieżką będzie:
+
+```
+/items/foo
+```
+
+!!! info
+ "Ścieżka" jest zazwyczaj nazywana "path", "endpoint" lub "route'.
+
+Podczas budowania API, "ścieżka" jest głównym sposobem na oddzielenie "odpowiedzialności" i „zasobów”.
+
+#### Operacje
+
+"Operacje" tutaj odnoszą się do jednej z "metod" HTTP.
+
+Jedna z:
+
+* `POST`
+* `GET`
+* `PUT`
+* `DELETE`
+
+...i te bardziej egzotyczne:
+
+* `OPTIONS`
+* `HEAD`
+* `PATCH`
+* `TRACE`
+
+W protokole HTTP można komunikować się z każdą ścieżką za pomocą jednej (lub więcej) "metod".
+
+---
+
+Podczas tworzenia API zwykle używasz tych metod HTTP do wykonania określonej akcji.
+
+Zazwyczaj używasz:
+
+* `POST`: do tworzenia danych.
+* `GET`: do odczytywania danych.
+* `PUT`: do aktualizacji danych.
+* `DELETE`: do usuwania danych.
+
+Tak więc w OpenAPI każda z metod HTTP nazywana jest "operacją".
+
+Będziemy je również nazywali "**operacjami**".
+
+#### Zdefiniuj *dekorator operacji na ścieżce*
+
+```Python hl_lines="6"
+{!../../../docs_src/first_steps/tutorial001.py!}
+```
+
+`@app.get("/")` mówi **FastAPI** że funkcja poniżej odpowiada za obsługę żądań, które trafiają do:
+
+* ścieżki `/`
+* używając operacji get
+
+!!! info "`@decorator` Info"
+ Składnia `@something` jest w Pythonie nazywana "dekoratorem".
+
+ Umieszczasz to na szczycie funkcji. Jak ładną ozdobną czapkę (chyba stąd wzięła się nazwa).
+
+ "Dekorator" przyjmuje funkcję znajdującą się poniżej jego i coś z nią robi.
+
+ W naszym przypadku dekorator mówi **FastAPI**, że poniższa funkcja odpowiada **ścieżce** `/` z **operacją** `get`.
+
+ Jest to "**dekorator operacji na ścieżce**".
+
+Możesz również użyć innej operacji:
+
+* `@app.post()`
+* `@app.put()`
+* `@app.delete()`
+
+Oraz tych bardziej egzotycznych:
+
+* `@app.options()`
+* `@app.head()`
+* `@app.patch()`
+* `@app.trace()`
+
+!!! tip
+ Możesz dowolnie używać każdej operacji (metody HTTP).
+
+ **FastAPI** nie narzuca żadnego konkretnego znaczenia.
+
+ Informacje tutaj są przedstawione jako wskazówka, a nie wymóg.
+
+ Na przykład, używając GraphQL, normalnie wykonujesz wszystkie akcje używając tylko operacji `POST`.
+
+### Krok 4: zdefiniuj **funkcję obsługującą ścieżkę**
+
+To jest nasza "**funkcja obsługująca ścieżkę**":
+
+* **ścieżka**: to `/`.
+* **operacja**: to `get`.
+* **funkcja**: to funkcja poniżej "dekoratora" (poniżej `@app.get("/")`).
+
+```Python hl_lines="7"
+{!../../../docs_src/first_steps/tutorial001.py!}
+```
+
+Jest to funkcja Python.
+
+Zostanie ona wywołana przez **FastAPI** za każdym razem, gdy otrzyma żądanie do adresu URL "`/`" przy użyciu operacji `GET`.
+
+W tym przypadku jest to funkcja "asynchroniczna".
+
+---
+
+Możesz również zdefiniować to jako normalną funkcję zamiast `async def`:
+
+```Python hl_lines="7"
+{!../../../docs_src/first_steps/tutorial003.py!}
+```
+
+!!! note
+ Jeśli nie znasz różnicy, sprawdź [Async: *"In a hurry?"*](/async/#in-a-hurry){.internal-link target=_blank}.
+
+### Krok 5: zwróć zawartość
+
+```Python hl_lines="8"
+{!../../../docs_src/first_steps/tutorial001.py!}
+```
+
+Możesz zwrócić `dict`, `list`, pojedynczą wartość jako `str`, `int`, itp.
+
+Możesz również zwrócić modele Pydantic (więcej o tym później).
+
+Istnieje wiele innych obiektów i modeli, które zostaną automatycznie skonwertowane do formatu JSON (w tym ORM itp.). Spróbuj użyć swoich ulubionych, jest bardzo prawdopodobne, że są już obsługiwane.
+
+## Podsumowanie
+
+* Zaimportuj `FastAPI`.
+* Stwórz instancję `app`.
+* Dodaj **dekorator operacji na ścieżce** (taki jak `@app.get("/")`).
+* Napisz **funkcję obsługującą ścieżkę** (taką jak `def root(): ...` powyżej).
+* Uruchom serwer deweloperski (`uvicorn main:app --reload`).
diff --git a/docs/pl/docs/tutorial/index.md b/docs/pl/docs/tutorial/index.md
index 1a97214af8ef5..ed8752a95a671 100644
--- a/docs/pl/docs/tutorial/index.md
+++ b/docs/pl/docs/tutorial/index.md
@@ -78,4 +78,3 @@ Jest też **Zaawansowany poradnik**, który możesz przeczytać po lekturze tego
Najpierw jednak powinieneś przeczytać **Samouczek** (czytasz go teraz).
Ten rozdział jest zaprojektowany tak, że możesz stworzyć kompletną aplikację używając tylko informacji tutaj zawartych, a następnie rozszerzać ją na różne sposoby, w zależności od potrzeb, używając kilku dodatkowych pomysłów z **Zaawansowanego poradnika**.
-
diff --git a/docs/pl/mkdocs.yml b/docs/pl/mkdocs.yml
index 932a43da470d6..1cd1294208f8f 100644
--- a/docs/pl/mkdocs.yml
+++ b/docs/pl/mkdocs.yml
@@ -5,13 +5,15 @@ theme:
name: material
custom_dir: overrides
palette:
- - scheme: default
+ - media: '(prefers-color-scheme: light)'
+ scheme: default
primary: teal
accent: amber
toggle:
icon: material/lightbulb
name: Switch to light mode
- - scheme: slate
+ - media: '(prefers-color-scheme: dark)'
+ scheme: slate
primary: teal
accent: amber
toggle:
@@ -42,6 +44,7 @@ nav:
- es: /es/
- fa: /fa/
- fr: /fr/
+ - he: /he/
- id: /id/
- it: /it/
- ja: /ja/
@@ -51,11 +54,13 @@ nav:
- pt: /pt/
- ru: /ru/
- sq: /sq/
+ - sv: /sv/
- tr: /tr/
- uk: /uk/
- zh: /zh/
- Samouczek:
- tutorial/index.md
+ - tutorial/first-steps.md
markdown_extensions:
- toc:
permalink: true
@@ -73,6 +78,8 @@ markdown_extensions:
format: !!python/name:pymdownx.superfences.fence_code_format ''
- pymdownx.tabbed:
alternate_style: true
+- attr_list
+- md_in_html
extra:
analytics:
provider: google
@@ -105,6 +112,8 @@ extra:
name: fa
- link: /fr/
name: fr - français
+ - link: /he/
+ name: he
- link: /id/
name: id
- link: /it/
@@ -123,6 +132,8 @@ extra:
name: ru - русский язык
- link: /sq/
name: sq - shqip
+ - link: /sv/
+ name: sv - svenska
- link: /tr/
name: tr - Türkçe
- link: /uk/
diff --git a/docs/pt/docs/alternatives.md b/docs/pt/docs/alternatives.md
index 6559b7398cfcb..61ee4f9000e10 100644
--- a/docs/pt/docs/alternatives.md
+++ b/docs/pt/docs/alternatives.md
@@ -331,7 +331,7 @@ Agora APIStar é um conjunto de ferramentas para validar especificações OpenAP
Existir.
A idéia de declarar múltiplas coisas (validação de dados, serialização e documentação) com os mesmos tipos Python, que ao mesmo tempo fornecesse grande suporte ao editor, era algo que eu considerava uma brilhante idéia.
-
+
E após procurar por um logo tempo por um framework similar e testar muitas alternativas diferentes, APIStar foi a melhor opção disponível.
Então APIStar parou de existir como um servidor e Starlette foi criado, e foi uma nova melhor fundação para tal sistema. Essa foi a inspiração final para construir **FastAPI**.
@@ -390,7 +390,7 @@ Essa é uma das principais coisas que **FastAPI** adiciona no topo, tudo baseado
Controlar todas as partes web centrais. Adiciona recursos no topo.
A classe `FastAPI` em si herda `Starlette`.
-
+
Então, qualquer coisa que você faz com Starlette, você pode fazer diretamente com **FastAPI**, pois ele é basicamente um Starlette com esteróides.
### Uvicorn
diff --git a/docs/pt/docs/async.md b/docs/pt/docs/async.md
index 44f4b5148ecaa..be1278a1b3098 100644
--- a/docs/pt/docs/async.md
+++ b/docs/pt/docs/async.md
@@ -94,7 +94,7 @@ Para "síncrono" (contrário de "assíncrono") também é utilizado o termo "seq
Essa idéia de código **assíncrono** descrito acima é algo às vezes chamado de **"concorrência"**. E é diferente de **"paralelismo"**.
-**Concorrência** e **paralelismo** ambos são relacionados a "diferentes coisas acontecendo mais ou menos ao mesmo tempo".
+**Concorrência** e **paralelismo** ambos são relacionados a "diferentes coisas acontecendo mais ou menos ao mesmo tempo".
Mas os detalhes entre *concorrência* e *paralelismo* são bem diferentes.
@@ -134,7 +134,7 @@ Mas então, embora você ainda não tenha os hambúrgueres, seu trabalho no caix
Mas enquanto você se afasta do balcão e senta na mesa com o número da sua chamada, você pode trocar sua atenção para seu _crush_ :heart_eyes:, e "trabalhar" nisso. Então você está novamente fazendo algo muito "produtivo", como flertar com seu _crush_ :heart_eyes:.
-Então o caixa diz que "seus hambúrgueres estão prontos" colocando seu número no balcão, mas você não corre que nem um maluco imediatamente quando o número exibido é o seu. Você sabe que ninguém irá roubar seus hambúrgueres porquê você tem o número de chamada, e os outros tem os números deles.
+Então o caixa diz que "seus hambúrgueres estão prontos" colocando seu número no balcão, mas você não corre que nem um maluco imediatamente quando o número exibido é o seu. Você sabe que ninguém irá roubar seus hambúrgueres porquê você tem o número de chamada, e os outros tem os números deles.
Então você espera que seu _crush_ :heart_eyes: termine a história que estava contando (terminar o trabalho atual / tarefa sendo processada), sorri gentilmente e diz que você está indo buscar os hambúrgueres.
@@ -358,9 +358,9 @@ Tudo isso é o que deixa o FastAPI poderoso (através do Starlette) e que o faz
!!! warning
Você pode provavelmente pular isso.
-
+
Esses são detalhes muito técnicos de como **FastAPI** funciona por baixo do capô.
-
+
Se você tem algum conhecimento técnico (corrotinas, threads, blocking etc) e está curioso sobre como o FastAPI controla o `async def` vs normal `def`, vá em frente.
### Funções de operação de rota
diff --git a/docs/pt/docs/benchmarks.md b/docs/pt/docs/benchmarks.md
index 7f7c95ba1c65e..07461ce46387c 100644
--- a/docs/pt/docs/benchmarks.md
+++ b/docs/pt/docs/benchmarks.md
@@ -2,7 +2,7 @@
As comparações independentes da TechEmpower mostram as aplicações **FastAPI** rodando com Uvicorn como um dos _frameworks_ Python mais rápidos disponíveis, somente atrás dos próprios Starlette e Uvicorn (utilizados internamente pelo FastAPI). (*)
-Mas quando se checa _benchmarks_ e comparações você deveria ter o seguinte em mente.
+Mas quando se checa _benchmarks_ e comparações você deveria ter o seguinte em mente.
## Comparações e velocidade
diff --git a/docs/pt/docs/deployment.md b/docs/pt/docs/deployment.md
index cd820cbd3c97b..2272467fdea0c 100644
--- a/docs/pt/docs/deployment.md
+++ b/docs/pt/docs/deployment.md
@@ -336,7 +336,7 @@ Você apenas precisa instalar um servidor ASGI compatível como:
```console
- $ pip install uvicorn[standard]
+ $ pip install "uvicorn[standard]"
---> 100%
```
diff --git a/docs/pt/docs/features.md b/docs/pt/docs/features.md
index 20014fe2df2b9..2b7836a6f2c2f 100644
--- a/docs/pt/docs/features.md
+++ b/docs/pt/docs/features.md
@@ -191,7 +191,7 @@ Com **FastAPI** você terá todos os recursos do **Pydantic** (já que FastAPI u
* Vai bem com o/a seu/sua **IDE/linter/cérebro**:
* Como as estruturas de dados do Pydantic são apenas instâncias de classes que você define, a auto completação, _linting_, _mypy_ e a sua intuição devem funcionar corretamente com seus dados validados.
* **Rápido**:
- * em _benchmarks_, o Pydantic é mais rápido que todas as outras bibliotecas testadas.
+ * em _benchmarks_, o Pydantic é mais rápido que todas as outras bibliotecas testadas.
* Valida **estruturas complexas**:
* Use modelos hierárquicos do Pydantic, `List` e `Dict` do `typing` do Python, etc.
* Validadores permitem que esquemas de dados complexos sejam limpos e facilmente definidos, conferidos e documentados como JSON Schema.
diff --git a/docs/pt/docs/help-fastapi.md b/docs/pt/docs/help-fastapi.md
index 086273a1df62c..d82ce3414a7a0 100644
--- a/docs/pt/docs/help-fastapi.md
+++ b/docs/pt/docs/help-fastapi.md
@@ -36,7 +36,7 @@ Você pode "acompanhar" (watch) o FastAPI no GitHub (clicando no botão com um "
Podendo selecionar apenas "Novos Updates".
-Fazendo isto, serão enviadas notificações (em seu email) sempre que tiver novos updates (uma nova versão) com correções de bugs e novos recursos no **FastAPI**
+Fazendo isto, serão enviadas notificações (em seu email) sempre que tiver novos updates (uma nova versão) com correções de bugs e novos recursos no **FastAPI**
## Conect-se com o autor
diff --git a/docs/pt/docs/index.md b/docs/pt/docs/index.md
index 97044dd90c921..51af486b97307 100644
--- a/docs/pt/docs/index.md
+++ b/docs/pt/docs/index.md
@@ -124,7 +124,7 @@ Você também precisará de um servidor ASGI para produção, tal como
```console
-$ pip install uvicorn[standard]
+$ pip install "uvicorn[standard]"
---> 100%
```
@@ -138,7 +138,7 @@ $ pip install uvicorn[standard]
* Crie um arquivo `main.py` com:
```Python
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
@@ -151,7 +151,7 @@ def read_root():
@app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
```
@@ -161,7 +161,7 @@ def read_item(item_id: int, q: Optional[str] = None):
Se seu código utiliza `async` / `await`, use `async def`:
```Python hl_lines="9 14"
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
@@ -174,7 +174,7 @@ async def read_root():
@app.get("/items/{item_id}")
-async def read_item(item_id: int, q: Optional[str] = None):
+async def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
```
@@ -253,6 +253,8 @@ Agora modifique o arquivo `main.py` para receber um corpo para uma requisição
Declare o corpo utilizando tipos padrão Python, graças ao Pydantic.
```Python hl_lines="4 9-12 25-27"
+from typing import Union
+
from fastapi import FastAPI
from pydantic import BaseModel
@@ -262,7 +264,7 @@ app = FastAPI()
class Item(BaseModel):
name: str
price: float
- is_offer: Optional[bool] = None
+ is_offer: Union[bool] = None
@app.get("/")
@@ -271,7 +273,7 @@ def read_root():
@app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
@@ -365,7 +367,7 @@ Voltando ao código do exemplo anterior, **FastAPI** irá:
* Como o parâmetro `q` é declarado com `= None`, ele é opcional.
* Sem o `None` ele poderia ser obrigatório (como o corpo no caso de `PUT`).
* Para requisições `PUT` para `/items/{item_id}`, lerá o corpo como JSON e:
- * Verifica que tem um atributo obrigatório `name` que deve ser `str`.
+ * Verifica que tem um atributo obrigatório `name` que deve ser `str`.
* Verifica que tem um atributo obrigatório `price` que deve ser `float`.
* Verifica que tem an atributo opcional `is_offer`, que deve ser `bool`, se presente.
* Tudo isso também funciona para objetos JSON profundamente aninhados.
diff --git a/docs/pt/docs/python-types.md b/docs/pt/docs/python-types.md
index df70afd4080bd..9f12211c74010 100644
--- a/docs/pt/docs/python-types.md
+++ b/docs/pt/docs/python-types.md
@@ -313,4 +313,3 @@ O importante é que, usando tipos padrão de Python, em um único local (em vez
!!! info "Informação"
Se você já passou por todo o tutorial e voltou para ver mais sobre os tipos, um bom recurso é a "cheat sheet" do `mypy` .
-
diff --git a/docs/pt/docs/tutorial/body.md b/docs/pt/docs/tutorial/body.md
index 5891185f36bf3..99e05ab77e95f 100644
--- a/docs/pt/docs/tutorial/body.md
+++ b/docs/pt/docs/tutorial/body.md
@@ -114,7 +114,7 @@ Mas você terá o mesmo suporte do editor no PyCharm como editor, você pode utilizar o Plugin do Pydantic para o PyCharm .
Melhora o suporte do editor para seus modelos Pydantic com::
-
+
* completação automática
* verificação de tipos
* refatoração
@@ -158,7 +158,7 @@ Os parâmetros da função serão reconhecidos conforme abaixo:
!!! note "Observação"
O FastAPI saberá que o valor de `q` não é obrigatório por causa do valor padrão `= None`.
- O `Optional` em `Optional[str]` não é utilizado pelo FastAPI, mas permite ao seu editor de texto lhe dar um suporte melhor e detectar erros.
+ O `Union` em `Union[str, None]` não é utilizado pelo FastAPI, mas permite ao seu editor de texto lhe dar um suporte melhor e detectar erros.
## Sem o Pydantic
diff --git a/docs/pt/docs/tutorial/handling-errors.md b/docs/pt/docs/tutorial/handling-errors.md
new file mode 100644
index 0000000000000..97a2e3eac9531
--- /dev/null
+++ b/docs/pt/docs/tutorial/handling-errors.md
@@ -0,0 +1,251 @@
+# Manipulação de erros
+
+Há diversas situações em que você precisa notificar um erro a um cliente que está utilizando a sua API.
+
+Esse cliente pode ser um browser com um frontend, o código de outra pessoa, um dispositivo IoT, etc.
+
+Pode ser que você precise comunicar ao cliente que:
+
+* O cliente não tem direitos para realizar aquela operação.
+* O cliente não tem acesso aquele recurso.
+* O item que o cliente está tentando acessar não existe.
+* etc.
+
+
+Nesses casos, você normalmente retornaria um **HTTP status code** próximo ao status code na faixa do status code **400** (do 400 ao 499).
+
+Isso é bastante similar ao caso do HTTP status code 200 (do 200 ao 299). Esses "200" status codes significam que, de algum modo, houve sucesso na requisição.
+
+Os status codes na faixa dos 400 significam que houve um erro por parte do cliente.
+
+Você se lembra de todos aqueles erros (e piadas) a respeito do "**404 Not Found**"?
+
+## Use o `HTTPException`
+
+Para retornar ao cliente *responses* HTTP com erros, use o `HTTPException`.
+
+### Import `HTTPException`
+
+```Python hl_lines="1"
+{!../../../docs_src/handling_errors/tutorial001.py!}
+```
+
+### Lance o `HTTPException` no seu código.
+
+`HTTPException`, ao fundo, nada mais é do que a conjunção entre uma exceção comum do Python e informações adicionais relevantes para APIs.
+
+E porque é uma exceção do Python, você não **retorna** (return) o `HTTPException`, você lança o (raise) no seu código.
+
+Isso também significa que, se você está escrevendo uma função de utilidade, a qual você está chamando dentro da sua função de operações de caminhos, e você lança o `HTTPException` dentro da função de utilidade, o resto do seu código não será executado dentro da função de operações de caminhos. Ao contrário, o `HTTPException` irá finalizar a requisição no mesmo instante e enviará o erro HTTP oriundo do `HTTPException` para o cliente.
+
+O benefício de lançar uma exceção em vez de retornar um valor ficará mais evidente na seção sobre Dependências e Segurança.
+
+Neste exemplo, quando o cliente pede, na requisição, por um item cujo ID não existe, a exceção com o status code `404` é lançada:
+
+```Python hl_lines="11"
+{!../../../docs_src/handling_errors/tutorial001.py!}
+```
+
+### A response resultante
+
+
+Se o cliente faz uma requisição para `http://example.com/items/foo` (um `item_id` `"foo"`), esse cliente receberá um HTTP status code 200, e uma resposta JSON:
+
+
+```
+{
+ "item": "The Foo Wrestlers"
+}
+```
+
+Mas se o cliente faz uma requisição para `http://example.com/items/bar` (ou seja, um não existente `item_id "bar"`), esse cliente receberá um HTTP status code 404 (o erro "não encontrado" — *not found error*), e uma resposta JSON:
+
+```JSON
+{
+ "detail": "Item not found"
+}
+```
+
+!!! tip "Dica"
+ Quando você lançar um `HTTPException`, você pode passar qualquer valor convertível em JSON como parâmetro de `detail`, e não apenas `str`.
+
+ Você pode passar um `dict` ou um `list`, etc.
+ Esses tipos de dados são manipulados automaticamente pelo **FastAPI** e convertidos em JSON.
+
+
+## Adicione headers customizados
+
+Há certas situações em que é bastante útil poder adicionar headers customizados no HTTP error. Exemplo disso seria adicionar headers customizados para tipos de segurança.
+
+Você provavelmente não precisará utilizar esses headers diretamente no seu código.
+
+Mas caso você precise, para um cenário mais complexo, você pode adicionar headers customizados:
+
+```Python hl_lines="14"
+{!../../../docs_src/handling_errors/tutorial002.py!}
+```
+
+## Instalando manipuladores de exceções customizados
+
+Você pode adicionar manipuladores de exceção customizados com a mesma seção de utilidade de exceções presentes no Starlette
+
+Digamos que você tenha uma exceção customizada `UnicornException` que você (ou uma biblioteca que você use) precise lançar (`raise`).
+
+Nesse cenário, se você precisa manipular essa exceção de modo global com o FastAPI, você pode adicionar um manipulador de exceção customizada com `@app.exception_handler()`.
+
+```Python hl_lines="5-7 13-18 24"
+{!../../../docs_src/handling_errors/tutorial003.py!}
+```
+
+Nesse cenário, se você fizer uma requisição para `/unicorns/yolo`, a *operação de caminho* vai lançar (`raise`) o `UnicornException`.
+
+Essa exceção será manipulada, contudo, pelo `unicorn_exception_handler`.
+
+Dessa forma você receberá um erro "limpo", com o HTTP status code `418` e um JSON com o conteúdo:
+
+```JSON
+{"message": "Oops! yolo did something. There goes a rainbow..."}
+```
+
+!!! note "Detalhes Técnicos"
+ Você também pode usar `from starlette.requests import Request` and `from starlette.responses import JSONResponse`.
+
+ **FastAPI** disponibiliza o mesmo `starlette.responses` através do `fastapi.responses` por conveniência ao desenvolvedor. Contudo, a maior parte das respostas disponíveis vem diretamente do Starlette. O mesmo acontece com o `Request`.
+
+## Sobrescreva o manipulador padrão de exceções
+
+**FastAPI** tem alguns manipuladores padrão de exceções.
+
+Esses manipuladores são os responsáveis por retornar o JSON padrão de respostas quando você lança (`raise`) o `HTTPException` e quando a requisição tem dados invalidos.
+
+Você pode sobrescrever esses manipuladores de exceção com os seus próprios manipuladores.
+
+## Sobrescreva exceções de validação da requisição
+
+Quando a requisição contém dados inválidos, **FastAPI** internamente lança para o `RequestValidationError`.
+
+Para sobrescrevê-lo, importe o `RequestValidationError` e use-o com o `@app.exception_handler(RequestValidationError)` para decorar o manipulador de exceções.
+
+```Python hl_lines="2 14-16"
+{!../../../docs_src/handling_errors/tutorial004.py!}
+```
+
+Se você for ao `/items/foo`, em vez de receber o JSON padrão com o erro:
+
+```JSON
+{
+ "detail": [
+ {
+ "loc": [
+ "path",
+ "item_id"
+ ],
+ "msg": "value is not a valid integer",
+ "type": "type_error.integer"
+ }
+ ]
+}
+```
+
+você receberá a versão em texto:
+
+```
+1 validation error
+path -> item_id
+ value is not a valid integer (type=type_error.integer)
+```
+
+### `RequestValidationError` vs `ValidationError`
+
+!!! warning "Aviso"
+ Você pode pular estes detalhes técnicos caso eles não sejam importantes para você neste momento.
+
+`RequestValidationError` é uma subclasse do `ValidationError` existente no Pydantic.
+
+**FastAPI** faz uso dele para que você veja o erro no seu log, caso você utilize um modelo de Pydantic em `response_model`, e seus dados tenham erro.
+
+Contudo, o cliente ou usuário não terão acesso a ele. Ao contrário, o cliente receberá um "Internal Server Error" com o HTTP status code `500`.
+
+E assim deve ser porque seria um bug no seu código ter o `ValidationError` do Pydantic na sua *response*, ou em qualquer outro lugar do seu código (que não na requisição do cliente).
+
+E enquanto você conserta o bug, os clientes / usuários não deveriam ter acesso às informações internas do erro, porque, desse modo, haveria exposição de uma vulnerabilidade de segurança.
+
+Do mesmo modo, você pode sobreescrever o `HTTPException`.
+
+Por exemplo, você pode querer retornar uma *response* em *plain text* ao invés de um JSON para os seguintes erros:
+
+```Python hl_lines="3-4 9-11 22"
+{!../../../docs_src/handling_errors/tutorial004.py!}
+```
+
+!!! note "Detalhes Técnicos"
+ Você pode usar `from starlette.responses import PlainTextResponse`.
+
+ **FastAPI** disponibiliza o mesmo `starlette.responses` como `fastapi.responses`, como conveniência a você, desenvolvedor. Contudo, a maior parte das respostas disponíveis vem diretamente do Starlette.
+
+
+### Use o body do `RequestValidationError`.
+
+O `RequestValidationError` contém o `body` que ele recebeu de dados inválidos.
+
+Você pode utilizá-lo enquanto desenvolve seu app para conectar o *body* e debugá-lo, e assim retorná-lo ao usuário, etc.
+
+Tente enviar um item inválido como este:
+
+```JSON
+{
+ "title": "towel",
+ "size": "XL"
+}
+```
+
+Você receberá uma *response* informando-o de que a data é inválida, e contendo o *body* recebido:
+
+```JSON hl_lines="12-15"
+{
+ "detail": [
+ {
+ "loc": [
+ "body",
+ "size"
+ ],
+ "msg": "value is not a valid integer",
+ "type": "type_error.integer"
+ }
+ ],
+ "body": {
+ "title": "towel",
+ "size": "XL"
+ }
+}
+```
+
+#### O `HTTPException` do FastAPI vs o `HTTPException` do Starlette.
+
+O **FastAPI** tem o seu próprio `HTTPException`.
+
+E a classe de erro `HTTPException` do **FastAPI** herda da classe de erro do `HTTPException` do Starlette.
+
+A diferença entre os dois é a de que o `HTTPException` do **FastAPI** permite que você adicione *headers* que serão incluídos nas *responses*.
+
+Esses *headers* são necessários/utilizados internamente pelo OAuth 2.0 e também por outras utilidades de segurança.
+
+Portanto, você pode continuar lançando o `HTTPException` do **FastAPI** normalmente no seu código.
+
+Porém, quando você registrar um manipulador de exceção, você deve registrá-lo através do `HTTPException` do Starlette.
+
+Dessa forma, se qualquer parte do código interno, extensão ou plug-in do Starlette lançar o `HTTPException`, o seu manipulador de exceção poderá capturar esse lançamento e tratá-lo.
+
+```Python
+from starlette.exceptions import HTTPException as StarletteHTTPException
+```
+
+### Re-use os manipulares de exceção do **FastAPI**
+
+Se você quer usar a exceção em conjunto com o mesmo manipulador de exceção *default* do **FastAPI**, você pode importar e re-usar esses manipuladores de exceção do `fastapi.exception_handlers`:
+
+```Python hl_lines="2-5 15 21"
+{!../../../docs_src/handling_errors/tutorial006.py!}
+```
+
+Nesse exemplo você apenas imprime (`print`) o erro com uma mensagem expressiva. Mesmo assim, dá para pegar a ideia. Você pode usar a exceção e então apenas re-usar o manipulador de exceção *default*.
diff --git a/docs/pt/docs/tutorial/index.md b/docs/pt/docs/tutorial/index.md
index f93fd8d75c74e..b1abd32bc19ab 100644
--- a/docs/pt/docs/tutorial/index.md
+++ b/docs/pt/docs/tutorial/index.md
@@ -43,7 +43,7 @@ Para o tutorial, você deve querer instalá-lo com todas as dependências e recu
```console
-$ pip install fastapi[all]
+$ pip install "fastapi[all]"
---> 100%
```
@@ -64,7 +64,7 @@ $ pip install fastapi[all]
Também instale o `uvicorn` para funcionar como servidor:
```
- pip install uvicorn[standard]
+ pip install "uvicorn[standard]"
```
E o mesmo para cada dependência opcional que você quiser usar.
diff --git a/docs/pt/docs/tutorial/query-params-str-validations.md b/docs/pt/docs/tutorial/query-params-str-validations.md
index baac5f4931549..9a9e071db9b3c 100644
--- a/docs/pt/docs/tutorial/query-params-str-validations.md
+++ b/docs/pt/docs/tutorial/query-params-str-validations.md
@@ -8,12 +8,12 @@ Vamos utilizar essa aplicação como exemplo:
{!../../../docs_src/query_params_str_validations/tutorial001.py!}
```
-O parâmetro de consulta `q` é do tipo `Optional[str]`, o que significa que é do tipo `str` mas que também pode ser `None`, e de fato, o valor padrão é `None`, então o FastAPI saberá que não é obrigatório.
+O parâmetro de consulta `q` é do tipo `Union[str, None]`, o que significa que é do tipo `str` mas que também pode ser `None`, e de fato, o valor padrão é `None`, então o FastAPI saberá que não é obrigatório.
!!! note "Observação"
O FastAPI saberá que o valor de `q` não é obrigatório por causa do valor padrão `= None`.
- O `Optional` em `Optional[str]` não é usado pelo FastAPI, mas permitirá que seu editor lhe dê um melhor suporte e detecte erros.
+ O `Union` em `Union[str, None]` não é usado pelo FastAPI, mas permitirá que seu editor lhe dê um melhor suporte e detecte erros.
## Validação adicional
@@ -35,18 +35,18 @@ Agora utilize-o como valor padrão do seu parâmetro, definindo o parâmetro `ma
{!../../../docs_src/query_params_str_validations/tutorial002.py!}
```
-Note que substituímos o valor padrão de `None` para `Query(None)`, o primeiro parâmetro de `Query` serve para o mesmo propósito: definir o valor padrão do parâmetro.
+Note que substituímos o valor padrão de `None` para `Query(default=None)`, o primeiro parâmetro de `Query` serve para o mesmo propósito: definir o valor padrão do parâmetro.
Então:
```Python
-q: Optional[str] = Query(None)
+q: Union[str, None] = Query(default=None)
```
...Torna o parâmetro opcional, da mesma maneira que:
```Python
-q: Optional[str] = None
+q: Union[str, None] = None
```
Mas o declara explicitamente como um parâmetro de consulta.
@@ -61,17 +61,17 @@ Mas o declara explicitamente como um parâmetro de consulta.
Ou com:
```Python
- = Query(None)
+ = Query(default=None)
```
E irá utilizar o `None` para detectar que o parâmetro de consulta não é obrigatório.
- O `Optional` é apenas para permitir que seu editor de texto lhe dê um melhor suporte.
+ O `Union` é apenas para permitir que seu editor de texto lhe dê um melhor suporte.
Então, podemos passar mais parâmetros para `Query`. Neste caso, o parâmetro `max_length` que se aplica a textos:
```Python
-q: str = Query(None, max_length=50)
+q: str = Query(default=None, max_length=50)
```
Isso irá validar os dados, mostrar um erro claro quando os dados forem inválidos, e documentar o parâmetro na *operação de rota* do esquema OpenAPI..
@@ -80,7 +80,7 @@ Isso irá validar os dados, mostrar um erro claro quando os dados forem inválid
Você também pode incluir um parâmetro `min_length`:
-```Python hl_lines="9"
+```Python hl_lines="10"
{!../../../docs_src/query_params_str_validations/tutorial003.py!}
```
@@ -88,7 +88,7 @@ Você também pode incluir um parâmetro `min_length`:
Você pode definir uma expressão regular que combine com um padrão esperado pelo parâmetro:
-```Python hl_lines="10"
+```Python hl_lines="11"
{!../../../docs_src/query_params_str_validations/tutorial004.py!}
```
@@ -126,13 +126,13 @@ q: str
em vez desta:
```Python
-q: Optional[str] = None
+q: Union[str, None] = None
```
Mas agora nós o estamos declarando como `Query`, conforme abaixo:
```Python
-q: Optional[str] = Query(None, min_length=3)
+q: Union[str, None] = Query(default=None, min_length=3)
```
Então, quando você precisa declarar um parâmetro obrigatório utilizando o `Query`, você pode utilizar `...` como o primeiro argumento:
diff --git a/docs/pt/docs/tutorial/query-params.md b/docs/pt/docs/tutorial/query-params.md
new file mode 100644
index 0000000000000..1897243961b73
--- /dev/null
+++ b/docs/pt/docs/tutorial/query-params.md
@@ -0,0 +1,224 @@
+# Parâmetros de Consulta
+
+Quando você declara outros parâmetros na função que não fazem parte dos parâmetros da rota, esses parâmetros são automaticamente interpretados como parâmetros de "consulta".
+
+```Python hl_lines="9"
+{!../../../docs_src/query_params/tutorial001.py!}
+```
+
+A consulta é o conjunto de pares chave-valor que vai depois de `?` na URL, separado pelo caractere `&`.
+
+Por exemplo, na URL:
+
+```
+http://127.0.0.1:8000/items/?skip=0&limit=10
+```
+
+...os parâmetros da consulta são:
+
+* `skip`: com o valor `0`
+* `limit`: com o valor `10`
+
+Como eles são parte da URL, eles são "naturalmente" strings.
+
+Mas quando você declara eles com os tipos do Python (no exemplo acima, como `int`), eles são convertidos para aquele tipo e validados em relação a ele.
+
+Todo o processo que era aplicado para parâmetros de rota também é aplicado para parâmetros de consulta:
+
+* Suporte do editor (obviamente)
+* "Parsing" de dados
+* Validação de dados
+* Documentação automática
+
+## Valores padrão
+
+Como os parâmetros de consulta não são uma parte fixa da rota, eles podem ser opcionais e podem ter valores padrão.
+
+No exemplo acima eles tem valores padrão de `skip=0` e `limit=10`.
+
+Então, se você for até a URL:
+
+```
+http://127.0.0.1:8000/items/
+```
+
+Seria o mesmo que ir para:
+
+```
+http://127.0.0.1:8000/items/?skip=0&limit=10
+```
+
+Mas, se por exemplo você for para:
+
+```
+http://127.0.0.1:8000/items/?skip=20
+```
+
+Os valores dos parâmetros na sua função serão:
+
+* `skip=20`: Por que você definiu isso na URL
+* `limit=10`: Por que esse era o valor padrão
+
+## Parâmetros opcionais
+
+Da mesma forma, você pode declarar parâmetros de consulta opcionais, definindo o valor padrão para `None`:
+
+=== "Python 3.6 and above"
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/query_params/tutorial002.py!}
+ ```
+
+=== "Python 3.10 and above"
+
+ ```Python hl_lines="7"
+ {!> ../../../docs_src/query_params/tutorial002_py310.py!}
+ ```
+
+Nesse caso, o parâmetro da função `q` será opcional, e `None` será o padrão.
+
+!!! check "Verificar"
+ Você também pode notar que o **FastAPI** é esperto o suficiente para perceber que o parâmetro da rota `item_id` é um parâmetro da rota, e `q` não é, portanto, `q` é o parâmetro de consulta.
+
+
+## Conversão dos tipos de parâmetros de consulta
+
+Você também pode declarar tipos `bool`, e eles serão convertidos:
+
+=== "Python 3.6 and above"
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/query_params/tutorial003.py!}
+ ```
+
+=== "Python 3.10 and above"
+
+ ```Python hl_lines="7"
+ {!> ../../../docs_src/query_params/tutorial003_py310.py!}
+ ```
+
+Nesse caso, se você for para:
+
+```
+http://127.0.0.1:8000/items/foo?short=1
+```
+
+ou
+
+```
+http://127.0.0.1:8000/items/foo?short=True
+```
+
+ou
+
+```
+http://127.0.0.1:8000/items/foo?short=true
+```
+
+ou
+
+```
+http://127.0.0.1:8000/items/foo?short=on
+```
+
+ou
+
+```
+http://127.0.0.1:8000/items/foo?short=yes
+```
+
+ou qualquer outra variação (tudo em maiúscula, primeira letra em maiúscula, etc), a sua função vai ver o parâmetro `short` com um valor `bool` de `True`. Caso contrário `False`.
+
+## Múltiplos parâmetros de rota e consulta
+
+Você pode declarar múltiplos parâmetros de rota e parâmetros de consulta ao mesmo tempo, o **FastAPI** vai saber o quê é o quê.
+
+E você não precisa declarar eles em nenhuma ordem específica.
+
+Eles serão detectados pelo nome:
+
+=== "Python 3.6 and above"
+
+ ```Python hl_lines="8 10"
+ {!> ../../../docs_src/query_params/tutorial004.py!}
+ ```
+
+=== "Python 3.10 and above"
+
+ ```Python hl_lines="6 8"
+ {!> ../../../docs_src/query_params/tutorial004_py310.py!}
+ ```
+
+## Parâmetros de consulta obrigatórios
+
+Quando você declara um valor padrão para parâmetros que não são de rota (até agora, nós vimos apenas parâmetros de consulta), então eles não são obrigatórios.
+
+Caso você não queira adicionar um valor específico mas queira apenas torná-lo opcional, defina o valor padrão como `None`.
+
+Porém, quando você quiser fazer com que o parâmetro de consulta seja obrigatório, você pode simplesmente não declarar nenhum valor como padrão.
+
+```Python hl_lines="6-7"
+{!../../../docs_src/query_params/tutorial005.py!}
+```
+
+Aqui o parâmetro de consulta `needy` é um valor obrigatório, do tipo `str`.
+
+Se você abrir no seu navegador a URL:
+
+```
+http://127.0.0.1:8000/items/foo-item
+```
+
+... sem adicionar o parâmetro obrigatório `needy`, você verá um erro como:
+
+```JSON
+{
+ "detail": [
+ {
+ "loc": [
+ "query",
+ "needy"
+ ],
+ "msg": "field required",
+ "type": "value_error.missing"
+ }
+ ]
+}
+```
+
+Como `needy` é um parâmetro obrigatório, você precisaria defini-lo na URL:
+
+```
+http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
+```
+
+...isso deve funcionar:
+
+```JSON
+{
+ "item_id": "foo-item",
+ "needy": "sooooneedy"
+}
+```
+
+E claro, você pode definir alguns parâmetros como obrigatórios, alguns possuindo um valor padrão, e outros sendo totalmente opcionais:
+
+=== "Python 3.6 and above"
+
+ ```Python hl_lines="10"
+ {!> ../../../docs_src/query_params/tutorial006.py!}
+ ```
+
+=== "Python 3.10 and above"
+
+ ```Python hl_lines="8"
+ {!> ../../../docs_src/query_params/tutorial006_py310.py!}
+ ```
+Nesse caso, existem 3 parâmetros de consulta:
+
+* `needy`, um `str` obrigatório.
+* `skip`, um `int` com o valor padrão `0`.
+* `limit`, um `int` opcional.
+
+!!! tip "Dica"
+ Você também poderia usar `Enum` da mesma forma que com [Path Parameters](path-params.md#predefined-values){.internal-link target=_blank}.
diff --git a/docs/pt/docs/tutorial/security/first-steps.md b/docs/pt/docs/tutorial/security/first-steps.md
new file mode 100644
index 0000000000000..ed07d1c963102
--- /dev/null
+++ b/docs/pt/docs/tutorial/security/first-steps.md
@@ -0,0 +1,181 @@
+# Segurança - Primeiros Passos
+
+Vamos imaginar que você tem a sua API **backend** em algum domínio.
+
+E você tem um **frontend** em outro domínio ou em um path diferente no mesmo domínio (ou em uma aplicação mobile).
+
+E você quer uma maneira de o frontend autenticar o backend, usando um **username** e **senha**.
+
+Nós podemos usar o **OAuth2** junto com o **FastAPI**.
+
+Mas, vamos poupar-lhe o tempo de ler toda a especificação apenas para achar as pequenas informações que você precisa.
+
+Vamos usar as ferramentas fornecidas pela **FastAPI** para lidar com segurança.
+
+## Como Parece
+
+Vamos primeiro usar o código e ver como funciona, e depois voltaremos para entender o que está acontecendo.
+
+## Crie um `main.py`
+Copie o exemplo em um arquivo `main.py`:
+
+```Python
+{!../../../docs_src/security/tutorial001.py!}
+```
+
+## Execute-o
+
+!!! informação
+ Primeiro, instale `python-multipart`.
+
+ Ex: `pip install python-multipart`.
+
+ Isso ocorre porque o **OAuth2** usa "dados de um formulário" para mandar o **username** e **senha**.
+
+Execute esse exemplo com:
+
+
+
+```console
+$ uvicorn main:app --reload
+
+INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
+```
+
+
+
+---
+
+**Documentation**: https://fastapi.tiangolo.com
+
+**Source Code**: https://github.com/tiangolo/fastapi
+
+---
+
+FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints.
+
+The key features are:
+
+* **Fast**: Very high performance, on par with **NodeJS** and **Go** (thanks to Starlette and Pydantic). [One of the fastest Python frameworks available](#performance).
+
+* **Fast to code**: Increase the speed to develop features by about 200% to 300%. *
+* **Fewer bugs**: Reduce about 40% of human (developer) induced errors. *
+* **Intuitive**: Great editor support. Completion everywhere. Less time debugging.
+* **Easy**: Designed to be easy to use and learn. Less time reading docs.
+* **Short**: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.
+* **Robust**: Get production-ready code. With automatic interactive documentation.
+* **Standards-based**: Based on (and fully compatible with) the open standards for APIs: OpenAPI (previously known as Swagger) and JSON Schema.
+
+* estimation based on tests on an internal development team, building production applications.
+
+## Sponsors
+
+
+
+{% if sponsors %}
+{% for sponsor in sponsors.gold -%}
+
+{% endfor -%}
+{%- for sponsor in sponsors.silver -%}
+
+{% endfor %}
+{% endif %}
+
+
+
+Other sponsors
+
+## Opinions
+
+"_[...] I'm using **FastAPI** a ton these days. [...] I'm actually planning to use it for all of my team's **ML services at Microsoft**. Some of them are getting integrated into the core **Windows** product and some **Office** products._"
+
+
+
+---
+
+"_We adopted the **FastAPI** library to spawn a **REST** server that can be queried to obtain **predictions**. [for Ludwig]_"
+
+
Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala - Uber(ref)
+
+---
+
+"_**Netflix** is pleased to announce the open-source release of our **crisis management** orchestration framework: **Dispatch**! [built with **FastAPI**]_"
+
+
Kevin Glisson, Marc Vilanova, Forest Monsen - Netflix(ref)
+
+---
+
+"_I’m over the moon excited about **FastAPI**. It’s so fun!_"
+
+
+
+---
+
+"_Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted **Hug** to be - it's really inspiring to see someone build that._"
+
+
+
+---
+
+"_If you're looking to learn one **modern framework** for building REST APIs, check out **FastAPI** [...] It's fast, easy to use and easy to learn [...]_"
+
+"_We've switched over to **FastAPI** for our **APIs** [...] I think you'll like it [...]_"
+
+
+
+---
+
+## **Typer**, the FastAPI of CLIs
+
+
+
+If you are building a CLI app to be used in the terminal instead of a web API, check out **Typer**.
+
+**Typer** is FastAPI's little sibling. And it's intended to be the **FastAPI of CLIs**. ⌨️ 🚀
+
+## Requirements
+
+Python 3.6+
+
+FastAPI stands on the shoulders of giants:
+
+* Starlette for the web parts.
+* Pydantic for the data parts.
+
+## Installation
+
+
+
+## Example
+
+### Create it
+
+* Create a file `main.py` with:
+
+```Python
+from typing import Union
+
+from fastapi import FastAPI
+
+app = FastAPI()
+
+
+@app.get("/")
+def read_root():
+ return {"Hello": "World"}
+
+
+@app.get("/items/{item_id}")
+def read_item(item_id: int, q: Union[str, None] = None):
+ return {"item_id": item_id, "q": q}
+```
+
+
+Or use async def...
+
+If your code uses `async` / `await`, use `async def`:
+
+```Python hl_lines="9 14"
+from typing import Union
+
+from fastapi import FastAPI
+
+app = FastAPI()
+
+
+@app.get("/")
+async def read_root():
+ return {"Hello": "World"}
+
+
+@app.get("/items/{item_id}")
+async def read_item(item_id: int, q: Union[str, None] = None):
+ return {"item_id": item_id, "q": q}
+```
+
+**Note**:
+
+If you don't know, check the _"In a hurry?"_ section about `async` and `await` in the docs.
+
+
+
+### Run it
+
+Run the server with:
+
+
+
+```console
+$ uvicorn main:app --reload
+
+INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
+INFO: Started reloader process [28720]
+INFO: Started server process [28722]
+INFO: Waiting for application startup.
+INFO: Application startup complete.
+```
+
+
+
+
+About the command uvicorn main:app --reload...
+
+The command `uvicorn main:app` refers to:
+
+* `main`: the file `main.py` (the Python "module").
+* `app`: the object created inside of `main.py` with the line `app = FastAPI()`.
+* `--reload`: make the server restart after code changes. Only do this for development.
+
+
+
+### Check it
+
+Open your browser at http://127.0.0.1:8000/items/5?q=somequery.
+
+You will see the JSON response as:
+
+```JSON
+{"item_id": 5, "q": "somequery"}
+```
+
+You already created an API that:
+
+* Receives HTTP requests in the _paths_ `/` and `/items/{item_id}`.
+* Both _paths_ take `GET` operations (also known as HTTP _methods_).
+* The _path_ `/items/{item_id}` has a _path parameter_ `item_id` that should be an `int`.
+* The _path_ `/items/{item_id}` has an optional `str` _query parameter_ `q`.
+
+### Interactive API docs
+
+Now go to http://127.0.0.1:8000/docs.
+
+You will see the automatic interactive API documentation (provided by Swagger UI):
+
+![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png)
+
+### Alternative API docs
+
+And now, go to http://127.0.0.1:8000/redoc.
+
+You will see the alternative automatic documentation (provided by ReDoc):
+
+![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png)
+
+## Example upgrade
+
+Now modify the file `main.py` to receive a body from a `PUT` request.
+
+Declare the body using standard Python types, thanks to Pydantic.
+
+```Python hl_lines="4 9-12 25-27"
+from typing import Union
+
+from fastapi import FastAPI
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class Item(BaseModel):
+ name: str
+ price: float
+ is_offer: Union[bool, None] = None
+
+
+@app.get("/")
+def read_root():
+ return {"Hello": "World"}
+
+
+@app.get("/items/{item_id}")
+def read_item(item_id: int, q: Union[str, None] = None):
+ return {"item_id": item_id, "q": q}
+
+
+@app.put("/items/{item_id}")
+def update_item(item_id: int, item: Item):
+ return {"item_name": item.name, "item_id": item_id}
+```
+
+The server should reload automatically (because you added `--reload` to the `uvicorn` command above).
+
+### Interactive API docs upgrade
+
+Now go to http://127.0.0.1:8000/docs.
+
+* The interactive API documentation will be automatically updated, including the new body:
+
+![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png)
+
+* Click on the button "Try it out", it allows you to fill the parameters and directly interact with the API:
+
+![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png)
+
+* Then click on the "Execute" button, the user interface will communicate with your API, send the parameters, get the results and show them on the screen:
+
+![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png)
+
+### Alternative API docs upgrade
+
+And now, go to http://127.0.0.1:8000/redoc.
+
+* The alternative documentation will also reflect the new query parameter and body:
+
+![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png)
+
+### Recap
+
+In summary, you declare **once** the types of parameters, body, etc. as function parameters.
+
+You do that with standard modern Python types.
+
+You don't have to learn a new syntax, the methods or classes of a specific library, etc.
+
+Just standard **Python 3.6+**.
+
+For example, for an `int`:
+
+```Python
+item_id: int
+```
+
+or for a more complex `Item` model:
+
+```Python
+item: Item
+```
+
+...and with that single declaration you get:
+
+* Editor support, including:
+ * Completion.
+ * Type checks.
+* Validation of data:
+ * Automatic and clear errors when the data is invalid.
+ * Validation even for deeply nested JSON objects.
+* Conversion of input data: coming from the network to Python data and types. Reading from:
+ * JSON.
+ * Path parameters.
+ * Query parameters.
+ * Cookies.
+ * Headers.
+ * Forms.
+ * Files.
+* Conversion of output data: converting from Python data and types to network data (as JSON):
+ * Convert Python types (`str`, `int`, `float`, `bool`, `list`, etc).
+ * `datetime` objects.
+ * `UUID` objects.
+ * Database models.
+ * ...and many more.
+* Automatic interactive API documentation, including 2 alternative user interfaces:
+ * Swagger UI.
+ * ReDoc.
+
+---
+
+Coming back to the previous code example, **FastAPI** will:
+
+* Validate that there is an `item_id` in the path for `GET` and `PUT` requests.
+* Validate that the `item_id` is of type `int` for `GET` and `PUT` requests.
+ * If it is not, the client will see a useful, clear error.
+* 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:
+ * Check that it has a required attribute `name` that should be a `str`.
+ * Check that it has a required attribute `price` that has to be a `float`.
+ * Check that it has an optional attribute `is_offer`, that should be a `bool`, if present.
+ * All this would also work for deeply nested JSON objects.
+* Convert from and to JSON automatically.
+* Document everything with OpenAPI, that can be used by:
+ * Interactive documentation systems.
+ * Automatic client code generation systems, for many languages.
+* Provide 2 interactive documentation web interfaces directly.
+
+---
+
+We just scratched the surface, but you already get the idea of how it all works.
+
+Try changing the line with:
+
+```Python
+ return {"item_name": item.name, "item_id": item_id}
+```
+
+...from:
+
+```Python
+ ... "item_name": item.name ...
+```
+
+...to:
+
+```Python
+ ... "item_price": item.price ...
+```
+
+...and see how your editor will auto-complete the attributes and know their types:
+
+![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png)
+
+For a more complete example including more features, see the Tutorial - User Guide.
+
+**Spoiler alert**: the tutorial - user guide includes:
+
+* Declaration of **parameters** from other different places as: **headers**, **cookies**, **form fields** and **files**.
+* How to set **validation constraints** as `maximum_length` or `regex`.
+* A very powerful and easy to use **Dependency Injection** system.
+* Security and authentication, including support for **OAuth2** with **JWT tokens** and **HTTP Basic** auth.
+* More advanced (but equally easy) techniques for declaring **deeply nested JSON models** (thanks to Pydantic).
+* **GraphQL** integration with Strawberry and other libraries.
+* Many extra features (thanks to Starlette) as:
+ * **WebSockets**
+ * extremely easy tests based on `requests` and `pytest`
+ * **CORS**
+ * **Cookie Sessions**
+ * ...and more.
+
+## Performance
+
+Independent TechEmpower benchmarks show **FastAPI** applications running under Uvicorn as one of the fastest Python frameworks available, only below Starlette and Uvicorn themselves (used internally by FastAPI). (*)
+
+To understand more about it, see the section Benchmarks.
+
+## Optional Dependencies
+
+Used by Pydantic:
+
+* ujson - for faster JSON "parsing".
+* email_validator - for email validation.
+
+Used by Starlette:
+
+* requests - Required if you want to use the `TestClient`.
+* jinja2 - Required if you want to use the default template configuration.
+* python-multipart - Required if you want to support form "parsing", with `request.form()`.
+* itsdangerous - Required for `SessionMiddleware` support.
+* pyyaml - Required for Starlette's `SchemaGenerator` support (you probably don't need it with FastAPI).
+* ujson - Required if you want to use `UJSONResponse`.
+
+Used by FastAPI / Starlette:
+
+* uvicorn - for the server that loads and serves your application.
+* orjson - Required if you want to use `ORJSONResponse`.
+
+You can install all of these with `pip install "fastapi[all]"`.
+
+## License
+
+This project is licensed under the terms of the MIT license.
diff --git a/docs/sv/mkdocs.yml b/docs/sv/mkdocs.yml
new file mode 100644
index 0000000000000..3332d232d646c
--- /dev/null
+++ b/docs/sv/mkdocs.yml
@@ -0,0 +1,145 @@
+site_name: FastAPI
+site_description: FastAPI framework, high performance, easy to learn, fast to code, ready for production
+site_url: https://fastapi.tiangolo.com/sv/
+theme:
+ name: material
+ custom_dir: overrides
+ palette:
+ - media: '(prefers-color-scheme: light)'
+ scheme: default
+ primary: teal
+ accent: amber
+ toggle:
+ icon: material/lightbulb
+ name: Switch to light mode
+ - media: '(prefers-color-scheme: dark)'
+ scheme: slate
+ primary: teal
+ accent: amber
+ toggle:
+ icon: material/lightbulb-outline
+ name: Switch to dark mode
+ features:
+ - search.suggest
+ - search.highlight
+ - content.tabs.link
+ icon:
+ repo: fontawesome/brands/github-alt
+ logo: https://fastapi.tiangolo.com/img/icon-white.svg
+ favicon: https://fastapi.tiangolo.com/img/favicon.png
+ language: sv
+repo_name: tiangolo/fastapi
+repo_url: https://github.com/tiangolo/fastapi
+edit_uri: ''
+plugins:
+- search
+- markdownextradata:
+ data: data
+nav:
+- FastAPI: index.md
+- Languages:
+ - en: /
+ - az: /az/
+ - de: /de/
+ - es: /es/
+ - fa: /fa/
+ - fr: /fr/
+ - he: /he/
+ - id: /id/
+ - it: /it/
+ - ja: /ja/
+ - ko: /ko/
+ - nl: /nl/
+ - pl: /pl/
+ - pt: /pt/
+ - ru: /ru/
+ - sq: /sq/
+ - sv: /sv/
+ - tr: /tr/
+ - uk: /uk/
+ - zh: /zh/
+markdown_extensions:
+- toc:
+ permalink: true
+- markdown.extensions.codehilite:
+ guess_lang: false
+- mdx_include:
+ base_path: docs
+- admonition
+- codehilite
+- extra
+- pymdownx.superfences:
+ custom_fences:
+ - name: mermaid
+ class: mermaid
+ format: !!python/name:pymdownx.superfences.fence_code_format ''
+- pymdownx.tabbed:
+ alternate_style: true
+- attr_list
+- md_in_html
+extra:
+ analytics:
+ provider: google
+ property: UA-133183413-1
+ social:
+ - icon: fontawesome/brands/github-alt
+ link: https://github.com/tiangolo/fastapi
+ - icon: fontawesome/brands/discord
+ link: https://discord.gg/VQjSZaeJmf
+ - icon: fontawesome/brands/twitter
+ link: https://twitter.com/fastapi
+ - icon: fontawesome/brands/linkedin
+ link: https://www.linkedin.com/in/tiangolo
+ - icon: fontawesome/brands/dev
+ link: https://dev.to/tiangolo
+ - icon: fontawesome/brands/medium
+ link: https://medium.com/@tiangolo
+ - icon: fontawesome/solid/globe
+ link: https://tiangolo.com
+ alternate:
+ - link: /
+ name: en - English
+ - link: /az/
+ name: az
+ - link: /de/
+ name: de
+ - link: /es/
+ name: es - español
+ - link: /fa/
+ name: fa
+ - link: /fr/
+ name: fr - français
+ - link: /he/
+ name: he
+ - link: /id/
+ name: id
+ - link: /it/
+ name: it - italiano
+ - link: /ja/
+ name: ja - 日本語
+ - link: /ko/
+ name: ko - 한국어
+ - link: /nl/
+ name: nl
+ - link: /pl/
+ name: pl
+ - link: /pt/
+ name: pt - português
+ - link: /ru/
+ name: ru - русский язык
+ - link: /sq/
+ name: sq - shqip
+ - link: /sv/
+ name: sv - svenska
+ - link: /tr/
+ name: tr - Türkçe
+ - link: /uk/
+ name: uk - українська мова
+ - link: /zh/
+ name: zh - 汉语
+extra_css:
+- https://fastapi.tiangolo.com/css/termynal.css
+- https://fastapi.tiangolo.com/css/custom.css
+extra_javascript:
+- https://fastapi.tiangolo.com/js/termynal.js
+- https://fastapi.tiangolo.com/js/custom.js
diff --git a/docs/sv/overrides/.gitignore b/docs/sv/overrides/.gitignore
new file mode 100644
index 0000000000000..e69de29bb2d1d
diff --git a/docs/tr/docs/features.md b/docs/tr/docs/features.md
index c06c27c16fe3e..0bcda4e9c7f85 100644
--- a/docs/tr/docs/features.md
+++ b/docs/tr/docs/features.md
@@ -6,7 +6,7 @@
### Açık standartları temel alır
-* API oluşturma işlemlerinde OpenAPI buna path operasyonları parametreleri, body talebi, güvenlik gibi şeyler dahil olmak üzere deklare bunların deklare edilmesi.
+* API oluşturma işlemlerinde OpenAPI buna path operasyonları parametreleri, body talebi, güvenlik gibi şeyler dahil olmak üzere deklare bunların deklare edilmesi.
* Otomatik olarak data modelinin JSON Schema ile beraber dokümante edilmesi (OpenAPI'n kendisi zaten JSON Schema'ya dayanıyor).
* Titiz bir çalışmanın sonucunda yukarıdaki standartlara uygun bir framework oluşturduk. Standartları pastanın üzerine sonradan eklenmiş bir çilek olarak görmedik.
* Ayrıca bu bir çok dilde kullanılabilecek **client code generator** kullanımına da izin veriyor.
@@ -74,7 +74,7 @@ my_second_user: User = User(**second_user_data)
### Editor desteği
-Bütün framework kullanılması kolay ve sezgileri güçlü olması için tasarlandı, verilen bütün kararlar geliştiricilere en iyi geliştirme deneyimini yaşatmak üzere, bir çok editör üzerinde test edildi.
+Bütün framework kullanılması kolay ve sezgileri güçlü olması için tasarlandı, verilen bütün kararlar geliştiricilere en iyi geliştirme deneyimini yaşatmak üzere, bir çok editör üzerinde test edildi.
Son yapılan Python geliştiricileri anketinde, açık ara en çok kullanılan özellik "oto-tamamlama" idi..
@@ -135,7 +135,7 @@ Bütün güvenlik şemaları OpenAPI'da tanımlanmış durumda, kapsadıkları:
Bütün güvenlik özellikleri Starlette'den geliyor (**session cookies'de** dahil olmak üzere).
-Bütün hepsi tekrardan kullanılabilir aletler ve bileşenler olarak, kolayca sistemlerinize, data depolarınıza, ilişkisel ve NoSQL databaselerinize entegre edebileceğiniz şekilde yapıldı.
+Bütün hepsi tekrardan kullanılabilir aletler ve bileşenler olarak, kolayca sistemlerinize, data depolarınıza, ilişkisel ve NoSQL databaselerinize entegre edebileceğiniz şekilde yapıldı.
### Dependency injection
@@ -198,7 +198,7 @@ Aynı şekilde, databaseden gelen objeyi de **direkt olarak isteğe** de tamamiy
* Kullandığın geliştirme araçları ile iyi çalışır **IDE/linter/brain**:
* Pydantic'in veri yapıları aslında sadece senin tanımladığın classlar; Bu yüzden doğrulanmış dataların ile otomatik tamamlama, linting ve mypy'ı kullanarak sorunsuz bir şekilde çalışabilirsin
* **Hızlı**:
- * Benchmarklarda, Pydantic'in diğer bütün test edilmiş bütün kütüphanelerden daha hızlı.
+ * Benchmarklarda, Pydantic'in diğer bütün test edilmiş bütün kütüphanelerden daha hızlı.
* **En kompleks** yapıları bile doğrula:
* Hiyerarşik Pydantic modellerinin kullanımı ile beraber, Python `typing`’s `List` and `Dict`, vs gibi şeyleri doğrula.
* Doğrulayıcılar en kompleks data şemalarının bile temiz ve kolay bir şekilde tanımlanmasına izin veriyor, ve hepsi JSON şeması olarak dokümante ediliyor
@@ -206,4 +206,3 @@ Aynı şekilde, databaseden gelen objeyi de **direkt olarak isteğe** de tamamiy
* **Genişletilebilir**:
* Pydantic özelleştirilmiş data tiplerinin tanımlanmasının yapılmasına izin veriyor ayrıca validator decoratorü ile senin doğrulamaları genişletip, kendi doğrulayıcılarını yazmana izin veriyor.
* 100% test kapsayıcılığı.
-
diff --git a/docs/tr/docs/index.md b/docs/tr/docs/index.md
index 19f46fb4c4acf..0d5337c87462d 100644
--- a/docs/tr/docs/index.md
+++ b/docs/tr/docs/index.md
@@ -28,7 +28,7 @@
---
-FastAPI, Python 3.6+'nın standart type hintlerine dayanan modern ve hızlı (yüksek performanslı) API'lar oluşturmak için kullanılabilecek web framework'ü.
+FastAPI, Python 3.6+'nın standart type hintlerine dayanan modern ve hızlı (yüksek performanslı) API'lar oluşturmak için kullanılabilecek web framework'ü.
Ana özellikleri:
@@ -143,7 +143,7 @@ Uygulamanı kullanılabilir hale getirmek için
```console
-$ pip install uvicorn[standard]
+$ pip install "uvicorn[standard]"
---> 100%
```
@@ -157,7 +157,7 @@ $ pip install uvicorn[standard]
* `main.py` adında bir dosya oluştur :
```Python
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
@@ -170,7 +170,7 @@ def read_root():
@app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
```
@@ -180,7 +180,7 @@ def read_item(item_id: int, q: Optional[str] = None):
Eğer kodunda `async` / `await` var ise, `async def` kullan:
```Python hl_lines="9 14"
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
@@ -193,7 +193,7 @@ async def read_root():
@app.get("/items/{item_id}")
-async def read_item(item_id: int, q: Optional[str] = None):
+async def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
```
@@ -272,7 +272,7 @@ Senin için alternatif olarak (
```console
-$ pip install uvicorn[standard]
+$ pip install "uvicorn[standard]"
---> 100%
```
@@ -149,7 +149,7 @@ $ pip install uvicorn[standard]
* Create a file `main.py` with:
```Python
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
@@ -162,7 +162,7 @@ def read_root():
@app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
```
@@ -172,7 +172,7 @@ def read_item(item_id: int, q: Optional[str] = None):
If your code uses `async` / `await`, use `async def`:
```Python hl_lines="9 14"
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
@@ -185,7 +185,7 @@ async def read_root():
@app.get("/items/{item_id}")
-async def read_item(item_id: int, q: Optional[str] = None):
+async def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
```
@@ -264,7 +264,7 @@ Now modify the file `main.py` to receive a body from a `PUT` request.
Declare the body using standard Python types, thanks to Pydantic.
```Python hl_lines="4 9-12 25-27"
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
from pydantic import BaseModel
@@ -275,7 +275,7 @@ app = FastAPI()
class Item(BaseModel):
name: str
price: float
- is_offer: Optional[bool] = None
+ is_offer: Union[bool, None] = None
@app.get("/")
@@ -284,7 +284,7 @@ def read_root():
@app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
@@ -321,7 +321,7 @@ And now, go to Starlette帮助文档
diff --git a/docs/zh/docs/advanced/response-directly.md b/docs/zh/docs/advanced/response-directly.md
index 05926a9c8310c..797a878eb923b 100644
--- a/docs/zh/docs/advanced/response-directly.md
+++ b/docs/zh/docs/advanced/response-directly.md
@@ -10,7 +10,7 @@
直接返回响应可能会有用处,比如返回自定义的响应头和 cookies。
-## 返回 `Response`
+## 返回 `Response`
事实上,你可以返回任意 `Response` 或者任意 `Response` 的子类。
@@ -62,4 +62,3 @@
但是你仍可以参考 [OpenApI 中的额外响应](additional-responses.md){.internal-link target=_blank} 给响应编写文档。
在后续的章节中你可以了解到如何使用/声明这些自定义的 `Response` 的同时还保留自动化的数据转换和文档等。
-
diff --git a/docs/zh/docs/benchmarks.md b/docs/zh/docs/benchmarks.md
index c133d51b7d90e..8991c72cd9b4b 100644
--- a/docs/zh/docs/benchmarks.md
+++ b/docs/zh/docs/benchmarks.md
@@ -22,7 +22,7 @@
* 具有最佳性能,因为除了服务器本身外,它没有太多额外的代码。
* 您不会直接在 Uvicorn 中编写应用程序。这意味着您的代码至少必须包含 Starlette(或 **FastAPI**)提供的代码。如果您这样做了(即直接在 Uvicorn 中编写应用程序),最终的应用程序会和使用了框架并且最小化了应用代码和 bug 的情况具有相同的性能损耗。
* 如果要对比与 Uvicorn 对标的服务器,请将其与 Daphne,Hypercorn,uWSGI等应用服务器进行比较。
-* **Starlette**:
+* **Starlette**:
* 在 Uvicorn 后使用 Starlette,性能会略有下降。实际上,Starlette 使用 Uvicorn运行。因此,由于必须执行更多的代码,它只会比 Uvicorn 更慢。
* 但它为您提供了构建简单的网络程序的工具,并具有基于路径的路由等功能。
* 如果想对比与 Starlette 对标的开发框架,请将其与 Sanic,Flask,Django 等网络框架(或微框架)进行比较。
diff --git a/docs/zh/docs/contributing.md b/docs/zh/docs/contributing.md
index 402668c47e4b6..95500d12be3a6 100644
--- a/docs/zh/docs/contributing.md
+++ b/docs/zh/docs/contributing.md
@@ -497,4 +497,4 @@ $ bash scripts/test-cov-html.sh