diff --git a/.github/ISSUE_TEMPLATE/question.yml b/.github/DISCUSSION_TEMPLATE/questions.yml
similarity index 87%
rename from .github/ISSUE_TEMPLATE/question.yml
rename to .github/DISCUSSION_TEMPLATE/questions.yml
index 3b16b4ad0..3726b7d18 100644
--- a/.github/ISSUE_TEMPLATE/question.yml
+++ b/.github/DISCUSSION_TEMPLATE/questions.yml
@@ -1,5 +1,3 @@
-name: Question or Problem
-description: Ask a question or ask about a problem
labels: [question]
body:
- type: markdown
@@ -9,9 +7,9 @@ body:
Please follow these instructions, fill every question, and do every step. 🙏
- I'm asking this because answering questions and solving problems in GitHub issues is what consumes most of the time.
+ I'm asking this because answering questions and solving problems in GitHub is what consumes most of the time.
- I end up not being able to add new features, fix bugs, review pull requests, etc. as fast as I wish because I have to spend too much time handling issues.
+ I end up not being able to add new features, fix bugs, review pull requests, etc. as fast as I wish because I have to spend too much time handling questions.
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.
@@ -21,16 +19,16 @@ body:
And there's a high chance that you will find the solution along the way and you won't even have to submit it and wait for an answer. 😎
- As there are too many issues with questions, I'll have to close the incomplete ones. That will allow me (and others) to focus on helping people like you that follow the whole process and help us help you. 🤓
+ As there are too many questions, I'll have to discard and 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. 🤓
- type: checkboxes
id: checks
attributes:
label: First Check
description: Please confirm and check all the following options.
options:
- - label: I added a very descriptive title to this issue.
+ - label: I added a very descriptive title here.
required: true
- - label: I used the GitHub search to find a similar issue and didn't find it.
+ - label: I used the GitHub search to find a similar question and didn't find it.
required: true
- label: I searched the FastAPI documentation, with the integrated search.
required: true
@@ -38,7 +36,7 @@ body:
required: true
- label: I already read and followed all the tutorial in the docs and didn't find an answer.
required: true
- - label: I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/samuelcolvin/pydantic).
+ - label: I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/pydantic/pydantic).
required: true
- label: I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).
required: true
@@ -51,9 +49,9 @@ body:
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.
+ * Read open questions until I find 2 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.
+ * Review one Pull Request by downloading the code and following [all the review process](https://fastapi.tiangolo.com/help-fastapi/#review-pull-requests).
options:
- label: I commit to help with one of those options 👆
diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml
index 55749398f..a8f4c4de2 100644
--- a/.github/ISSUE_TEMPLATE/config.yml
+++ b/.github/ISSUE_TEMPLATE/config.yml
@@ -2,3 +2,15 @@ blank_issues_enabled: false
contact_links:
- name: Security Contact
about: Please report security vulnerabilities to security@tiangolo.com
+ - name: Question or Problem
+ about: Ask a question or ask about a problem in GitHub Discussions.
+ url: https://github.com/tiangolo/fastapi/discussions/categories/questions
+ - name: Feature Request
+ about: To suggest an idea or ask about a feature, please start with a question saying what you would like to achieve. There might be a way to do it already.
+ url: https://github.com/tiangolo/fastapi/discussions/categories/questions
+ - name: Show and tell
+ about: Show what you built with FastAPI or to be used with FastAPI.
+ url: https://github.com/tiangolo/fastapi/discussions/categories/show-and-tell
+ - name: Translations
+ about: Coordinate translations in GitHub Discussions.
+ url: https://github.com/tiangolo/fastapi/discussions/categories/translations
diff --git a/.github/ISSUE_TEMPLATE/feature-request.yml b/.github/ISSUE_TEMPLATE/feature-request.yml
deleted file mode 100644
index 322b6536a..000000000
--- a/.github/ISSUE_TEMPLATE/feature-request.yml
+++ /dev/null
@@ -1,181 +0,0 @@
-name: Feature Request
-description: Suggest an idea or ask for a feature that you would like to have in FastAPI
-labels: [enhancement]
-body:
- - type: markdown
- attributes:
- value: |
- 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.
-
- 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. 🤓
- - type: checkboxes
- id: checks
- attributes:
- label: First Check
- description: Please confirm and check all the following options.
- options:
- - label: I added a very descriptive title to this issue.
- required: true
- - label: I used the GitHub search to find a similar issue and didn't find it.
- required: true
- - label: I searched the FastAPI documentation, with the integrated search.
- required: true
- - label: I already searched in Google "How to X in FastAPI" and didn't find any information.
- required: true
- - label: I already read and followed all the tutorial in the docs and didn't find an answer.
- required: true
- - label: I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/samuelcolvin/pydantic).
- required: true
- - label: I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).
- required: true
- - label: I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).
- required: true
- - type: checkboxes
- id: help
- attributes:
- 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.
-
- options:
- - label: I commit to help with one of those options 👆
- required: true
- - type: textarea
- id: example
- attributes:
- label: Example Code
- description: |
- Please add a self-contained, [minimal, reproducible, example](https://stackoverflow.com/help/minimal-reproducible-example) with your use case.
-
- If I (or someone) can copy it, run it, and see it right away, there's a much higher chance I (or someone) will be able to help you.
-
- placeholder: |
- from fastapi import FastAPI
-
- app = FastAPI()
-
-
- @app.get("/")
- def read_root():
- return {"Hello": "World"}
- render: python
- validations:
- required: true
- - type: textarea
- id: description
- attributes:
- label: Description
- description: |
- What is your feature request?
-
- Write a short description telling me what you are trying to solve and what you are currently doing.
- placeholder: |
- * Open the browser and call the endpoint `/`.
- * It returns a JSON with `{"Hello": "World"}`.
- * I would like it to have an extra parameter to teleport me to the moon and back.
- validations:
- required: true
- - type: textarea
- id: wanted-solution
- attributes:
- label: Wanted Solution
- description: |
- Tell me what's the solution you would like.
- placeholder: |
- I would like it to have a `teleport_to_moon` parameter that defaults to `False`, and can be set to `True` to teleport me.
- validations:
- required: true
- - type: textarea
- id: wanted-code
- attributes:
- label: Wanted Code
- description: Show me an example of how you would want the code to look like.
- placeholder: |
- from fastapi import FastAPI
-
- app = FastAPI()
-
-
- @app.get("/", teleport_to_moon=True)
- def read_root():
- return {"Hello": "World"}
- render: python
- validations:
- required: true
- - type: textarea
- id: alternatives
- attributes:
- label: Alternatives
- description: |
- Tell me about alternatives you've considered.
- placeholder: |
- To wait for Space X moon travel plans to drop down long after they release them. But I would rather teleport.
- - type: dropdown
- id: os
- attributes:
- label: Operating System
- description: What operating system are you on?
- multiple: true
- options:
- - Linux
- - Windows
- - macOS
- - Other
- validations:
- required: true
- - type: textarea
- id: os-details
- attributes:
- label: Operating System Details
- description: You can add more details about your operating system here, in particular if you chose "Other".
- - type: input
- id: fastapi-version
- attributes:
- label: FastAPI Version
- description: |
- What FastAPI version are you using?
-
- You can find the FastAPI version with:
-
- ```bash
- python -c "import fastapi; print(fastapi.__version__)"
- ```
- validations:
- required: true
- - type: input
- id: python-version
- attributes:
- label: Python Version
- description: |
- What Python version are you using?
-
- You can find the Python version with:
-
- ```bash
- python --version
- ```
- validations:
- required: true
- - type: textarea
- id: context
- attributes:
- label: Additional Context
- description: Add any additional context information or screenshots you think are useful.
diff --git a/.github/ISSUE_TEMPLATE/privileged.yml b/.github/ISSUE_TEMPLATE/privileged.yml
new file mode 100644
index 000000000..c01e34b6d
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/privileged.yml
@@ -0,0 +1,22 @@
+name: Privileged
+description: You are @tiangolo or he asked you directly to create an issue here. If not, check the other options. 👇
+body:
+ - type: markdown
+ attributes:
+ value: |
+ Thanks for your interest in FastAPI! 🚀
+
+ If you are not @tiangolo or he didn't ask you directly to create an issue here, please start the conversation in a [Question in GitHub Discussions](https://github.com/tiangolo/fastapi/discussions/categories/questions) instead.
+ - type: checkboxes
+ id: privileged
+ attributes:
+ label: Privileged issue
+ description: Confirm that you are allowed to create an issue here.
+ options:
+ - label: I'm @tiangolo or he asked me directly to create an issue here.
+ required: true
+ - type: textarea
+ id: content
+ attributes:
+ label: Issue Content
+ description: Add the content of the issue here.
diff --git a/.github/actions/notify-translations/app/main.py b/.github/actions/notify-translations/app/main.py
index d4ba0ecfc..494fe6ad8 100644
--- a/.github/actions/notify-translations/app/main.py
+++ b/.github/actions/notify-translations/app/main.py
@@ -1,10 +1,11 @@
import logging
import random
+import sys
import time
from pathlib import Path
-from typing import Dict, Union
+from typing import Any, Dict, List, Union, cast
-import yaml
+import httpx
from github import Github
from pydantic import BaseModel, BaseSettings, SecretStr
@@ -13,12 +14,172 @@ lang_all_label = "lang-all"
approved_label = "approved-2"
translations_path = Path(__file__).parent / "translations.yml"
+github_graphql_url = "https://api.github.com/graphql"
+questions_translations_category_id = "DIC_kwDOCZduT84CT5P9"
+
+all_discussions_query = """
+query Q($category_id: ID) {
+ repository(name: "fastapi", owner: "tiangolo") {
+ discussions(categoryId: $category_id, first: 100) {
+ nodes {
+ title
+ id
+ number
+ labels(first: 10) {
+ edges {
+ node {
+ id
+ name
+ }
+ }
+ }
+ }
+ }
+ }
+}
+"""
+
+translation_discussion_query = """
+query Q($after: String, $discussion_number: Int!) {
+ repository(name: "fastapi", owner: "tiangolo") {
+ discussion(number: $discussion_number) {
+ comments(first: 100, after: $after) {
+ edges {
+ cursor
+ node {
+ id
+ url
+ body
+ }
+ }
+ }
+ }
+ }
+}
+"""
+
+add_comment_mutation = """
+mutation Q($discussion_id: ID!, $body: String!) {
+ addDiscussionComment(input: {discussionId: $discussion_id, body: $body}) {
+ comment {
+ id
+ url
+ body
+ }
+ }
+}
+"""
+
+update_comment_mutation = """
+mutation Q($comment_id: ID!, $body: String!) {
+ updateDiscussionComment(input: {commentId: $comment_id, body: $body}) {
+ comment {
+ id
+ url
+ body
+ }
+ }
+}
+"""
+
+
+class Comment(BaseModel):
+ id: str
+ url: str
+ body: str
+
+
+class UpdateDiscussionComment(BaseModel):
+ comment: Comment
+
+
+class UpdateCommentData(BaseModel):
+ updateDiscussionComment: UpdateDiscussionComment
+
+
+class UpdateCommentResponse(BaseModel):
+ data: UpdateCommentData
+
+
+class AddDiscussionComment(BaseModel):
+ comment: Comment
+
+
+class AddCommentData(BaseModel):
+ addDiscussionComment: AddDiscussionComment
+
+
+class AddCommentResponse(BaseModel):
+ data: AddCommentData
+
+
+class CommentsEdge(BaseModel):
+ node: Comment
+ cursor: str
+
+
+class Comments(BaseModel):
+ edges: List[CommentsEdge]
+
+
+class CommentsDiscussion(BaseModel):
+ comments: Comments
+
+
+class CommentsRepository(BaseModel):
+ discussion: CommentsDiscussion
+
+
+class CommentsData(BaseModel):
+ repository: CommentsRepository
+
+
+class CommentsResponse(BaseModel):
+ data: CommentsData
+
+
+class AllDiscussionsLabelNode(BaseModel):
+ id: str
+ name: str
+
+
+class AllDiscussionsLabelsEdge(BaseModel):
+ node: AllDiscussionsLabelNode
+
+
+class AllDiscussionsDiscussionLabels(BaseModel):
+ edges: List[AllDiscussionsLabelsEdge]
+
+
+class AllDiscussionsDiscussionNode(BaseModel):
+ title: str
+ id: str
+ number: int
+ labels: AllDiscussionsDiscussionLabels
+
+
+class AllDiscussionsDiscussions(BaseModel):
+ nodes: List[AllDiscussionsDiscussionNode]
+
+
+class AllDiscussionsRepository(BaseModel):
+ discussions: AllDiscussionsDiscussions
+
+
+class AllDiscussionsData(BaseModel):
+ repository: AllDiscussionsRepository
+
+
+class AllDiscussionsResponse(BaseModel):
+ data: AllDiscussionsData
+
class Settings(BaseSettings):
github_repository: str
input_token: SecretStr
github_event_path: Path
github_event_name: Union[str, None] = None
+ httpx_timeout: int = 30
input_debug: Union[bool, None] = False
@@ -30,6 +191,113 @@ class PartialGitHubEvent(BaseModel):
pull_request: PartialGitHubEventIssue
+def get_graphql_response(
+ *,
+ settings: Settings,
+ query: str,
+ after: Union[str, None] = None,
+ category_id: Union[str, None] = None,
+ discussion_number: Union[int, None] = None,
+ discussion_id: Union[str, None] = None,
+ comment_id: Union[str, None] = None,
+ body: Union[str, None] = None,
+) -> Dict[str, Any]:
+ headers = {"Authorization": f"token {settings.input_token.get_secret_value()}"}
+ # some fields are only used by one query, but GraphQL allows unused variables, so
+ # keep them here for simplicity
+ variables = {
+ "after": after,
+ "category_id": category_id,
+ "discussion_number": discussion_number,
+ "discussion_id": discussion_id,
+ "comment_id": comment_id,
+ "body": body,
+ }
+ response = httpx.post(
+ github_graphql_url,
+ headers=headers,
+ timeout=settings.httpx_timeout,
+ json={"query": query, "variables": variables, "operationName": "Q"},
+ )
+ if response.status_code != 200:
+ logging.error(
+ f"Response was not 200, after: {after}, category_id: {category_id}"
+ )
+ logging.error(response.text)
+ raise RuntimeError(response.text)
+ data = response.json()
+ if "errors" in data:
+ logging.error(f"Errors in response, after: {after}, category_id: {category_id}")
+ logging.error(response.text)
+ raise RuntimeError(response.text)
+ return cast(Dict[str, Any], data)
+
+
+def get_graphql_translation_discussions(*, settings: Settings):
+ data = get_graphql_response(
+ settings=settings,
+ query=all_discussions_query,
+ category_id=questions_translations_category_id,
+ )
+ graphql_response = AllDiscussionsResponse.parse_obj(data)
+ return graphql_response.data.repository.discussions.nodes
+
+
+def get_graphql_translation_discussion_comments_edges(
+ *, settings: Settings, discussion_number: int, after: Union[str, None] = None
+):
+ data = get_graphql_response(
+ settings=settings,
+ query=translation_discussion_query,
+ discussion_number=discussion_number,
+ after=after,
+ )
+ graphql_response = CommentsResponse.parse_obj(data)
+ return graphql_response.data.repository.discussion.comments.edges
+
+
+def get_graphql_translation_discussion_comments(
+ *, settings: Settings, discussion_number: int
+):
+ comment_nodes: List[Comment] = []
+ discussion_edges = get_graphql_translation_discussion_comments_edges(
+ settings=settings, discussion_number=discussion_number
+ )
+
+ while discussion_edges:
+ for discussion_edge in discussion_edges:
+ comment_nodes.append(discussion_edge.node)
+ last_edge = discussion_edges[-1]
+ discussion_edges = get_graphql_translation_discussion_comments_edges(
+ settings=settings,
+ discussion_number=discussion_number,
+ after=last_edge.cursor,
+ )
+ return comment_nodes
+
+
+def create_comment(*, settings: Settings, discussion_id: str, body: str):
+ data = get_graphql_response(
+ settings=settings,
+ query=add_comment_mutation,
+ discussion_id=discussion_id,
+ body=body,
+ )
+ response = AddCommentResponse.parse_obj(data)
+ return response.data.addDiscussionComment.comment
+
+
+def update_comment(*, settings: Settings, comment_id: str, body: str):
+ data = get_graphql_response(
+ settings=settings,
+ query=update_comment_mutation,
+ comment_id=comment_id,
+ body=body,
+ )
+ response = UpdateCommentResponse.parse_obj(data)
+ return response.data.updateDiscussionComment.comment
+
+
if __name__ == "__main__":
settings = Settings()
if settings.input_debug:
@@ -45,60 +313,105 @@ if __name__ == "__main__":
)
contents = settings.github_event_path.read_text()
github_event = PartialGitHubEvent.parse_raw(contents)
- translations_map: Dict[str, int] = yaml.safe_load(translations_path.read_text())
- logging.debug(f"Using translations map: {translations_map}")
+
+ # Avoid race conditions with multiple labels
sleep_time = random.random() * 10 # random number between 0 and 10 seconds
- pr = repo.get_pull(github_event.pull_request.number)
- logging.debug(
- f"Processing PR: {pr.number}, with anti-race condition sleep time: {sleep_time}"
+ logging.info(
+ f"Sleeping for {sleep_time} seconds to avoid "
+ "race conditions and multiple comments"
)
- if pr.state == "open":
- logging.debug(f"PR is open: {pr.number}")
- label_strs = {label.name for label in pr.get_labels()}
- if lang_all_label in label_strs and awaiting_label in label_strs:
+ time.sleep(sleep_time)
+
+ # Get PR
+ logging.debug(f"Processing PR: #{github_event.pull_request.number}")
+ pr = repo.get_pull(github_event.pull_request.number)
+ label_strs = {label.name for label in pr.get_labels()}
+ langs = []
+ for label in label_strs:
+ if label.startswith("lang-") and not label == lang_all_label:
+ langs.append(label[5:])
+ logging.info(f"PR #{pr.number} has labels: {label_strs}")
+ if not langs or lang_all_label not in label_strs:
+ logging.info(f"PR #{pr.number} doesn't seem to be a translation PR, skipping")
+ sys.exit(0)
+
+ # Generate translation map, lang ID to discussion
+ discussions = get_graphql_translation_discussions(settings=settings)
+ lang_to_discussion_map: Dict[str, AllDiscussionsDiscussionNode] = {}
+ for discussion in discussions:
+ for edge in discussion.labels.edges:
+ label = edge.node.name
+ if label.startswith("lang-") and not label == lang_all_label:
+ lang = label[5:]
+ lang_to_discussion_map[lang] = discussion
+ logging.debug(f"Using translations map: {lang_to_discussion_map}")
+
+ # Messages to create or check
+ new_translation_message = f"Good news everyone! 😉 There's a new translation PR to be reviewed: #{pr.number} by @{pr.user.login}. 🎉 This requires 2 approvals from native speakers to be merged. 🤓"
+ done_translation_message = f"~There's a new translation PR to be reviewed: #{pr.number} by @{pr.user.login}~ Good job! This is done. 🍰☕"
+
+ # Normally only one language, but still
+ for lang in langs:
+ if lang not in lang_to_discussion_map:
+ log_message = f"Could not find discussion for language: {lang}"
+ logging.error(log_message)
+ raise RuntimeError(log_message)
+ discussion = lang_to_discussion_map[lang]
+ logging.info(
+ f"Found a translation discussion for language: {lang} in discussion: #{discussion.number}"
+ )
+
+ already_notified_comment: Union[Comment, None] = None
+ already_done_comment: Union[Comment, None] = None
+
+ logging.info(
+ f"Checking current comments in discussion: #{discussion.number} to see if already notified about this PR: #{pr.number}"
+ )
+ comments = get_graphql_translation_discussion_comments(
+ settings=settings, discussion_number=discussion.number
+ )
+ for comment in comments:
+ if new_translation_message in comment.body:
+ already_notified_comment = comment
+ elif done_translation_message in comment.body:
+ already_done_comment = comment
+ logging.info(
+ f"Already notified comment: {already_notified_comment}, already done comment: {already_done_comment}"
+ )
+
+ if pr.state == "open" and awaiting_label in label_strs:
logging.info(
- f"This PR seems to be a language translation and awaiting reviews: {pr.number}"
+ f"This PR seems to be a language translation and awaiting reviews: #{pr.number}"
)
- if approved_label in label_strs:
- message = (
- f"It seems this PR already has the approved label: {pr.number}"
+ if already_notified_comment:
+ logging.info(
+ f"This PR #{pr.number} was already notified in comment: {already_notified_comment.url}"
)
- logging.error(message)
- raise RuntimeError(message)
- langs = []
- for label in label_strs:
- if label.startswith("lang-") and not label == lang_all_label:
- langs.append(label[5:])
- for lang in langs:
- if lang in translations_map:
- num = translations_map[lang]
- logging.info(
- f"Found a translation issue for language: {lang} in issue: {num}"
- )
- issue = repo.get_issue(num)
- message = f"Good news everyone! 😉 There's a new translation PR to be reviewed: #{pr.number} 🎉"
- already_notified = False
- time.sleep(sleep_time)
- logging.info(
- f"Sleeping for {sleep_time} seconds to avoid race conditions and multiple comments"
- )
- logging.info(
- f"Checking current comments in issue: {num} to see if already notified about this PR: {pr.number}"
- )
- for comment in issue.get_comments():
- if message in comment.body:
- already_notified = True
- if not already_notified:
- logging.info(
- f"Writing comment in issue: {num} about PR: {pr.number}"
- )
- issue.create_comment(message)
- else:
- logging.info(
- f"Issue: {num} was already notified of PR: {pr.number}"
- )
- else:
- logging.info(
- f"Changing labels in a closed PR doesn't trigger comments, PR: {pr.number}"
- )
+ else:
+ logging.info(
+ f"Writing notification comment about PR #{pr.number} in Discussion: #{discussion.number}"
+ )
+ comment = create_comment(
+ settings=settings,
+ discussion_id=discussion.id,
+ body=new_translation_message,
+ )
+ logging.info(f"Notified in comment: {comment.url}")
+ elif pr.state == "closed" or approved_label in label_strs:
+ logging.info(f"Already approved or closed PR #{pr.number}")
+ if already_done_comment:
+ logging.info(
+ f"This PR #{pr.number} was already marked as done in comment: {already_done_comment.url}"
+ )
+ elif already_notified_comment:
+ updated_comment = update_comment(
+ settings=settings,
+ comment_id=already_notified_comment.id,
+ body=done_translation_message,
+ )
+ logging.info(f"Marked as done in comment: {updated_comment.url}")
+ else:
+ logging.info(
+ f"There doesn't seem to be anything to be done about PR #{pr.number}"
+ )
logging.info("Finished")
diff --git a/.github/actions/notify-translations/app/translations.yml b/.github/actions/notify-translations/app/translations.yml
deleted file mode 100644
index 4338e1326..000000000
--- a/.github/actions/notify-translations/app/translations.yml
+++ /dev/null
@@ -1,21 +0,0 @@
-pt: 1211
-es: 1218
-zh: 1228
-ru: 1362
-it: 1556
-ja: 1572
-uk: 1748
-tr: 1892
-fr: 1972
-ko: 2017
-fa: 2041
-pl: 3169
-de: 3716
-id: 3717
-az: 3994
-nl: 4701
-uz: 4883
-sv: 5146
-he: 5157
-ta: 5434
-ar: 3349
diff --git a/.github/actions/people/app/main.py b/.github/actions/people/app/main.py
index 31756a5fc..2bf59f25e 100644
--- a/.github/actions/people/app/main.py
+++ b/.github/actions/people/app/main.py
@@ -4,7 +4,7 @@ import sys
from collections import Counter, defaultdict
from datetime import datetime, timedelta, timezone
from pathlib import Path
-from typing import Container, DefaultDict, Dict, List, Set, Union
+from typing import Any, Container, DefaultDict, Dict, List, Set, Union
import httpx
import yaml
@@ -12,6 +12,50 @@ from github import Github
from pydantic import BaseModel, BaseSettings, SecretStr
github_graphql_url = "https://api.github.com/graphql"
+questions_category_id = "MDE4OkRpc2N1c3Npb25DYXRlZ29yeTMyMDAxNDM0"
+
+discussions_query = """
+query Q($after: String, $category_id: ID) {
+ repository(name: "fastapi", owner: "tiangolo") {
+ discussions(first: 100, after: $after, categoryId: $category_id) {
+ edges {
+ cursor
+ node {
+ number
+ author {
+ login
+ avatarUrl
+ url
+ }
+ title
+ createdAt
+ comments(first: 100) {
+ nodes {
+ createdAt
+ author {
+ login
+ avatarUrl
+ url
+ }
+ isAnswer
+ replies(first: 10) {
+ nodes {
+ createdAt
+ author {
+ login
+ avatarUrl
+ url
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+"""
issues_query = """
query Q($after: String) {
@@ -131,15 +175,30 @@ class Author(BaseModel):
url: str
+# Issues and Discussions
+
+
class CommentsNode(BaseModel):
createdAt: datetime
author: Union[Author, None] = None
+class Replies(BaseModel):
+ nodes: List[CommentsNode]
+
+
+class DiscussionsCommentsNode(CommentsNode):
+ replies: Replies
+
+
class Comments(BaseModel):
nodes: List[CommentsNode]
+class DiscussionsComments(BaseModel):
+ nodes: List[DiscussionsCommentsNode]
+
+
class IssuesNode(BaseModel):
number: int
author: Union[Author, None] = None
@@ -149,27 +208,59 @@ class IssuesNode(BaseModel):
comments: Comments
+class DiscussionsNode(BaseModel):
+ number: int
+ author: Union[Author, None] = None
+ title: str
+ createdAt: datetime
+ comments: DiscussionsComments
+
+
class IssuesEdge(BaseModel):
cursor: str
node: IssuesNode
+class DiscussionsEdge(BaseModel):
+ cursor: str
+ node: DiscussionsNode
+
+
class Issues(BaseModel):
edges: List[IssuesEdge]
+class Discussions(BaseModel):
+ edges: List[DiscussionsEdge]
+
+
class IssuesRepository(BaseModel):
issues: Issues
+class DiscussionsRepository(BaseModel):
+ discussions: Discussions
+
+
class IssuesResponseData(BaseModel):
repository: IssuesRepository
+class DiscussionsResponseData(BaseModel):
+ repository: DiscussionsRepository
+
+
class IssuesResponse(BaseModel):
data: IssuesResponseData
+class DiscussionsResponse(BaseModel):
+ data: DiscussionsResponseData
+
+
+# PRs
+
+
class LabelNode(BaseModel):
name: str
@@ -219,6 +310,9 @@ class PRsResponse(BaseModel):
data: PRsResponseData
+# Sponsors
+
+
class SponsorEntity(BaseModel):
login: str
avatarUrl: str
@@ -264,10 +358,16 @@ class Settings(BaseSettings):
def get_graphql_response(
- *, settings: Settings, query: str, after: Union[str, None] = None
-):
+ *,
+ settings: Settings,
+ query: str,
+ after: Union[str, None] = None,
+ category_id: Union[str, None] = None,
+) -> Dict[str, Any]:
headers = {"Authorization": f"token {settings.input_token.get_secret_value()}"}
- variables = {"after": after}
+ # category_id is only used by one query, but GraphQL allows unused variables, so
+ # keep it here for simplicity
+ variables = {"after": after, "category_id": category_id}
response = httpx.post(
github_graphql_url,
headers=headers,
@@ -275,10 +375,16 @@ def get_graphql_response(
json={"query": query, "variables": variables, "operationName": "Q"},
)
if response.status_code != 200:
- logging.error(f"Response was not 200, after: {after}")
+ logging.error(
+ f"Response was not 200, after: {after}, category_id: {category_id}"
+ )
logging.error(response.text)
raise RuntimeError(response.text)
data = response.json()
+ if "errors" in data:
+ logging.error(f"Errors in response, after: {after}, category_id: {category_id}")
+ logging.error(response.text)
+ raise RuntimeError(response.text)
return data
@@ -288,6 +394,21 @@ def get_graphql_issue_edges(*, settings: Settings, after: Union[str, None] = Non
return graphql_response.data.repository.issues.edges
+def get_graphql_question_discussion_edges(
+ *,
+ settings: Settings,
+ after: Union[str, None] = None,
+):
+ data = get_graphql_response(
+ settings=settings,
+ query=discussions_query,
+ after=after,
+ category_id=questions_category_id,
+ )
+ graphql_response = DiscussionsResponse.parse_obj(data)
+ return graphql_response.data.repository.discussions.edges
+
+
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)
@@ -300,7 +421,7 @@ def get_graphql_sponsor_edges(*, settings: Settings, after: Union[str, None] = N
return graphql_response.data.user.sponsorshipsAsMaintainer.edges
-def get_experts(settings: Settings):
+def get_issues_experts(settings: Settings):
issue_nodes: List[IssuesNode] = []
issue_edges = get_graphql_issue_edges(settings=settings)
@@ -326,13 +447,78 @@ def get_experts(settings: Settings):
for comment in issue.comments.nodes:
if comment.author:
authors[comment.author.login] = comment.author
- if comment.author.login == issue_author_name:
- continue
- issue_commentors.add(comment.author.login)
+ if comment.author.login != issue_author_name:
+ issue_commentors.add(comment.author.login)
for author_name in issue_commentors:
commentors[author_name] += 1
if issue.createdAt > one_month_ago:
last_month_commentors[author_name] += 1
+
+ return commentors, last_month_commentors, authors
+
+
+def get_discussions_experts(settings: Settings):
+ discussion_nodes: List[DiscussionsNode] = []
+ discussion_edges = get_graphql_question_discussion_edges(settings=settings)
+
+ while discussion_edges:
+ for discussion_edge in discussion_edges:
+ discussion_nodes.append(discussion_edge.node)
+ last_edge = discussion_edges[-1]
+ discussion_edges = get_graphql_question_discussion_edges(
+ settings=settings, after=last_edge.cursor
+ )
+
+ commentors = Counter()
+ last_month_commentors = Counter()
+ authors: Dict[str, Author] = {}
+
+ now = datetime.now(tz=timezone.utc)
+ one_month_ago = now - timedelta(days=30)
+
+ for discussion in discussion_nodes:
+ discussion_author_name = None
+ if discussion.author:
+ authors[discussion.author.login] = discussion.author
+ discussion_author_name = discussion.author.login
+ discussion_commentors = set()
+ for comment in discussion.comments.nodes:
+ if comment.author:
+ authors[comment.author.login] = comment.author
+ if comment.author.login != discussion_author_name:
+ discussion_commentors.add(comment.author.login)
+ for reply in comment.replies.nodes:
+ if reply.author:
+ authors[reply.author.login] = reply.author
+ if reply.author.login != discussion_author_name:
+ discussion_commentors.add(reply.author.login)
+ for author_name in discussion_commentors:
+ commentors[author_name] += 1
+ if discussion.createdAt > one_month_ago:
+ last_month_commentors[author_name] += 1
+ return commentors, last_month_commentors, authors
+
+
+def get_experts(settings: Settings):
+ # Migrated to only use GitHub Discussions
+ # (
+ # issues_commentors,
+ # issues_last_month_commentors,
+ # issues_authors,
+ # ) = get_issues_experts(settings=settings)
+ (
+ discussions_commentors,
+ discussions_last_month_commentors,
+ discussions_authors,
+ ) = get_discussions_experts(settings=settings)
+ # commentors = issues_commentors + discussions_commentors
+ commentors = discussions_commentors
+ # last_month_commentors = (
+ # issues_last_month_commentors + discussions_last_month_commentors
+ # )
+ last_month_commentors = discussions_last_month_commentors
+ # authors = {**issues_authors, **discussions_authors}
+ authors = {**discussions_authors}
return commentors, last_month_commentors, authors
@@ -425,13 +611,13 @@ if __name__ == "__main__":
logging.info(f"Using config: {settings.json()}")
g = Github(settings.input_standard_token.get_secret_value())
repo = g.get_repo(settings.github_repository)
- issue_commentors, issue_last_month_commentors, issue_authors = get_experts(
+ question_commentors, question_last_month_commentors, question_authors = get_experts(
settings=settings
)
contributors, pr_commentors, reviewers, pr_authors = get_contributors(
settings=settings
)
- authors = {**issue_authors, **pr_authors}
+ authors = {**question_authors, **pr_authors}
maintainers_logins = {"tiangolo"}
bot_names = {"codecov", "github-actions", "pre-commit-ci", "dependabot"}
maintainers = []
@@ -440,7 +626,7 @@ if __name__ == "__main__":
maintainers.append(
{
"login": login,
- "answers": issue_commentors[login],
+ "answers": question_commentors[login],
"prs": contributors[login],
"avatarUrl": user.avatarUrl,
"url": user.url,
@@ -453,13 +639,13 @@ if __name__ == "__main__":
min_count_reviewer = 4
skip_users = maintainers_logins | bot_names
experts = get_top_users(
- counter=issue_commentors,
+ counter=question_commentors,
min_count=min_count_expert,
authors=authors,
skip_users=skip_users,
)
last_month_active = get_top_users(
- counter=issue_last_month_commentors,
+ counter=question_last_month_commentors,
min_count=min_count_last_month,
authors=authors,
skip_users=skip_users,
diff --git a/.github/workflows/build-docs.yml b/.github/workflows/build-docs.yml
index b9bd521b3..68a180e38 100644
--- a/.github/workflows/build-docs.yml
+++ b/.github/workflows/build-docs.yml
@@ -7,7 +7,7 @@ on:
types: [opened, synchronize]
jobs:
build-docs:
- runs-on: ubuntu-18.04
+ runs-on: ubuntu-latest
steps:
- name: Dump GitHub context
env:
@@ -17,7 +17,7 @@ jobs:
- name: Set up Python
uses: actions/setup-python@v4
with:
- python-version: "3.7"
+ python-version: "3.11"
- uses: actions/cache@v3
id: cache
with:
diff --git a/.github/workflows/notify-translations.yml b/.github/workflows/notify-translations.yml
index 2fcb7595e..fdd24414c 100644
--- a/.github/workflows/notify-translations.yml
+++ b/.github/workflows/notify-translations.yml
@@ -4,6 +4,7 @@ on:
pull_request_target:
types:
- labeled
+ - closed
jobs:
notify-translations:
diff --git a/.github/workflows/people.yml b/.github/workflows/people.yml
index 4b47b4072..cca1329e7 100644
--- a/.github/workflows/people.yml
+++ b/.github/workflows/people.yml
@@ -15,6 +15,9 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
+ # Ref: https://github.com/actions/runner/issues/2033
+ - name: Fix git safe.directory in container
+ run: mkdir -p /home/runner/work/_temp/_github_home && printf "[safe]\n\tdirectory = /github/workspace" > /home/runner/work/_temp/_github_home/.gitconfig
# 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 7d31a9c64..91b0cba02 100644
--- a/.github/workflows/preview-docs.yml
+++ b/.github/workflows/preview-docs.yml
@@ -16,7 +16,7 @@ jobs:
rm -rf ./site
mkdir ./site
- name: Download Artifact Docs
- uses: dawidd6/action-download-artifact@v2.24.2
+ uses: dawidd6/action-download-artifact@v2.27.0
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
workflow: build-docs.yml
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml
index 8ffb493a4..1ad11f8d2 100644
--- a/.github/workflows/publish.yml
+++ b/.github/workflows/publish.yml
@@ -18,7 +18,8 @@ jobs:
uses: actions/setup-python@v4
with:
python-version: "3.7"
- cache: "pip"
+ # Issue ref: https://github.com/actions/setup-python/issues/436
+ # cache: "pip"
cache-dependency-path: pyproject.toml
- uses: actions/cache@v3
id: cache
@@ -31,7 +32,7 @@ jobs:
- name: Build distribution
run: python -m build
- name: Publish
- uses: pypa/gh-action-pypi-publish@v1.5.2
+ uses: pypa/gh-action-pypi-publish@v1.8.5
with:
password: ${{ secrets.PYPI_API_TOKEN }}
- name: Dump GitHub context
diff --git a/.github/workflows/smokeshow.yml b/.github/workflows/smokeshow.yml
index 7559c24c0..f135fb3e4 100644
--- a/.github/workflows/smokeshow.yml
+++ b/.github/workflows/smokeshow.yml
@@ -20,7 +20,7 @@ jobs:
- run: pip install smokeshow
- - uses: dawidd6/action-download-artifact@v2.24.2
+ - uses: dawidd6/action-download-artifact@v2.27.0
with:
workflow: test.yml
commit: ${{ github.event.workflow_run.head_sha }}
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index ddc43c942..65b29be20 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -21,7 +21,8 @@ jobs:
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}
- cache: "pip"
+ # Issue ref: https://github.com/actions/setup-python/issues/436
+ # cache: "pip"
cache-dependency-path: pyproject.toml
- uses: actions/cache@v3
id: cache
@@ -54,7 +55,8 @@ jobs:
- uses: actions/setup-python@v4
with:
python-version: '3.8'
- cache: "pip"
+ # Issue ref: https://github.com/actions/setup-python/issues/436
+ # cache: "pip"
cache-dependency-path: pyproject.toml
- name: Get coverage files
@@ -75,3 +77,19 @@ jobs:
with:
name: coverage-html
path: htmlcov
+
+ # https://github.com/marketplace/actions/alls-green#why
+ check: # This job does nothing and is only used for the branch protection
+
+ if: always()
+
+ needs:
+ - coverage-combine
+
+ runs-on: ubuntu-latest
+
+ steps:
+ - name: Decide whether the needed jobs succeeded or failed
+ uses: re-actors/alls-green@release/v1
+ with:
+ jobs: ${{ toJSON(needs) }}
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 96f097caa..25e797d24 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -1,8 +1,10 @@
# See https://pre-commit.com for more information
# See https://pre-commit.com/hooks.html for more hooks
+default_language_version:
+ python: python3.10
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
- rev: v4.3.0
+ rev: v4.4.0
hooks:
- id: check-added-large-files
- id: check-toml
@@ -12,20 +14,20 @@ repos:
- id: end-of-file-fixer
- id: trailing-whitespace
- repo: https://github.com/asottile/pyupgrade
- rev: v3.2.2
+ rev: v3.3.1
hooks:
- id: pyupgrade
args:
- --py3-plus
- --keep-runtime-typing
- repo: https://github.com/charliermarsh/ruff-pre-commit
- rev: v0.0.138
+ rev: v0.0.254
hooks:
- id: ruff
args:
- --fix
- repo: https://github.com/pycqa/isort
- rev: 5.10.1
+ rev: 5.12.0
hooks:
- id: isort
name: isort (python)
@@ -36,7 +38,7 @@ repos:
name: isort (pyi)
types: [pyi]
- repo: https://github.com/psf/black
- rev: 22.10.0
+ rev: 23.1.0
hooks:
- id: black
ci:
diff --git a/README.md b/README.md
index 7c4a6c4b4..8baee7825 100644
--- a/README.md
+++ b/README.md
@@ -46,17 +46,15 @@ The key features are:
-
-
-
-
-
+
+
+
@@ -102,6 +100,12 @@ The key features are:
---
+"_If anyone is looking to build a production Python API, I would highly recommend **FastAPI**. It is **beautifully designed**, **simple to use** and **highly scalable**, it has become a **key component** in our API first development strategy and is driving many automations and services such as our Virtual TAC Engineer._"
+
+
+
+---
+
+**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.7+ 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 [...]_"
+
+
+
+---
+
+"_If anyone is looking to build a production Python API, I would highly recommend **FastAPI**. It is **beautifully designed**, **simple to use** and **highly scalable**, it has become a **key component** in our API first development strategy and is driving many automations and services such as our Virtual TAC Engineer._"
+
+
+
+---
+
+## **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.7+
+
+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):
+
+
+
+### Alternative API docs
+
+And now, go to http://127.0.0.1:8000/redoc.
+
+You will see the alternative automatic documentation (provided by ReDoc):
+
+
+
+## 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:
+
+
+
+* Click on the button "Try it out", it allows you to fill the parameters and directly interact with the API:
+
+
+
+* 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:
+
+
+
+### 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:
+
+
+
+### 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.7+**.
+
+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:
+
+
+
+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 HTTPX 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:
+
+* httpx - Required if you want to use the `TestClient`.
+* jinja2 - Required if you want to use the default template configuration.
+* python-multipart - Required if you want to support form "parsing", with `request.form()`.
+* itsdangerous - Required for `SessionMiddleware` support.
+* pyyaml - Required for Starlette's `SchemaGenerator` support (you probably don't need it with FastAPI).
+* ujson - Required if you want to use `UJSONResponse`.
+
+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/cs/mkdocs.yml b/docs/cs/mkdocs.yml
new file mode 100644
index 000000000..539d7d65d
--- /dev/null
+++ b/docs/cs/mkdocs.yml
@@ -0,0 +1,154 @@
+site_name: FastAPI
+site_description: FastAPI framework, high performance, easy to learn, fast to code, ready for production
+site_url: https://fastapi.tiangolo.com/cs/
+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: cs
+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/
+ - cs: /cs/
+ - de: /de/
+ - es: /es/
+ - fa: /fa/
+ - fr: /fr/
+ - he: /he/
+ - hy: /hy/
+ - id: /id/
+ - it: /it/
+ - ja: /ja/
+ - ko: /ko/
+ - nl: /nl/
+ - pl: /pl/
+ - pt: /pt/
+ - ru: /ru/
+ - sq: /sq/
+ - sv: /sv/
+ - ta: /ta/
+ - 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: G-YNEVN69SC3
+ 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: /cs/
+ name: cs
+ - 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: /hy/
+ name: hy
+ - 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: /ta/
+ name: ta - தமிழ்
+ - 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/cs/overrides/.gitignore b/docs/cs/overrides/.gitignore
new file mode 100644
index 000000000..e69de29bb
diff --git a/docs/de/mkdocs.yml b/docs/de/mkdocs.yml
index 8c3c42b5f..8ee11d46c 100644
--- a/docs/de/mkdocs.yml
+++ b/docs/de/mkdocs.yml
@@ -40,11 +40,14 @@ nav:
- Languages:
- en: /
- az: /az/
+ - cs: /cs/
- de: /de/
+ - em: /em/
- es: /es/
- fa: /fa/
- fr: /fr/
- he: /he/
+ - hy: /hy/
- id: /id/
- it: /it/
- ja: /ja/
@@ -55,6 +58,7 @@ nav:
- ru: /ru/
- sq: /sq/
- sv: /sv/
+ - ta: /ta/
- tr: /tr/
- uk: /uk/
- zh: /zh/
@@ -81,7 +85,7 @@ markdown_extensions:
extra:
analytics:
provider: google
- property: UA-133183413-1
+ property: G-YNEVN69SC3
social:
- icon: fontawesome/brands/github-alt
link: https://github.com/tiangolo/fastapi
@@ -102,8 +106,12 @@ extra:
name: en - English
- link: /az/
name: az
+ - link: /cs/
+ name: cs
- link: /de/
name: de
+ - link: /em/
+ name: 😉
- link: /es/
name: es - español
- link: /fa/
@@ -112,6 +120,8 @@ extra:
name: fr - français
- link: /he/
name: he
+ - link: /hy/
+ name: hy
- link: /id/
name: id
- link: /it/
@@ -132,6 +142,8 @@ extra:
name: sq - shqip
- link: /sv/
name: sv - svenska
+ - link: /ta/
+ name: ta - தமிழ்
- link: /tr/
name: tr - Türkçe
- link: /uk/
diff --git a/docs/em/docs/advanced/additional-responses.md b/docs/em/docs/advanced/additional-responses.md
new file mode 100644
index 000000000..26963c2e3
--- /dev/null
+++ b/docs/em/docs/advanced/additional-responses.md
@@ -0,0 +1,240 @@
+# 🌖 📨 🗄
+
+!!! warning
+ 👉 👍 🏧 ❔.
+
+ 🚥 👆 ▶️ ⏮️ **FastAPI**, 👆 💪 🚫 💪 👉.
+
+👆 💪 📣 🌖 📨, ⏮️ 🌖 👔 📟, 🔉 🆎, 📛, ♒️.
+
+👈 🌖 📨 🔜 🔌 🗄 🔗, 👫 🔜 😑 🛠️ 🩺.
+
+✋️ 👈 🌖 📨 👆 ✔️ ⚒ 💭 👆 📨 `Response` 💖 `JSONResponse` 🔗, ⏮️ 👆 👔 📟 & 🎚.
+
+## 🌖 📨 ⏮️ `model`
+
+👆 💪 🚶♀️ 👆 *➡ 🛠️ 👨🎨* 🔢 `responses`.
+
+⚫️ 📨 `dict`, 🔑 👔 📟 🔠 📨, 💖 `200`, & 💲 🎏 `dict`Ⓜ ⏮️ ℹ 🔠 👫.
+
+🔠 👈 📨 `dict`Ⓜ 💪 ✔️ 🔑 `model`, ⚗ Pydantic 🏷, 💖 `response_model`.
+
+**FastAPI** 🔜 ✊ 👈 🏷, 🏗 🚮 🎻 🔗 & 🔌 ⚫️ ☑ 🥉 🗄.
+
+🖼, 📣 ➕1️⃣ 📨 ⏮️ 👔 📟 `404` & Pydantic 🏷 `Message`, 👆 💪 ✍:
+
+```Python hl_lines="18 22"
+{!../../../docs_src/additional_responses/tutorial001.py!}
+```
+
+!!! note
+ ✔️ 🤯 👈 👆 ✔️ 📨 `JSONResponse` 🔗.
+
+!!! info
+ `model` 🔑 🚫 🍕 🗄.
+
+ **FastAPI** 🔜 ✊ Pydantic 🏷 ⚪️➡️ 📤, 🏗 `JSON Schema`, & 🚮 ⚫️ ☑ 🥉.
+
+ ☑ 🥉:
+
+ * 🔑 `content`, 👈 ✔️ 💲 ➕1️⃣ 🎻 🎚 (`dict`) 👈 🔌:
+ * 🔑 ⏮️ 📻 🆎, ✅ `application/json`, 👈 🔌 💲 ➕1️⃣ 🎻 🎚, 👈 🔌:
+ * 🔑 `schema`, 👈 ✔️ 💲 🎻 🔗 ⚪️➡️ 🏷, 📥 ☑ 🥉.
+ * **FastAPI** 🚮 🔗 📥 🌐 🎻 🔗 ➕1️⃣ 🥉 👆 🗄 ↩️ ✅ ⚫️ 🔗. 👉 🌌, 🎏 🈸 & 👩💻 💪 ⚙️ 👈 🎻 🔗 🔗, 🚚 👻 📟 ⚡ 🧰, ♒️.
+
+🏗 📨 🗄 👉 *➡ 🛠️* 🔜:
+
+```JSON hl_lines="3-12"
+{
+ "responses": {
+ "404": {
+ "description": "Additional Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Message"
+ }
+ }
+ }
+ },
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Item"
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ }
+}
+```
+
+🔗 🔗 ➕1️⃣ 🥉 🔘 🗄 🔗:
+
+```JSON hl_lines="4-16"
+{
+ "components": {
+ "schemas": {
+ "Message": {
+ "title": "Message",
+ "required": [
+ "message"
+ ],
+ "type": "object",
+ "properties": {
+ "message": {
+ "title": "Message",
+ "type": "string"
+ }
+ }
+ },
+ "Item": {
+ "title": "Item",
+ "required": [
+ "id",
+ "value"
+ ],
+ "type": "object",
+ "properties": {
+ "id": {
+ "title": "Id",
+ "type": "string"
+ },
+ "value": {
+ "title": "Value",
+ "type": "string"
+ }
+ }
+ },
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": [
+ "loc",
+ "msg",
+ "type"
+ ],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "msg": {
+ "title": "Message",
+ "type": "string"
+ },
+ "type": {
+ "title": "Error Type",
+ "type": "string"
+ }
+ }
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/ValidationError"
+ }
+ }
+ }
+ }
+ }
+ }
+}
+```
+
+## 🌖 🔉 🆎 👑 📨
+
+👆 💪 ⚙️ 👉 🎏 `responses` 🔢 🚮 🎏 🔉 🆎 🎏 👑 📨.
+
+🖼, 👆 💪 🚮 🌖 📻 🆎 `image/png`, 📣 👈 👆 *➡ 🛠️* 💪 📨 🎻 🎚 (⏮️ 📻 🆎 `application/json`) ⚖️ 🇩🇴 🖼:
+
+```Python hl_lines="19-24 28"
+{!../../../docs_src/additional_responses/tutorial002.py!}
+```
+
+!!! note
+ 👀 👈 👆 ✔️ 📨 🖼 ⚙️ `FileResponse` 🔗.
+
+!!! info
+ 🚥 👆 ✔ 🎏 📻 🆎 🎯 👆 `responses` 🔢, FastAPI 🔜 🤔 📨 ✔️ 🎏 📻 🆎 👑 📨 🎓 (🔢 `application/json`).
+
+ ✋️ 🚥 👆 ✔️ ✔ 🛃 📨 🎓 ⏮️ `None` 🚮 📻 🆎, FastAPI 🔜 ⚙️ `application/json` 🙆 🌖 📨 👈 ✔️ 👨💼 🏷.
+
+## 🌀 ℹ
+
+👆 💪 🌀 📨 ℹ ⚪️➡️ 💗 🥉, 🔌 `response_model`, `status_code`, & `responses` 🔢.
+
+👆 💪 📣 `response_model`, ⚙️ 🔢 👔 📟 `200` (⚖️ 🛃 1️⃣ 🚥 👆 💪), & ⤴️ 📣 🌖 ℹ 👈 🎏 📨 `responses`, 🔗 🗄 🔗.
+
+**FastAPI** 🔜 🚧 🌖 ℹ ⚪️➡️ `responses`, & 🌀 ⚫️ ⏮️ 🎻 🔗 ⚪️➡️ 👆 🏷.
+
+🖼, 👆 💪 📣 📨 ⏮️ 👔 📟 `404` 👈 ⚙️ Pydantic 🏷 & ✔️ 🛃 `description`.
+
+& 📨 ⏮️ 👔 📟 `200` 👈 ⚙️ 👆 `response_model`, ✋️ 🔌 🛃 `example`:
+
+```Python hl_lines="20-31"
+{!../../../docs_src/additional_responses/tutorial003.py!}
+```
+
+⚫️ 🔜 🌐 🌀 & 🔌 👆 🗄, & 🎦 🛠️ 🩺:
+
+
+
+## 🌀 🔢 📨 & 🛃 🕐
+
+👆 💪 💚 ✔️ 🔁 📨 👈 ✔ 📚 *➡ 🛠️*, ✋️ 👆 💚 🌀 👫 ⏮️ 🛃 📨 💚 🔠 *➡ 🛠️*.
+
+📚 💼, 👆 💪 ⚙️ 🐍 ⚒ "🏗" `dict` ⏮️ `**dict_to_unpack`:
+
+```Python
+old_dict = {
+ "old key": "old value",
+ "second old key": "second old value",
+}
+new_dict = {**old_dict, "new key": "new value"}
+```
+
+📥, `new_dict` 🔜 🔌 🌐 🔑-💲 👫 ⚪️➡️ `old_dict` ➕ 🆕 🔑-💲 👫:
+
+```Python
+{
+ "old key": "old value",
+ "second old key": "second old value",
+ "new key": "new value",
+}
+```
+
+👆 💪 ⚙️ 👈 ⚒ 🏤-⚙️ 🔢 📨 👆 *➡ 🛠️* & 🌀 👫 ⏮️ 🌖 🛃 🕐.
+
+🖼:
+
+```Python hl_lines="13-17 26"
+{!../../../docs_src/additional_responses/tutorial004.py!}
+```
+
+## 🌖 ℹ 🔃 🗄 📨
+
+👀 ⚫️❔ ⚫️❔ 👆 💪 🔌 📨, 👆 💪 ✅ 👉 📄 🗄 🔧:
+
+* 🗄 📨 🎚, ⚫️ 🔌 `Response Object`.
+* 🗄 📨 🎚, 👆 💪 🔌 🕳 ⚪️➡️ 👉 🔗 🔠 📨 🔘 👆 `responses` 🔢. ✅ `description`, `headers`, `content` (🔘 👉 👈 👆 📣 🎏 🔉 🆎 & 🎻 🔗), & `links`.
diff --git a/docs/em/docs/advanced/additional-status-codes.md b/docs/em/docs/advanced/additional-status-codes.md
new file mode 100644
index 000000000..392579df6
--- /dev/null
+++ b/docs/em/docs/advanced/additional-status-codes.md
@@ -0,0 +1,37 @@
+# 🌖 👔 📟
+
+🔢, **FastAPI** 🔜 📨 📨 ⚙️ `JSONResponse`, 🚮 🎚 👆 📨 ⚪️➡️ 👆 *➡ 🛠️* 🔘 👈 `JSONResponse`.
+
+⚫️ 🔜 ⚙️ 🔢 👔 📟 ⚖️ 1️⃣ 👆 ⚒ 👆 *➡ 🛠️*.
+
+## 🌖 👔 📟
+
+🚥 👆 💚 📨 🌖 👔 📟 ↖️ ⚪️➡️ 👑 1️⃣, 👆 💪 👈 🛬 `Response` 🔗, 💖 `JSONResponse`, & ⚒ 🌖 👔 📟 🔗.
+
+🖼, ➡️ 💬 👈 👆 💚 ✔️ *➡ 🛠️* 👈 ✔ ℹ 🏬, & 📨 🇺🇸🔍 👔 📟 2️⃣0️⃣0️⃣ "👌" 🕐❔ 🏆.
+
+✋️ 👆 💚 ⚫️ 🚫 🆕 🏬. & 🕐❔ 🏬 🚫 🔀 ⏭, ⚫️ ✍ 👫, & 📨 🇺🇸🔍 👔 📟 2️⃣0️⃣1️⃣ "✍".
+
+🏆 👈, 🗄 `JSONResponse`, & 📨 👆 🎚 📤 🔗, ⚒ `status_code` 👈 👆 💚:
+
+```Python hl_lines="4 25"
+{!../../../docs_src/additional_status_codes/tutorial001.py!}
+```
+
+!!! warning
+ 🕐❔ 👆 📨 `Response` 🔗, 💖 🖼 🔛, ⚫️ 🔜 📨 🔗.
+
+ ⚫️ 🏆 🚫 🎻 ⏮️ 🏷, ♒️.
+
+ ⚒ 💭 ⚫️ ✔️ 📊 👆 💚 ⚫️ ✔️, & 👈 💲 ☑ 🎻 (🚥 👆 ⚙️ `JSONResponse`).
+
+!!! note "📡 ℹ"
+ 👆 💪 ⚙️ `from starlette.responses import JSONResponse`.
+
+ **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. 🎏 ⏮️ `status`.
+
+## 🗄 & 🛠️ 🩺
+
+🚥 👆 📨 🌖 👔 📟 & 📨 🔗, 👫 🏆 🚫 🔌 🗄 🔗 (🛠️ 🩺), ↩️ FastAPI 🚫 ✔️ 🌌 💭 ⏪ ⚫️❔ 👆 🚶 📨.
+
+✋️ 👆 💪 📄 👈 👆 📟, ⚙️: [🌖 📨](additional-responses.md){.internal-link target=_blank}.
diff --git a/docs/em/docs/advanced/advanced-dependencies.md b/docs/em/docs/advanced/advanced-dependencies.md
new file mode 100644
index 000000000..fa1554734
--- /dev/null
+++ b/docs/em/docs/advanced/advanced-dependencies.md
@@ -0,0 +1,70 @@
+# 🏧 🔗
+
+## 🔗 🔗
+
+🌐 🔗 👥 ✔️ 👀 🔧 🔢 ⚖️ 🎓.
+
+✋️ 📤 💪 💼 🌐❔ 👆 💚 💪 ⚒ 🔢 🔛 🔗, 🍵 ✔️ 📣 📚 🎏 🔢 ⚖️ 🎓.
+
+➡️ 🌈 👈 👥 💚 ✔️ 🔗 👈 ✅ 🚥 🔢 🔢 `q` 🔌 🔧 🎚.
+
+✋️ 👥 💚 💪 🔗 👈 🔧 🎚.
+
+## "🇧🇲" 👐
+
+🐍 📤 🌌 ⚒ 👐 🎓 "🇧🇲".
+
+🚫 🎓 ⚫️ (❔ ⏪ 🇧🇲), ✋️ 👐 👈 🎓.
+
+👈, 👥 📣 👩🔬 `__call__`:
+
+```Python hl_lines="10"
+{!../../../docs_src/dependencies/tutorial011.py!}
+```
+
+👉 💼, 👉 `__call__` ⚫️❔ **FastAPI** 🔜 ⚙️ ✅ 🌖 🔢 & 🎧-🔗, & 👉 ⚫️❔ 🔜 🤙 🚶♀️ 💲 🔢 👆 *➡ 🛠️ 🔢* ⏪.
+
+## 🔗 👐
+
+& 🔜, 👥 💪 ⚙️ `__init__` 📣 🔢 👐 👈 👥 💪 ⚙️ "🔗" 🔗:
+
+```Python hl_lines="7"
+{!../../../docs_src/dependencies/tutorial011.py!}
+```
+
+👉 💼, **FastAPI** 🏆 🚫 ⏱ 👆 ⚖️ 💅 🔃 `__init__`, 👥 🔜 ⚙️ ⚫️ 🔗 👆 📟.
+
+## ✍ 👐
+
+👥 💪 ✍ 👐 👉 🎓 ⏮️:
+
+```Python hl_lines="16"
+{!../../../docs_src/dependencies/tutorial011.py!}
+```
+
+& 👈 🌌 👥 💪 "🔗" 👆 🔗, 👈 🔜 ✔️ `"bar"` 🔘 ⚫️, 🔢 `checker.fixed_content`.
+
+## ⚙️ 👐 🔗
+
+⤴️, 👥 💪 ⚙️ 👉 `checker` `Depends(checker)`, ↩️ `Depends(FixedContentQueryChecker)`, ↩️ 🔗 👐, `checker`, 🚫 🎓 ⚫️.
+
+& 🕐❔ ❎ 🔗, **FastAPI** 🔜 🤙 👉 `checker` 💖:
+
+```Python
+checker(q="somequery")
+```
+
+...& 🚶♀️ ⚫️❔ 👈 📨 💲 🔗 👆 *➡ 🛠️ 🔢* 🔢 `fixed_content_included`:
+
+```Python hl_lines="20"
+{!../../../docs_src/dependencies/tutorial011.py!}
+```
+
+!!! tip
+ 🌐 👉 💪 😑 🎭. & ⚫️ 💪 🚫 📶 🆑 ❔ ⚫️ ⚠.
+
+ 👫 🖼 😫 🙅, ✋️ 🎦 ❔ ⚫️ 🌐 👷.
+
+ 📃 🔃 💂♂, 📤 🚙 🔢 👈 🛠️ 👉 🎏 🌌.
+
+ 🚥 👆 🤔 🌐 👉, 👆 ⏪ 💭 ❔ 👈 🚙 🧰 💂♂ 👷 🔘.
diff --git a/docs/em/docs/advanced/async-sql-databases.md b/docs/em/docs/advanced/async-sql-databases.md
new file mode 100644
index 000000000..848936de1
--- /dev/null
+++ b/docs/em/docs/advanced/async-sql-databases.md
@@ -0,0 +1,162 @@
+# 🔁 🗄 (🔗) 💽
+
+👆 💪 ⚙️ `encode/databases` ⏮️ **FastAPI** 🔗 💽 ⚙️ `async` & `await`.
+
+⚫️ 🔗 ⏮️:
+
+* ✳
+* ✳
+* 🗄
+
+👉 🖼, 👥 🔜 ⚙️ **🗄**, ↩️ ⚫️ ⚙️ 👁 📁 & 🐍 ✔️ 🛠️ 🐕🦺. , 👆 💪 📁 👉 🖼 & 🏃 ⚫️.
+
+⏪, 👆 🏭 🈸, 👆 💪 💚 ⚙️ 💽 💽 💖 **✳**.
+
+!!! tip
+ 👆 💪 🛠️ 💭 ⚪️➡️ 📄 🔃 🇸🇲 🐜 ([🗄 (🔗) 💽](../tutorial/sql-databases.md){.internal-link target=_blank}), 💖 ⚙️ 🚙 🔢 🎭 🛠️ 💽, 🔬 👆 **FastAPI** 📟.
+
+ 👉 📄 🚫 ✔ 📚 💭, 🌓 😑 💃.
+
+## 🗄 & ⚒ 🆙 `SQLAlchemy`
+
+* 🗄 `SQLAlchemy`.
+* ✍ `metadata` 🎚.
+* ✍ 🏓 `notes` ⚙️ `metadata` 🎚.
+
+```Python hl_lines="4 14 16-22"
+{!../../../docs_src/async_sql_databases/tutorial001.py!}
+```
+
+!!! tip
+ 👀 👈 🌐 👉 📟 😁 🇸🇲 🐚.
+
+ `databases` 🚫 🔨 🕳 📥.
+
+## 🗄 & ⚒ 🆙 `databases`
+
+* 🗄 `databases`.
+* ✍ `DATABASE_URL`.
+* ✍ `database` 🎚.
+
+```Python hl_lines="3 9 12"
+{!../../../docs_src/async_sql_databases/tutorial001.py!}
+```
+
+!!! tip
+ 🚥 👆 🔗 🎏 💽 (✅ ✳), 👆 🔜 💪 🔀 `DATABASE_URL`.
+
+## ✍ 🏓
+
+👉 💼, 👥 🏗 🏓 🎏 🐍 📁, ✋️ 🏭, 👆 🔜 🎲 💚 ✍ 👫 ⏮️ ⚗, 🛠️ ⏮️ 🛠️, ♒️.
+
+📥, 👉 📄 🔜 🏃 🔗, ▶️️ ⏭ ▶️ 👆 **FastAPI** 🈸.
+
+* ✍ `engine`.
+* ✍ 🌐 🏓 ⚪️➡️ `metadata` 🎚.
+
+```Python hl_lines="25-28"
+{!../../../docs_src/async_sql_databases/tutorial001.py!}
+```
+
+## ✍ 🏷
+
+✍ Pydantic 🏷:
+
+* 🗒 ✍ (`NoteIn`).
+* 🗒 📨 (`Note`).
+
+```Python hl_lines="31-33 36-39"
+{!../../../docs_src/async_sql_databases/tutorial001.py!}
+```
+
+🏗 👫 Pydantic 🏷, 🔢 💽 🔜 ✔, 🎻 (🗜), & ✍ (📄).
+
+, 👆 🔜 💪 👀 ⚫️ 🌐 🎓 🛠️ 🩺.
+
+## 🔗 & 🔌
+
+* ✍ 👆 `FastAPI` 🈸.
+* ✍ 🎉 🐕🦺 🔗 & 🔌 ⚪️➡️ 💽.
+
+```Python hl_lines="42 45-47 50-52"
+{!../../../docs_src/async_sql_databases/tutorial001.py!}
+```
+
+## ✍ 🗒
+
+✍ *➡ 🛠️ 🔢* ✍ 🗒:
+
+```Python hl_lines="55-58"
+{!../../../docs_src/async_sql_databases/tutorial001.py!}
+```
+
+!!! Note
+ 👀 👈 👥 🔗 ⏮️ 💽 ⚙️ `await`, *➡ 🛠️ 🔢* 📣 ⏮️ `async`.
+
+### 👀 `response_model=List[Note]`
+
+⚫️ ⚙️ `typing.List`.
+
+👈 📄 (& ✔, 🎻, ⛽) 🔢 💽, `list` `Note`Ⓜ.
+
+## ✍ 🗒
+
+✍ *➡ 🛠️ 🔢* ✍ 🗒:
+
+```Python hl_lines="61-65"
+{!../../../docs_src/async_sql_databases/tutorial001.py!}
+```
+
+!!! Note
+ 👀 👈 👥 🔗 ⏮️ 💽 ⚙️ `await`, *➡ 🛠️ 🔢* 📣 ⏮️ `async`.
+
+### 🔃 `{**note.dict(), "id": last_record_id}`
+
+`note` Pydantic `Note` 🎚.
+
+`note.dict()` 📨 `dict` ⏮️ 🚮 💽, 🕳 💖:
+
+```Python
+{
+ "text": "Some note",
+ "completed": False,
+}
+```
+
+✋️ ⚫️ 🚫 ✔️ `id` 🏑.
+
+👥 ✍ 🆕 `dict`, 👈 🔌 🔑-💲 👫 ⚪️➡️ `note.dict()` ⏮️:
+
+```Python
+{**note.dict()}
+```
+
+`**note.dict()` "unpacks" the key value pairs directly, so, `{**note.dict()}` would be, more or less, a copy of `note.dict()`.
+
+& ⤴️, 👥 ↔ 👈 📁 `dict`, ❎ ➕1️⃣ 🔑-💲 👫: `"id": last_record_id`:
+
+```Python
+{**note.dict(), "id": last_record_id}
+```
+
+, 🏁 🏁 📨 🔜 🕳 💖:
+
+```Python
+{
+ "id": 1,
+ "text": "Some note",
+ "completed": False,
+}
+```
+
+## ✅ ⚫️
+
+👆 💪 📁 👉 📟, & 👀 🩺 http://127.0.0.1:8000/docs.
+
+📤 👆 💪 👀 🌐 👆 🛠️ 📄 & 🔗 ⏮️ ⚫️:
+
+
+
+## 🌅 ℹ
+
+👆 💪 ✍ 🌅 🔃 `encode/databases` 🚮 📂 📃.
diff --git a/docs/em/docs/advanced/async-tests.md b/docs/em/docs/advanced/async-tests.md
new file mode 100644
index 000000000..df94c6ce7
--- /dev/null
+++ b/docs/em/docs/advanced/async-tests.md
@@ -0,0 +1,92 @@
+# 🔁 💯
+
+👆 ✔️ ⏪ 👀 ❔ 💯 👆 **FastAPI** 🈸 ⚙️ 🚚 `TestClient`. 🆙 🔜, 👆 ✔️ 🕴 👀 ❔ ✍ 🔁 💯, 🍵 ⚙️ `async` 🔢.
+
+➖ 💪 ⚙️ 🔁 🔢 👆 💯 💪 ⚠, 🖼, 🕐❔ 👆 🔬 👆 💽 🔁. 🌈 👆 💚 💯 📨 📨 👆 FastAPI 🈸 & ⤴️ ✔ 👈 👆 👩💻 ⏪ ✍ ☑ 💽 💽, ⏪ ⚙️ 🔁 💽 🗃.
+
+➡️ 👀 ❔ 👥 💪 ⚒ 👈 👷.
+
+## pytest.mark.anyio
+
+🚥 👥 💚 🤙 🔁 🔢 👆 💯, 👆 💯 🔢 ✔️ 🔁. AnyIO 🚚 👌 📁 👉, 👈 ✔ 👥 ✔ 👈 💯 🔢 🤙 🔁.
+
+## 🇸🇲
+
+🚥 👆 **FastAPI** 🈸 ⚙️ 😐 `def` 🔢 ↩️ `async def`, ⚫️ `async` 🈸 🔘.
+
+`TestClient` 🔨 🎱 🔘 🤙 🔁 FastAPI 🈸 👆 😐 `def` 💯 🔢, ⚙️ 🐩 ✳. ✋️ 👈 🎱 🚫 👷 🚫🔜 🕐❔ 👥 ⚙️ ⚫️ 🔘 🔁 🔢. 🏃 👆 💯 🔁, 👥 💪 🙅♂ 📏 ⚙️ `TestClient` 🔘 👆 💯 🔢.
+
+`TestClient` ⚓️ 🔛 🇸🇲, & ↩️, 👥 💪 ⚙️ ⚫️ 🔗 💯 🛠️.
+
+## 🖼
+
+🙅 🖼, ➡️ 🤔 📁 📊 🎏 1️⃣ 🔬 [🦏 🈸](../tutorial/bigger-applications.md){.internal-link target=_blank} & [🔬](../tutorial/testing.md){.internal-link target=_blank}:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+│ └── test_main.py
+```
+
+📁 `main.py` 🔜 ✔️:
+
+```Python
+{!../../../docs_src/async_tests/main.py!}
+```
+
+📁 `test_main.py` 🔜 ✔️ 💯 `main.py`, ⚫️ 💪 👀 💖 👉 🔜:
+
+```Python
+{!../../../docs_src/async_tests/test_main.py!}
+```
+
+## 🏃 ⚫️
+
+👆 💪 🏃 👆 💯 🐌 📨:
+
+
+
+ ```console
+ // You could create an env var MY_NAME with
+ $ export MY_NAME="Wade Wilson"
+
+ // Then you could use it with other programs, like
+ $ echo "Hello $MY_NAME"
+
+ Hello Wade Wilson
+ ```
+
+
+
+=== "🚪 📋"
+
+
+
+ ```console
+ // Create an env var MY_NAME
+ $ $Env:MY_NAME = "Wade Wilson"
+
+ // Use it with other programs, like
+ $ echo "Hello $Env:MY_NAME"
+
+ Hello Wade Wilson
+ ```
+
+
+
+```console
+// Here we don't set the env var yet
+$ python main.py
+
+// As we didn't set the env var, we get the default value
+
+Hello World from Python
+
+// But if we create an environment variable first
+$ export MY_NAME="Wade Wilson"
+
+// And then call the program again
+$ python main.py
+
+// Now it can read the environment variable
+
+Hello Wade Wilson from Python
+```
+
+
+
+```console
+// Create an env var MY_NAME in line for this program call
+$ MY_NAME="Wade Wilson" python main.py
+
+// Now it can read the environment variable
+
+Hello Wade Wilson from Python
+
+// The env var no longer exists afterwards
+$ python main.py
+
+Hello World from Python
+```
+
+
+
+```console
+$ typer --install-completion
+
+zsh completion installed in /home/user/.bashrc.
+Completion will take effect once you restart the terminal.
+```
+
+
+
+### 📱 & 🩺 🎏 🕰
+
+🚥 👆 🏃 🖼 ⏮️, ✅:
+
+
+
+```console
+$ uvicorn tutorial001:app --reload
+
+INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
+```
+
+
+
+```console
+// Use the command "live" and pass the language code as a CLI argument
+$ python ./scripts/docs.py live es
+
+[INFO] Serving on http://127.0.0.1:8008
+[INFO] Start watching changes
+[INFO] Start detecting changes
+```
+
+
+
+```console
+// Use the command new-lang, pass the language code as a CLI argument
+$ python ./scripts/docs.py new-lang ht
+
+Successfully initialized: docs/ht
+Updating ht
+Updating en
+```
+
+
+
+```console
+// Use the command "build-all", this will take a bit
+$ python ./scripts/docs.py build-all
+
+Updating es
+Updating en
+Building docs for: en
+Building docs for: es
+Successfully built docs for: es
+Copying en index.md to README.md
+```
+
+
+
+```console
+// Use the command "serve" after running "build-all"
+$ python ./scripts/docs.py serve
+
+Warning: this is a very simple server. For development, use mkdocs serve instead.
+This is here only to preview a site with translations already built.
+Make sure you run the build-all command first.
+Serving at: http://127.0.0.1:8008
+```
+
+
+
+```console
+$ uvicorn main:app --host 0.0.0.0 --port 8080 --workers 4
+INFO: Uvicorn running on http://0.0.0.0:8080 (Press CTRL+C to quit)
+INFO: Started parent process [27365]
+INFO: Started server process [27368]
+INFO: Waiting for application startup.
+INFO: Application startup complete.
+INFO: Started server process [27369]
+INFO: Waiting for application startup.
+INFO: Application startup complete.
+INFO: Started server process [27370]
+INFO: Waiting for application startup.
+INFO: Application startup complete.
+INFO: Started server process [27367]
+INFO: Waiting for application startup.
+INFO: Application startup complete.
+```
+
+
+
+```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.
+```
+
+
+
+```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.
+```
+
+
+
+```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.
+```
+
+
diff --git a/docs/em/mkdocs.yml b/docs/em/mkdocs.yml
new file mode 100644
index 000000000..df21a1093
--- /dev/null
+++ b/docs/em/mkdocs.yml
@@ -0,0 +1,261 @@
+site_name: FastAPI
+site_description: FastAPI framework, high performance, easy to learn, fast to code, ready for production
+site_url: https://fastapi.tiangolo.com/em/
+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: en
+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/
+ - em: /em/
+ - es: /es/
+ - fa: /fa/
+ - fr: /fr/
+ - he: /he/
+ - hy: /hy/
+ - id: /id/
+ - it: /it/
+ - ja: /ja/
+ - ko: /ko/
+ - nl: /nl/
+ - pl: /pl/
+ - pt: /pt/
+ - ru: /ru/
+ - sq: /sq/
+ - sv: /sv/
+ - ta: /ta/
+ - tr: /tr/
+ - uk: /uk/
+ - zh: /zh/
+- features.md
+- fastapi-people.md
+- python-types.md
+- 🔰 - 👩💻 🦮:
+ - tutorial/index.md
+ - tutorial/first-steps.md
+ - tutorial/path-params.md
+ - tutorial/query-params.md
+ - tutorial/body.md
+ - tutorial/query-params-str-validations.md
+ - tutorial/path-params-numeric-validations.md
+ - tutorial/body-multiple-params.md
+ - tutorial/body-fields.md
+ - tutorial/body-nested-models.md
+ - tutorial/schema-extra-example.md
+ - tutorial/extra-data-types.md
+ - tutorial/cookie-params.md
+ - tutorial/header-params.md
+ - tutorial/response-model.md
+ - tutorial/extra-models.md
+ - tutorial/response-status-code.md
+ - tutorial/request-forms.md
+ - tutorial/request-files.md
+ - tutorial/request-forms-and-files.md
+ - tutorial/handling-errors.md
+ - tutorial/path-operation-configuration.md
+ - tutorial/encoder.md
+ - tutorial/body-updates.md
+ - 🔗:
+ - tutorial/dependencies/index.md
+ - tutorial/dependencies/classes-as-dependencies.md
+ - tutorial/dependencies/sub-dependencies.md
+ - tutorial/dependencies/dependencies-in-path-operation-decorators.md
+ - tutorial/dependencies/global-dependencies.md
+ - tutorial/dependencies/dependencies-with-yield.md
+ - 💂♂:
+ - tutorial/security/index.md
+ - tutorial/security/first-steps.md
+ - tutorial/security/get-current-user.md
+ - tutorial/security/simple-oauth2.md
+ - tutorial/security/oauth2-jwt.md
+ - tutorial/middleware.md
+ - tutorial/cors.md
+ - tutorial/sql-databases.md
+ - tutorial/bigger-applications.md
+ - tutorial/background-tasks.md
+ - tutorial/metadata.md
+ - tutorial/static-files.md
+ - tutorial/testing.md
+ - tutorial/debugging.md
+- 🏧 👩💻 🦮:
+ - advanced/index.md
+ - advanced/path-operation-advanced-configuration.md
+ - advanced/additional-status-codes.md
+ - advanced/response-directly.md
+ - advanced/custom-response.md
+ - advanced/additional-responses.md
+ - advanced/response-cookies.md
+ - advanced/response-headers.md
+ - advanced/response-change-status-code.md
+ - advanced/advanced-dependencies.md
+ - 🏧 💂♂:
+ - advanced/security/index.md
+ - advanced/security/oauth2-scopes.md
+ - advanced/security/http-basic-auth.md
+ - advanced/using-request-directly.md
+ - advanced/dataclasses.md
+ - advanced/middleware.md
+ - advanced/sql-databases-peewee.md
+ - advanced/async-sql-databases.md
+ - advanced/nosql-databases.md
+ - advanced/sub-applications.md
+ - advanced/behind-a-proxy.md
+ - advanced/templates.md
+ - advanced/graphql.md
+ - advanced/websockets.md
+ - advanced/events.md
+ - advanced/custom-request-and-route.md
+ - advanced/testing-websockets.md
+ - advanced/testing-events.md
+ - advanced/testing-dependencies.md
+ - advanced/testing-database.md
+ - advanced/async-tests.md
+ - advanced/settings.md
+ - advanced/conditional-openapi.md
+ - advanced/extending-openapi.md
+ - advanced/openapi-callbacks.md
+ - advanced/wsgi.md
+ - advanced/generate-clients.md
+- async.md
+- 🛠️:
+ - deployment/index.md
+ - deployment/versions.md
+ - deployment/https.md
+ - deployment/manually.md
+ - deployment/concepts.md
+ - deployment/deta.md
+ - deployment/server-workers.md
+ - deployment/docker.md
+- project-generation.md
+- alternatives.md
+- history-design-future.md
+- external-links.md
+- benchmarks.md
+- help-fastapi.md
+- contributing.md
+- release-notes.md
+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: G-YNEVN69SC3
+ 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: /em/
+ name: 😉
+ - link: /es/
+ name: es - español
+ - link: /fa/
+ name: fa
+ - link: /fr/
+ name: fr - français
+ - link: /he/
+ name: he
+ - link: /hy/
+ name: hy
+ - 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: /ta/
+ name: ta - தமிழ்
+ - 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/em/overrides/.gitignore b/docs/em/overrides/.gitignore
new file mode 100644
index 000000000..e69de29bb
diff --git a/docs/en/data/external_links.yml b/docs/en/data/external_links.yml
index 934c5842b..af5810778 100644
--- a/docs/en/data/external_links.yml
+++ b/docs/en/data/external_links.yml
@@ -1,5 +1,13 @@
articles:
english:
+ - author: Raf Rasenberg
+ author_link: https://rafrasenberg.com/about/
+ link: https://rafrasenberg.com/fastapi-lambda/
+ title: 'FastAPI lambda container: serverless simplified'
+ - author: Teresa N. Fontanella De Santis
+ author_link: https://dev.to/
+ link: https://dev.to/teresafds/authorization-on-fastapi-with-casbin-41og
+ title: Authorization on FastAPI with Casbin
- author: WayScript
author_link: https://www.wayscript.com
link: https://blog.wayscript.com/fast-api-quickstart/
@@ -300,6 +308,11 @@ articles:
author_link: https://fullstackstation.com/author/figonking/
link: https://fullstackstation.com/fastapi-trien-khai-bang-docker/
title: 'FASTAPI: TRIỂN KHAI BẰNG DOCKER'
+ taiwanese:
+ - author: Leon
+ author_link: http://editor.leonh.space/
+ link: https://editor.leonh.space/2022/tortoise/
+ title: 'Tortoise ORM / FastAPI 整合快速筆記'
podcasts:
english:
- author: Podcast.`__init__`
diff --git a/docs/en/data/github_sponsors.yml b/docs/en/data/github_sponsors.yml
index 1953df801..2a8573f19 100644
--- a/docs/en/data/github_sponsors.yml
+++ b/docs/en/data/github_sponsors.yml
@@ -2,15 +2,12 @@ sponsors:
- - login: jina-ai
avatarUrl: https://avatars.githubusercontent.com/u/60539444?v=4
url: https://github.com/jina-ai
-- - login: Doist
- avatarUrl: https://avatars.githubusercontent.com/u/2565372?v=4
- url: https://github.com/Doist
- - login: cryptapi
+- - login: armand-sauzay
+ avatarUrl: https://avatars.githubusercontent.com/u/35524799?u=56e3e944bfe62770d1709c09552d2efc6d285ca6&v=4
+ url: https://github.com/armand-sauzay
+- - login: cryptapi
avatarUrl: https://avatars.githubusercontent.com/u/44925437?u=61369138589bc7fee6c417f3fbd50fbd38286cc4&v=4
url: https://github.com/cryptapi
- - login: jrobbins-LiveData
- avatarUrl: https://avatars.githubusercontent.com/u/79278744?u=bae8175fc3f09db281aca1f97a9ddc1a914a8c4f&v=4
- url: https://github.com/jrobbins-LiveData
- - login: nihpo
avatarUrl: https://avatars.githubusercontent.com/u/1841030?u=0264956d7580f7e46687a762a7baa629f84cf97c&v=4
url: https://github.com/nihpo
@@ -32,6 +29,9 @@ sponsors:
- login: investsuite
avatarUrl: https://avatars.githubusercontent.com/u/73833632?v=4
url: https://github.com/investsuite
+ - login: svix
+ avatarUrl: https://avatars.githubusercontent.com/u/80175132?v=4
+ url: https://github.com/svix
- login: VincentParedes
avatarUrl: https://avatars.githubusercontent.com/u/103889729?v=4
url: https://github.com/VincentParedes
@@ -44,36 +44,24 @@ sponsors:
- - login: vyos
avatarUrl: https://avatars.githubusercontent.com/u/5647000?v=4
url: https://github.com/vyos
- - login: SendCloud
- avatarUrl: https://avatars.githubusercontent.com/u/7831959?v=4
- url: https://github.com/SendCloud
- - login: matallan
- avatarUrl: https://avatars.githubusercontent.com/u/12107723?v=4
- url: https://github.com/matallan
- login: takashi-yoneya
avatarUrl: https://avatars.githubusercontent.com/u/33813153?u=2d0522bceba0b8b69adf1f2db866503bd96f944e&v=4
url: https://github.com/takashi-yoneya
- - login: mercedes-benz
- avatarUrl: https://avatars.githubusercontent.com/u/34240465?v=4
- url: https://github.com/mercedes-benz
- login: xoflare
avatarUrl: https://avatars.githubusercontent.com/u/74335107?v=4
url: https://github.com/xoflare
- - login: Striveworks
- avatarUrl: https://avatars.githubusercontent.com/u/45523576?v=4
- url: https://github.com/Striveworks
- login: BoostryJP
avatarUrl: https://avatars.githubusercontent.com/u/57932412?v=4
url: https://github.com/BoostryJP
- - login: johnadjei
avatarUrl: https://avatars.githubusercontent.com/u/767860?v=4
url: https://github.com/johnadjei
- - login: gvisniuc
- avatarUrl: https://avatars.githubusercontent.com/u/1614747?u=502dfdb2b087ddcf5460026297c98c7907bc2795&v=4
- url: https://github.com/gvisniuc
- login: HiredScore
avatarUrl: https://avatars.githubusercontent.com/u/3908850?v=4
url: https://github.com/HiredScore
+ - login: ianshan0915
+ avatarUrl: https://avatars.githubusercontent.com/u/5893101?u=a178d247d882578b1d1ef214b2494e52eb28634c&v=4
+ url: https://github.com/ianshan0915
- login: Trivie
avatarUrl: https://avatars.githubusercontent.com/u/8161763?v=4
url: https://github.com/Trivie
@@ -83,6 +71,9 @@ sponsors:
- - login: moellenbeck
avatarUrl: https://avatars.githubusercontent.com/u/169372?v=4
url: https://github.com/moellenbeck
+ - login: birkjernstrom
+ avatarUrl: https://avatars.githubusercontent.com/u/281715?u=4be14b43f76b4bd497b1941309bb390250b405e6&v=4
+ url: https://github.com/birkjernstrom
- login: AccentDesign
avatarUrl: https://avatars.githubusercontent.com/u/2429332?v=4
url: https://github.com/AccentDesign
@@ -110,9 +101,6 @@ sponsors:
- - login: indeedeng
avatarUrl: https://avatars.githubusercontent.com/u/2905043?v=4
url: https://github.com/indeedeng
- - login: A-Edge
- avatarUrl: https://avatars.githubusercontent.com/u/59514131?v=4
- url: https://github.com/A-Edge
- - login: Kludex
avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4
url: https://github.com/Kludex
@@ -134,9 +122,6 @@ sponsors:
- login: pamelafox
avatarUrl: https://avatars.githubusercontent.com/u/297042?v=4
url: https://github.com/pamelafox
- - login: deserat
- avatarUrl: https://avatars.githubusercontent.com/u/299332?v=4
- url: https://github.com/deserat
- login: ericof
avatarUrl: https://avatars.githubusercontent.com/u/306014?u=cf7c8733620397e6584a451505581c01c5d842d7&v=4
url: https://github.com/ericof
@@ -152,30 +137,24 @@ sponsors:
- login: jqueguiner
avatarUrl: https://avatars.githubusercontent.com/u/690878?u=bd65cc1f228ce6455e56dfaca3ef47c33bc7c3b0&v=4
url: https://github.com/jqueguiner
- - login: alexsantos
- avatarUrl: https://avatars.githubusercontent.com/u/932219?v=4
- url: https://github.com/alexsantos
+ - login: iobruno
+ avatarUrl: https://avatars.githubusercontent.com/u/901651?u=460bc34ac298dca9870aafe3a1560a2ae789bc4a&v=4
+ url: https://github.com/iobruno
- login: tcsmith
avatarUrl: https://avatars.githubusercontent.com/u/989034?u=7d8d741552b3279e8f4d3878679823a705a46f8f&v=4
url: https://github.com/tcsmith
- - login: ltieman
- avatarUrl: https://avatars.githubusercontent.com/u/1084689?u=e69b17de17cb3ca141a17daa7ccbe173ceb1eb17&v=4
- url: https://github.com/ltieman
- login: mrkmcknz
avatarUrl: https://avatars.githubusercontent.com/u/1089376?u=2b9b8a8c25c33a4f6c220095638bd821cdfd13a3&v=4
url: https://github.com/mrkmcknz
- login: coffeewasmyidea
avatarUrl: https://avatars.githubusercontent.com/u/1636488?u=8e32a4f200eff54dd79cd79d55d254bfce5e946d&v=4
url: https://github.com/coffeewasmyidea
+ - login: jonakoudijs
+ avatarUrl: https://avatars.githubusercontent.com/u/1906344?u=5ca0c9a1a89b6a2ba31abe35c66bdc07af60a632&v=4
+ url: https://github.com/jonakoudijs
- login: corleyma
- avatarUrl: https://avatars.githubusercontent.com/u/2080732?u=aed2ff652294a87d666b1c3f6dbe98104db76d26&v=4
+ avatarUrl: https://avatars.githubusercontent.com/u/2080732?u=c61f9a4bbc45a45f5d855f93e5f6e0fc8b32c468&v=4
url: https://github.com/corleyma
- - login: madisonmay
- avatarUrl: https://avatars.githubusercontent.com/u/2645393?u=f22b93c6ea345a4d26a90a3834dfc7f0789fcb63&v=4
- url: https://github.com/madisonmay
- - login: saivarunk
- avatarUrl: https://avatars.githubusercontent.com/u/2976867?u=71f4385e781e9a9e871a52f2d4686f9a8d69ba2f&v=4
- url: https://github.com/saivarunk
- login: andre1sk
avatarUrl: https://avatars.githubusercontent.com/u/3148093?v=4
url: https://github.com/andre1sk
@@ -185,51 +164,36 @@ sponsors:
- login: ColliotL
avatarUrl: https://avatars.githubusercontent.com/u/3412402?u=ca64b07ecbef2f9da1cc2cac3f37522aa4814902&v=4
url: https://github.com/ColliotL
- - login: grillazz
- avatarUrl: https://avatars.githubusercontent.com/u/3415861?u=453cd1725c8d7fe3e258016bc19cff861d4fcb53&v=4
- url: https://github.com/grillazz
- login: dblackrun
avatarUrl: https://avatars.githubusercontent.com/u/3528486?v=4
url: https://github.com/dblackrun
- login: zsinx6
avatarUrl: https://avatars.githubusercontent.com/u/3532625?u=ba75a5dc744d1116ccfeaaf30d41cb2fe81fe8dd&v=4
url: https://github.com/zsinx6
- - login: MarekBleschke
- avatarUrl: https://avatars.githubusercontent.com/u/3616870?v=4
- url: https://github.com/MarekBleschke
- login: aacayaco
avatarUrl: https://avatars.githubusercontent.com/u/3634801?u=eaadda178c964178fcb64886f6c732172c8f8219&v=4
url: https://github.com/aacayaco
- login: anomaly
avatarUrl: https://avatars.githubusercontent.com/u/3654837?v=4
url: https://github.com/anomaly
- - login: peterHoburg
- avatarUrl: https://avatars.githubusercontent.com/u/3860655?u=f55f47eb2d6a9b495e806ac5a044e3ae01ccc1fa&v=4
- url: https://github.com/peterHoburg
- login: jgreys
avatarUrl: https://avatars.githubusercontent.com/u/4136890?u=c66ae617d614f6c886f1f1c1799d22100b3c848d&v=4
url: https://github.com/jgreys
- - login: gorhack
- avatarUrl: https://avatars.githubusercontent.com/u/4141690?u=ec119ebc4bdf00a7bc84657a71aa17834f4f27f3&v=4
- url: https://github.com/gorhack
- login: jaredtrog
avatarUrl: https://avatars.githubusercontent.com/u/4381365?v=4
url: https://github.com/jaredtrog
- login: oliverxchen
avatarUrl: https://avatars.githubusercontent.com/u/4471774?u=534191f25e32eeaadda22dfab4b0a428733d5489&v=4
url: https://github.com/oliverxchen
- - login: Rey8d01
- avatarUrl: https://avatars.githubusercontent.com/u/4836190?u=5942598a23a377602c1669522334ab5ebeaf9165&v=4
- url: https://github.com/Rey8d01
- - login: ScrimForever
- avatarUrl: https://avatars.githubusercontent.com/u/5040124?u=091ec38bfe16d6e762099e91309b59f248616a65&v=4
- url: https://github.com/ScrimForever
- login: ennui93
avatarUrl: https://avatars.githubusercontent.com/u/5300907?u=5b5452725ddb391b2caaebf34e05aba873591c3a&v=4
url: https://github.com/ennui93
- login: ternaus
avatarUrl: https://avatars.githubusercontent.com/u/5481618?u=fabc8d75c921b3380126adb5a931c5da6e7db04f&v=4
url: https://github.com/ternaus
+ - login: eseglem
+ avatarUrl: https://avatars.githubusercontent.com/u/5920492?u=208d419cf667b8ac594c82a8db01932c7e50d057&v=4
+ url: https://github.com/eseglem
- login: Yaleesa
avatarUrl: https://avatars.githubusercontent.com/u/6135475?v=4
url: https://github.com/Yaleesa
@@ -248,6 +212,9 @@ sponsors:
- login: Rehket
avatarUrl: https://avatars.githubusercontent.com/u/7015688?u=3afb0ba200feebbc7f958950e92db34df2a3c172&v=4
url: https://github.com/Rehket
+ - login: ValentinCalomme
+ avatarUrl: https://avatars.githubusercontent.com/u/7288672?u=e09758c7a36c49f0fb3574abe919cbd344fdc2d6&v=4
+ url: https://github.com/ValentinCalomme
- login: hiancdtrsnm
avatarUrl: https://avatars.githubusercontent.com/u/7343177?v=4
url: https://github.com/hiancdtrsnm
@@ -257,15 +224,9 @@ sponsors:
- login: wdwinslow
avatarUrl: https://avatars.githubusercontent.com/u/11562137?u=dc01daafb354135603a263729e3d26d939c0c452&v=4
url: https://github.com/wdwinslow
- - login: bapi24
- avatarUrl: https://avatars.githubusercontent.com/u/11890901?u=45cc721d8f66ad2f62b086afc3d4761d0c16b9c6&v=4
- url: https://github.com/bapi24
- login: svats2k
avatarUrl: https://avatars.githubusercontent.com/u/12378398?u=ecf28c19f61052e664bdfeb2391f8107d137915c&v=4
url: https://github.com/svats2k
- - login: gokulyc
- avatarUrl: https://avatars.githubusercontent.com/u/13468848?u=269f269d3e70407b5fb80138c52daba7af783997&v=4
- url: https://github.com/gokulyc
- login: dannywade
avatarUrl: https://avatars.githubusercontent.com/u/13680237?u=418ee985bd41577b20fde81417fb2d901e875e8a&v=4
url: https://github.com/dannywade
@@ -273,20 +234,26 @@ sponsors:
avatarUrl: https://avatars.githubusercontent.com/u/13686061?u=59f25ef42ecf04c22657aac4238ce0e2d3d30304&v=4
url: https://github.com/khadrawy
- login: pablonnaoji
- avatarUrl: https://avatars.githubusercontent.com/u/15187159?u=afc15bd5a4ba9c5c7206bbb1bcaeef606a0932e0&v=4
+ avatarUrl: https://avatars.githubusercontent.com/u/15187159?u=7480e0eaf959e9c5dfe3a05286f2ea4588c0a3c6&v=4
url: https://github.com/pablonnaoji
+ - login: mjohnsey
+ avatarUrl: https://avatars.githubusercontent.com/u/16784016?u=38fad2e6b411244560b3af99c5f5a4751bc81865&v=4
+ url: https://github.com/mjohnsey
+ - login: abdalla19977
+ avatarUrl: https://avatars.githubusercontent.com/u/17257234?v=4
+ url: https://github.com/abdalla19977
- login: wedwardbeck
avatarUrl: https://avatars.githubusercontent.com/u/19333237?u=1de4ae2bf8d59eb4c013f21d863cbe0f2010575f&v=4
url: https://github.com/wedwardbeck
- - login: m4knV
- avatarUrl: https://avatars.githubusercontent.com/u/19666130?u=843383978814886be93c137d10d2e20e9f13af07&v=4
- url: https://github.com/m4knV
- login: Filimoa
- avatarUrl: https://avatars.githubusercontent.com/u/21352040?u=75e02d102d2ee3e3d793e555fa5c63045913ccb0&v=4
+ avatarUrl: https://avatars.githubusercontent.com/u/21352040?u=0be845711495bbd7b756e13fcaeb8efc1ebd78ba&v=4
url: https://github.com/Filimoa
- login: shuheng-liu
avatarUrl: https://avatars.githubusercontent.com/u/22414322?u=813c45f30786c6b511b21a661def025d8f7b609e&v=4
url: https://github.com/shuheng-liu
+ - login: Pablongo24
+ avatarUrl: https://avatars.githubusercontent.com/u/24843427?u=78a6798469889d7a0690449fc667c39e13d5c6a9&v=4
+ url: https://github.com/Pablongo24
- login: Joeriksson
avatarUrl: https://avatars.githubusercontent.com/u/25037079?v=4
url: https://github.com/Joeriksson
@@ -317,9 +284,12 @@ sponsors:
- login: ProteinQure
avatarUrl: https://avatars.githubusercontent.com/u/33707203?v=4
url: https://github.com/ProteinQure
- - login: faviasono
- avatarUrl: https://avatars.githubusercontent.com/u/37707874?u=f0b75ca4248987c08ed8fb8ed682e7e74d5d7091&v=4
- url: https://github.com/faviasono
+ - login: askurihin
+ avatarUrl: https://avatars.githubusercontent.com/u/37978981?v=4
+ url: https://github.com/askurihin
+ - login: arleybri18
+ avatarUrl: https://avatars.githubusercontent.com/u/39681546?u=5c028f81324b0e8c73b3c15bc4e7b0218d2ba0c3&v=4
+ url: https://github.com/arleybri18
- login: ybressler
avatarUrl: https://avatars.githubusercontent.com/u/40807730?u=41e2c00f1eebe3c402635f0325e41b4e6511462c&v=4
url: https://github.com/ybressler
@@ -329,18 +299,21 @@ sponsors:
- login: VictorCalderon
avatarUrl: https://avatars.githubusercontent.com/u/44529243?u=cea69884f826a29aff1415493405209e0706d07a&v=4
url: https://github.com/VictorCalderon
- - login: arthuRHD
- avatarUrl: https://avatars.githubusercontent.com/u/48015496?u=05a0d5b8b9320eeb7990d35c9337b823f269d2ff&v=4
- url: https://github.com/arthuRHD
- login: rafsaf
avatarUrl: https://avatars.githubusercontent.com/u/51059348?u=f8f0d6d6e90fac39fa786228158ba7f013c74271&v=4
url: https://github.com/rafsaf
- login: dudikbender
- avatarUrl: https://avatars.githubusercontent.com/u/53487583?u=494f85229115076121b3639a3806bbac1c6ae7f6&v=4
+ avatarUrl: https://avatars.githubusercontent.com/u/53487583?u=3a57542938ebfd57579a0111db2b297e606d9681&v=4
url: https://github.com/dudikbender
- - login: dazeddd
- avatarUrl: https://avatars.githubusercontent.com/u/59472056?u=7a1b668449bf8b448db13e4c575576d24d7d658b&v=4
- url: https://github.com/dazeddd
+ - login: thisistheplace
+ avatarUrl: https://avatars.githubusercontent.com/u/57633545?u=a3f3a7f8ace8511c6c067753f6eb6aee0db11ac6&v=4
+ url: https://github.com/thisistheplace
+ - login: kyjoconn
+ avatarUrl: https://avatars.githubusercontent.com/u/58443406?u=a3e9c2acfb7ba62edda9334aba61cf027f41f789&v=4
+ url: https://github.com/kyjoconn
+ - login: A-Edge
+ avatarUrl: https://avatars.githubusercontent.com/u/59514131?v=4
+ url: https://github.com/A-Edge
- login: yakkonaut
avatarUrl: https://avatars.githubusercontent.com/u/60633704?u=90a71fd631aa998ba4a96480788f017c9904e07b&v=4
url: https://github.com/yakkonaut
@@ -350,31 +323,28 @@ sponsors:
- login: predictionmachine
avatarUrl: https://avatars.githubusercontent.com/u/63719559?v=4
url: https://github.com/predictionmachine
- - login: minsau
- avatarUrl: https://avatars.githubusercontent.com/u/64386242?u=7e45f24b2958caf946fa3546ea33bacf5cd886f8&v=4
- url: https://github.com/minsau
- login: daverin
avatarUrl: https://avatars.githubusercontent.com/u/70378377?u=6d1814195c0de7162820eaad95a25b423a3869c0&v=4
url: https://github.com/daverin
- login: anthonycepeda
avatarUrl: https://avatars.githubusercontent.com/u/72019805?u=4252c6b6dc5024af502a823a3ac5e7a03a69963f&v=4
url: https://github.com/anthonycepeda
- - login: fpiem
- avatarUrl: https://avatars.githubusercontent.com/u/77389987?u=f667a25cd4832b28801189013b74450e06cc232c&v=4
- url: https://github.com/fpiem
- login: DelfinaCare
avatarUrl: https://avatars.githubusercontent.com/u/83734439?v=4
url: https://github.com/DelfinaCare
- - login: programvx
- avatarUrl: https://avatars.githubusercontent.com/u/96057906?v=4
- url: https://github.com/programvx
+ - login: osawa-koki
+ avatarUrl: https://avatars.githubusercontent.com/u/94336223?u=59c6fe6945bcbbaff87b2a794238671b060620d2&v=4
+ url: https://github.com/osawa-koki
- login: pyt3h
avatarUrl: https://avatars.githubusercontent.com/u/99658549?v=4
url: https://github.com/pyt3h
- login: Dagmaara
avatarUrl: https://avatars.githubusercontent.com/u/115501964?v=4
url: https://github.com/Dagmaara
-- - login: linux-china
+- - login: pawamoy
+ avatarUrl: https://avatars.githubusercontent.com/u/3999221?u=b030e4c89df2f3a36bc4710b925bdeb6745c9856&v=4
+ url: https://github.com/pawamoy
+ - login: linux-china
avatarUrl: https://avatars.githubusercontent.com/u/46711?u=cd77c65338b158750eb84dc7ff1acf3209ccfc4f&v=4
url: https://github.com/linux-china
- login: ddanier
@@ -389,12 +359,6 @@ sponsors:
- login: bryanculbertson
avatarUrl: https://avatars.githubusercontent.com/u/144028?u=defda4f90e93429221cc667500944abde60ebe4a&v=4
url: https://github.com/bryanculbertson
- - login: hhatto
- avatarUrl: https://avatars.githubusercontent.com/u/150309?u=3e8f63c27bf996bfc68464b0ce3f7a3e40e6ea7f&v=4
- url: https://github.com/hhatto
- - login: slafs
- avatarUrl: https://avatars.githubusercontent.com/u/210173?v=4
- url: https://github.com/slafs
- login: adamghill
avatarUrl: https://avatars.githubusercontent.com/u/317045?u=f1349d5ffe84a19f324e204777859fbf69ddf633&v=4
url: https://github.com/adamghill
@@ -404,9 +368,6 @@ sponsors:
- login: dmig
avatarUrl: https://avatars.githubusercontent.com/u/388564?v=4
url: https://github.com/dmig
- - login: rinckd
- avatarUrl: https://avatars.githubusercontent.com/u/546002?u=8ec88ab721a5636346f19dcd677a6f323058be8b&v=4
- url: https://github.com/rinckd
- login: securancy
avatarUrl: https://avatars.githubusercontent.com/u/606673?v=4
url: https://github.com/securancy
@@ -419,39 +380,27 @@ sponsors:
- login: janfilips
avatarUrl: https://avatars.githubusercontent.com/u/870699?u=50de77b93d3a0b06887e672d4e8c7b9d643085aa&v=4
url: https://github.com/janfilips
- - login: woodrad
- avatarUrl: https://avatars.githubusercontent.com/u/1410765?u=86707076bb03d143b3b11afc1743d2aa496bd8bf&v=4
- url: https://github.com/woodrad
- - login: Pytlicek
- avatarUrl: https://avatars.githubusercontent.com/u/1430522?u=01b1f2f7671ce3131e0877d08e2e3f8bdbb0a38a&v=4
- url: https://github.com/Pytlicek
- login: allen0125
avatarUrl: https://avatars.githubusercontent.com/u/1448456?u=dc2ad819497eef494b88688a1796e0adb87e7cae&v=4
url: https://github.com/allen0125
- login: WillHogan
avatarUrl: https://avatars.githubusercontent.com/u/1661551?u=7036c064cf29781470573865264ec8e60b6b809f&v=4
url: https://github.com/WillHogan
+ - login: my3
+ avatarUrl: https://avatars.githubusercontent.com/u/1825270?v=4
+ url: https://github.com/my3
- login: cbonoz
avatarUrl: https://avatars.githubusercontent.com/u/2351087?u=fd3e8030b2cc9fbfbb54a65e9890c548a016f58b&v=4
url: https://github.com/cbonoz
- - login: Debakel
- avatarUrl: https://avatars.githubusercontent.com/u/2857237?u=07df6d11c8feef9306d071cb1c1005a2dd596585&v=4
- url: https://github.com/Debakel
- login: paul121
avatarUrl: https://avatars.githubusercontent.com/u/3116995?u=6e2d8691cc345e63ee02e4eb4d7cef82b1fcbedc&v=4
url: https://github.com/paul121
- - login: igorcorrea
- avatarUrl: https://avatars.githubusercontent.com/u/3438238?u=c57605077c31a8f7b2341fc4912507f91b4a5621&v=4
- url: https://github.com/igorcorrea
+ - login: larsvik
+ avatarUrl: https://avatars.githubusercontent.com/u/3442226?v=4
+ url: https://github.com/larsvik
- login: anthonycorletti
avatarUrl: https://avatars.githubusercontent.com/u/3477132?v=4
url: https://github.com/anthonycorletti
- - login: jonathanhle
- avatarUrl: https://avatars.githubusercontent.com/u/3851599?u=76b9c5d2fecd6c3a16e7645231878c4507380d4d&v=4
- url: https://github.com/jonathanhle
- - login: pawamoy
- avatarUrl: https://avatars.githubusercontent.com/u/3999221?u=b030e4c89df2f3a36bc4710b925bdeb6745c9856&v=4
- url: https://github.com/pawamoy
- login: nikeee
avatarUrl: https://avatars.githubusercontent.com/u/4068864?u=63f8eee593f25138e0f1032ef442e9ad24907d4c&v=4
url: https://github.com/nikeee
@@ -467,11 +416,14 @@ sponsors:
- login: Baghdady92
avatarUrl: https://avatars.githubusercontent.com/u/5708590?v=4
url: https://github.com/Baghdady92
+ - login: KentShikama
+ avatarUrl: https://avatars.githubusercontent.com/u/6329898?u=8b236810db9b96333230430837e1f021f9246da1&v=4
+ url: https://github.com/KentShikama
- login: holec
avatarUrl: https://avatars.githubusercontent.com/u/6438041?u=f5af71ec85b3a9d7b8139cb5af0512b02fa9ab1e&v=4
url: https://github.com/holec
- login: mattwelke
- avatarUrl: https://avatars.githubusercontent.com/u/7719209?u=5d963ead289969257190b133250653bd99df06ba&v=4
+ avatarUrl: https://avatars.githubusercontent.com/u/7719209?v=4
url: https://github.com/mattwelke
- login: hcristea
avatarUrl: https://avatars.githubusercontent.com/u/7814406?u=61d7a4fcf846983a4606788eac25e1c6c1209ba8&v=4
@@ -479,9 +431,6 @@ sponsors:
- login: moonape1226
avatarUrl: https://avatars.githubusercontent.com/u/8532038?u=d9f8b855a429fff9397c3833c2ff83849ebf989d&v=4
url: https://github.com/moonape1226
- - login: yenchenLiu
- avatarUrl: https://avatars.githubusercontent.com/u/9199638?u=8cdf5ae507448430d90f6f3518d1665a23afe99b&v=4
- url: https://github.com/yenchenLiu
- login: xncbf
avatarUrl: https://avatars.githubusercontent.com/u/9462045?u=866a1311e4bd3ec5ae84185c4fcc99f397c883d7&v=4
url: https://github.com/xncbf
@@ -506,9 +455,9 @@ sponsors:
- login: giuliano-oliveira
avatarUrl: https://avatars.githubusercontent.com/u/13181797?u=0ef2dfbf7fc9a9726d45c21d32b5d1038a174870&v=4
url: https://github.com/giuliano-oliveira
- - login: logan-connolly
- avatarUrl: https://avatars.githubusercontent.com/u/16244943?u=8ae66dfbba936463cc8aa0dd7a6d2b4c0cc757eb&v=4
- url: https://github.com/logan-connolly
+ - login: TheR1D
+ avatarUrl: https://avatars.githubusercontent.com/u/16740832?u=b2923ac17fe6e2a7c9ea14800351ddb92f79b100&v=4
+ url: https://github.com/TheR1D
- login: cdsre
avatarUrl: https://avatars.githubusercontent.com/u/16945936?v=4
url: https://github.com/cdsre
@@ -518,21 +467,18 @@ sponsors:
- login: paulowiz
avatarUrl: https://avatars.githubusercontent.com/u/18649504?u=d8a6ac40321f2bded0eba78b637751c7f86c6823&v=4
url: https://github.com/paulowiz
- - login: yannicschroeer
- avatarUrl: https://avatars.githubusercontent.com/u/22749683?u=4df05a7296c207b91c5d7c7a11c29df5ab313e2b&v=4
- url: https://github.com/yannicschroeer
- login: ghandic
avatarUrl: https://avatars.githubusercontent.com/u/23500353?u=e2e1d736f924d9be81e8bfc565b6d8836ba99773&v=4
url: https://github.com/ghandic
- - login: fstau
- avatarUrl: https://avatars.githubusercontent.com/u/24669867?u=60e7c8c09f8dafabee8fc3edcd6f9e19abbff918&v=4
- url: https://github.com/fstau
- login: pers0n4
- avatarUrl: https://avatars.githubusercontent.com/u/24864600?u=444441027bc2c9f9db68e8047d65ff23d25699cf&v=4
+ avatarUrl: https://avatars.githubusercontent.com/u/24864600?u=f211a13a7b572cbbd7779b9c8d8cb428cc7ba07e&v=4
url: https://github.com/pers0n4
- login: SebTota
avatarUrl: https://avatars.githubusercontent.com/u/25122511?v=4
url: https://github.com/SebTota
+ - login: hoenie-ams
+ avatarUrl: https://avatars.githubusercontent.com/u/25708487?u=cda07434f0509ac728d9edf5e681117c0f6b818b&v=4
+ url: https://github.com/hoenie-ams
- login: joerambo
avatarUrl: https://avatars.githubusercontent.com/u/26282974?v=4
url: https://github.com/joerambo
@@ -549,7 +495,7 @@ sponsors:
avatarUrl: https://avatars.githubusercontent.com/u/33275230?u=eb223cad27017bb1e936ee9b429b450d092d0236&v=4
url: https://github.com/engineerjoe440
- login: bnkc
- avatarUrl: https://avatars.githubusercontent.com/u/34930566?u=20f362505e2a994805233f42e69f9f14b4a9dd0c&v=4
+ avatarUrl: https://avatars.githubusercontent.com/u/34930566?u=76cdc0a8b4e88c7d3e58dccb4b2670839e1247b4&v=4
url: https://github.com/bnkc
- login: declon
avatarUrl: https://avatars.githubusercontent.com/u/36180226?v=4
@@ -564,26 +510,14 @@ sponsors:
avatarUrl: https://avatars.githubusercontent.com/u/38921751?u=ae14bc1e40f2dd5a9c5741fc0b0dffbd416a5fa9&v=4
url: https://github.com/ww-daniel-mora
- login: rwxd
- avatarUrl: https://avatars.githubusercontent.com/u/40308458?u=9ddf8023ca3326381ba8fb77285ae36598a15de3&v=4
+ avatarUrl: https://avatars.githubusercontent.com/u/40308458?u=cd04a39e3655923be4f25c2ba8a5a07b3da3230a&v=4
url: https://github.com/rwxd
- - login: ilias-ant
- avatarUrl: https://avatars.githubusercontent.com/u/42189572?u=a2d6121bac4d125d92ec207460fa3f1842d37e66&v=4
- url: https://github.com/ilias-ant
- login: arrrrrmin
- avatarUrl: https://avatars.githubusercontent.com/u/43553423?u=2a812c1a2ec58227ed01778837f255143de9df97&v=4
+ avatarUrl: https://avatars.githubusercontent.com/u/43553423?u=5265858add14a6822bd145f7547323cf078563e6&v=4
url: https://github.com/arrrrrmin
- - login: MauriceKuenicke
- avatarUrl: https://avatars.githubusercontent.com/u/47433175?u=37455bc95c7851db296ac42626f0cacb77ca2443&v=4
- url: https://github.com/MauriceKuenicke
- login: hgalytoby
avatarUrl: https://avatars.githubusercontent.com/u/50397689?u=f4888c2c54929bd86eed0d3971d09fcb306e5088&v=4
url: https://github.com/hgalytoby
- - login: akanz1
- avatarUrl: https://avatars.githubusercontent.com/u/51492342?u=2280f57134118714645e16b535c1a37adf6b369b&v=4
- url: https://github.com/akanz1
- - login: shidenko97
- avatarUrl: https://avatars.githubusercontent.com/u/54946990?u=3fdc0caea36af9217dacf1cc7760c7ed9d67dcfe&v=4
- url: https://github.com/shidenko97
- login: data-djinn
avatarUrl: https://avatars.githubusercontent.com/u/56449985?u=42146e140806908d49bd59ccc96f222abf587886&v=4
url: https://github.com/data-djinn
@@ -602,21 +536,12 @@ sponsors:
- login: realabja
avatarUrl: https://avatars.githubusercontent.com/u/66185192?u=001e2dd9297784f4218997981b4e6fa8357bb70b&v=4
url: https://github.com/realabja
- - login: alessio-proietti
- avatarUrl: https://avatars.githubusercontent.com/u/67370599?u=8ac73db1e18e946a7681f173abdb640516f88515&v=4
- url: https://github.com/alessio-proietti
- - login: pondDevThai
- avatarUrl: https://avatars.githubusercontent.com/u/71592181?u=08af9a59bccfd8f6b101de1005aa9822007d0a44&v=4
- url: https://github.com/pondDevThai
-- - login: wardal
- avatarUrl: https://avatars.githubusercontent.com/u/15804042?v=4
- url: https://github.com/wardal
- - login: gabrielmbmb
- avatarUrl: https://avatars.githubusercontent.com/u/29572918?u=6d1e00b5d558e96718312ff910a2318f47cc3145&v=4
- url: https://github.com/gabrielmbmb
+ - login: garydsong
+ avatarUrl: https://avatars.githubusercontent.com/u/105745865?u=03cc1aa9c978be0020e5a1ce1ecca323dd6c8d65&v=4
+ url: https://github.com/garydsong
+- - login: Leon0824
+ avatarUrl: https://avatars.githubusercontent.com/u/1922026?v=4
+ url: https://github.com/Leon0824
- login: danburonline
avatarUrl: https://avatars.githubusercontent.com/u/34251194?u=2cad4388c1544e539ecb732d656e42fb07b4ff2d&v=4
url: https://github.com/danburonline
- - login: Moises6669
- avatarUrl: https://avatars.githubusercontent.com/u/66188523?u=96af25b8d5be9f983cb96e9dd7c605c716caf1f5&v=4
- url: https://github.com/Moises6669
diff --git a/docs/en/data/people.yml b/docs/en/data/people.yml
index 51940a6b1..412f4517a 100644
--- a/docs/en/data/people.yml
+++ b/docs/en/data/people.yml
@@ -1,158 +1,158 @@
maintainers:
- login: tiangolo
- answers: 1837
- prs: 360
+ answers: 1827
+ prs: 384
avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=740f11212a731f56798f558ceddb0bd07642afa7&v=4
url: https://github.com/tiangolo
experts:
- login: Kludex
- count: 374
+ count: 376
avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4
url: https://github.com/Kludex
- login: dmontagu
- count: 262
+ count: 237
avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=58ed2a45798a4339700e2f62b2e12e6e54bf0396&v=4
url: https://github.com/dmontagu
-- login: ycd
- count: 221
- avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=bba5af018423a2858d49309bed2a899bb5c34ac5&v=4
- url: https://github.com/ycd
- login: Mause
- count: 207
+ count: 220
avatarUrl: https://avatars.githubusercontent.com/u/1405026?v=4
url: https://github.com/Mause
+- login: ycd
+ count: 217
+ avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=bba5af018423a2858d49309bed2a899bb5c34ac5&v=4
+ url: https://github.com/ycd
- login: JarroVGIT
count: 192
avatarUrl: https://avatars.githubusercontent.com/u/13659033?u=e8bea32d07a5ef72f7dde3b2079ceb714923ca05&v=4
url: https://github.com/JarroVGIT
- login: euri10
- count: 166
+ count: 151
avatarUrl: https://avatars.githubusercontent.com/u/1104190?u=321a2e953e6645a7d09b732786c7a8061e0f8a8b&v=4
url: https://github.com/euri10
- login: phy25
- count: 130
+ count: 126
avatarUrl: https://avatars.githubusercontent.com/u/331403?v=4
url: https://github.com/phy25
- login: iudeen
- count: 87
+ count: 116
avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4
url: https://github.com/iudeen
+- login: jgould22
+ count: 101
+ avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4
+ url: https://github.com/jgould22
- login: raphaelauv
- count: 77
+ count: 83
avatarUrl: https://avatars.githubusercontent.com/u/10202690?u=e6f86f5c0c3026a15d6b51792fa3e532b12f1371&v=4
url: https://github.com/raphaelauv
- login: ArcLightSlavik
count: 71
avatarUrl: https://avatars.githubusercontent.com/u/31127044?u=b0f2c37142f4b762e41ad65dc49581813422bd71&v=4
url: https://github.com/ArcLightSlavik
+- login: ghandic
+ count: 71
+ avatarUrl: https://avatars.githubusercontent.com/u/23500353?u=e2e1d736f924d9be81e8bfc565b6d8836ba99773&v=4
+ url: https://github.com/ghandic
- login: falkben
- count: 59
+ count: 57
avatarUrl: https://avatars.githubusercontent.com/u/653031?u=0c8d8f33d87f1aa1a6488d3f02105e9abc838105&v=4
url: https://github.com/falkben
-- login: jgould22
- count: 55
- avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4
- url: https://github.com/jgould22
- login: sm-Fifteen
- count: 50
+ count: 49
avatarUrl: https://avatars.githubusercontent.com/u/516999?u=437c0c5038558c67e887ccd863c1ba0f846c03da&v=4
url: https://github.com/sm-Fifteen
-- login: insomnes
- count: 46
- avatarUrl: https://avatars.githubusercontent.com/u/16958893?u=f8be7088d5076d963984a21f95f44e559192d912&v=4
- url: https://github.com/insomnes
- login: Dustyposa
count: 45
avatarUrl: https://avatars.githubusercontent.com/u/27180793?u=5cf2877f50b3eb2bc55086089a78a36f07042889&v=4
url: https://github.com/Dustyposa
+- login: insomnes
+ count: 45
+ avatarUrl: https://avatars.githubusercontent.com/u/16958893?u=f8be7088d5076d963984a21f95f44e559192d912&v=4
+ url: https://github.com/insomnes
+- login: frankie567
+ count: 43
+ avatarUrl: https://avatars.githubusercontent.com/u/1144727?u=85c025e3fcc7bd79a5665c63ee87cdf8aae13374&v=4
+ url: https://github.com/frankie567
+- login: acidjunk
+ count: 43
+ avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4
+ url: https://github.com/acidjunk
+- login: odiseo0
+ count: 42
+ avatarUrl: https://avatars.githubusercontent.com/u/87550035?u=16f9255804161c6ff3c8b7ef69848f0126bcd405&v=4
+ url: https://github.com/odiseo0
- login: adriangb
count: 40
- avatarUrl: https://avatars.githubusercontent.com/u/1755071?u=75087f0cf0e9f725f3cd18a899218b6c63ae60d3&v=4
+ avatarUrl: https://avatars.githubusercontent.com/u/1755071?u=1e2c2c9b39f5c9b780fb933d8995cf08ec235a47&v=4
url: https://github.com/adriangb
- login: includeamin
- count: 39
+ count: 40
avatarUrl: https://avatars.githubusercontent.com/u/11836741?u=8bd5ef7e62fe6a82055e33c4c0e0a7879ff8cfb6&v=4
url: https://github.com/includeamin
- login: STeveShary
count: 37
avatarUrl: https://avatars.githubusercontent.com/u/5167622?u=de8f597c81d6336fcebc37b32dfd61a3f877160c&v=4
url: https://github.com/STeveShary
-- login: chbndrhnns
- count: 36
- avatarUrl: https://avatars.githubusercontent.com/u/7534547?v=4
- url: https://github.com/chbndrhnns
-- login: frankie567
- count: 33
- avatarUrl: https://avatars.githubusercontent.com/u/1144727?u=85c025e3fcc7bd79a5665c63ee87cdf8aae13374&v=4
- url: https://github.com/frankie567
-- login: prostomarkeloff
- count: 33
- avatarUrl: https://avatars.githubusercontent.com/u/28061158?u=72309cc1f2e04e40fa38b29969cb4e9d3f722e7b&v=4
- url: https://github.com/prostomarkeloff
-- login: acidjunk
- count: 32
- avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4
- url: https://github.com/acidjunk
- login: krishnardt
- count: 31
+ count: 35
avatarUrl: https://avatars.githubusercontent.com/u/31960541?u=47f4829c77f4962ab437ffb7995951e41eeebe9b&v=4
url: https://github.com/krishnardt
-- login: wshayes
- count: 29
- avatarUrl: https://avatars.githubusercontent.com/u/365303?u=07ca03c5ee811eb0920e633cc3c3db73dbec1aa5&v=4
- url: https://github.com/wshayes
+- login: yinziyan1206
+ count: 34
+ avatarUrl: https://avatars.githubusercontent.com/u/37829370?u=da44ca53aefd5c23f346fab8e9fd2e108294c179&v=4
+ url: https://github.com/yinziyan1206
+- login: chbndrhnns
+ count: 34
+ avatarUrl: https://avatars.githubusercontent.com/u/7534547?v=4
+ url: https://github.com/chbndrhnns
- login: panla
- count: 29
+ count: 32
avatarUrl: https://avatars.githubusercontent.com/u/41326348?u=ba2fda6b30110411ecbf406d187907e2b420ac19&v=4
url: https://github.com/panla
-- login: ghandic
- count: 25
- avatarUrl: https://avatars.githubusercontent.com/u/23500353?u=e2e1d736f924d9be81e8bfc565b6d8836ba99773&v=4
- url: https://github.com/ghandic
+- login: prostomarkeloff
+ count: 28
+ avatarUrl: https://avatars.githubusercontent.com/u/28061158?u=72309cc1f2e04e40fa38b29969cb4e9d3f722e7b&v=4
+ url: https://github.com/prostomarkeloff
- login: dbanty
- count: 25
+ count: 26
avatarUrl: https://avatars.githubusercontent.com/u/43723790?u=9bcce836bbce55835291c5b2ac93a4e311f4b3c3&v=4
url: https://github.com/dbanty
-- login: yinziyan1206
+- login: wshayes
count: 25
- avatarUrl: https://avatars.githubusercontent.com/u/37829370?u=da44ca53aefd5c23f346fab8e9fd2e108294c179&v=4
- url: https://github.com/yinziyan1206
+ avatarUrl: https://avatars.githubusercontent.com/u/365303?u=07ca03c5ee811eb0920e633cc3c3db73dbec1aa5&v=4
+ url: https://github.com/wshayes
- login: SirTelemak
- count: 24
+ count: 23
avatarUrl: https://avatars.githubusercontent.com/u/9435877?u=719327b7d2c4c62212456d771bfa7c6b8dbb9eac&v=4
url: https://github.com/SirTelemak
-- login: odiseo0
- count: 24
- avatarUrl: https://avatars.githubusercontent.com/u/87550035?u=16f9255804161c6ff3c8b7ef69848f0126bcd405&v=4
- url: https://github.com/odiseo0
-- login: acnebs
- count: 22
- avatarUrl: https://avatars.githubusercontent.com/u/9054108?u=c27e50269f1ef8ea950cc6f0268c8ec5cebbe9c9&v=4
- url: https://github.com/acnebs
+- login: caeser1996
+ count: 21
+ avatarUrl: https://avatars.githubusercontent.com/u/16540232?u=05d2beb8e034d584d0a374b99d8826327bd7f614&v=4
+ url: https://github.com/caeser1996
+- login: rafsaf
+ count: 21
+ avatarUrl: https://avatars.githubusercontent.com/u/51059348?u=f8f0d6d6e90fac39fa786228158ba7f013c74271&v=4
+ url: https://github.com/rafsaf
- login: nsidnev
- count: 22
+ count: 20
avatarUrl: https://avatars.githubusercontent.com/u/22559461?u=a9cc3238217e21dc8796a1a500f01b722adb082c&v=4
url: https://github.com/nsidnev
+- login: acnebs
+ count: 20
+ avatarUrl: https://avatars.githubusercontent.com/u/9054108?u=c27e50269f1ef8ea950cc6f0268c8ec5cebbe9c9&v=4
+ url: https://github.com/acnebs
- login: chris-allnutt
- count: 21
+ count: 20
avatarUrl: https://avatars.githubusercontent.com/u/565544?v=4
url: https://github.com/chris-allnutt
- login: retnikt
- count: 19
+ count: 18
avatarUrl: https://avatars.githubusercontent.com/u/24581770?v=4
url: https://github.com/retnikt
-- login: rafsaf
- count: 19
- avatarUrl: https://avatars.githubusercontent.com/u/51059348?u=f8f0d6d6e90fac39fa786228158ba7f013c74271&v=4
- url: https://github.com/rafsaf
-- login: Hultner
+- login: zoliknemet
count: 18
- avatarUrl: https://avatars.githubusercontent.com/u/2669034?u=115e53df959309898ad8dc9443fbb35fee71df07&v=4
- url: https://github.com/Hultner
-- login: jorgerpo
- count: 17
- avatarUrl: https://avatars.githubusercontent.com/u/12537771?u=7444d20019198e34911082780cc7ad73f2b97cb3&v=4
- url: https://github.com/jorgerpo
+ avatarUrl: https://avatars.githubusercontent.com/u/22326718?u=31ba446ac290e23e56eea8e4f0c558aaf0b40779&v=4
+ url: https://github.com/zoliknemet
- login: nkhitrov
count: 17
avatarUrl: https://avatars.githubusercontent.com/u/28262306?u=66ee21316275ef356081c2efc4ed7a4572e690dc&v=4
@@ -161,75 +161,79 @@ experts:
count: 17
avatarUrl: https://avatars.githubusercontent.com/u/1765494?u=5b1ab7c582db4b4016fa31affe977d10af108ad4&v=4
url: https://github.com/harunyasar
-- login: waynerv
+- login: Hultner
+ count: 17
+ avatarUrl: https://avatars.githubusercontent.com/u/2669034?u=115e53df959309898ad8dc9443fbb35fee71df07&v=4
+ url: https://github.com/Hultner
+- login: jonatasoli
count: 16
- avatarUrl: https://avatars.githubusercontent.com/u/39515546?u=ec35139777597cdbbbddda29bf8b9d4396b429a9&v=4
- url: https://github.com/waynerv
+ avatarUrl: https://avatars.githubusercontent.com/u/26334101?u=071c062d2861d3dd127f6b4a5258cd8ef55d4c50&v=4
+ url: https://github.com/jonatasoli
- login: dstlny
count: 16
avatarUrl: https://avatars.githubusercontent.com/u/41964673?u=9f2174f9d61c15c6e3a4c9e3aeee66f711ce311f&v=4
url: https://github.com/dstlny
-- login: jonatasoli
+- login: jorgerpo
count: 15
- avatarUrl: https://avatars.githubusercontent.com/u/26334101?u=071c062d2861d3dd127f6b4a5258cd8ef55d4c50&v=4
- url: https://github.com/jonatasoli
-- login: mbroton
+ avatarUrl: https://avatars.githubusercontent.com/u/12537771?u=7444d20019198e34911082780cc7ad73f2b97cb3&v=4
+ url: https://github.com/jorgerpo
+- login: ghost
count: 15
- avatarUrl: https://avatars.githubusercontent.com/u/50829834?u=a48610bf1bffaa9c75d03228926e2eb08a2e24ee&v=4
- url: https://github.com/mbroton
+ avatarUrl: https://avatars.githubusercontent.com/u/10137?u=b1951d34a583cf12ec0d3b0781ba19be97726318&v=4
+ url: https://github.com/ghost
+- login: simondale00
+ count: 15
+ avatarUrl: https://avatars.githubusercontent.com/u/33907262?v=4
+ url: https://github.com/simondale00
- login: hellocoldworld
count: 14
avatarUrl: https://avatars.githubusercontent.com/u/47581948?u=3d2186796434c507a6cb6de35189ab0ad27c356f&v=4
url: https://github.com/hellocoldworld
-- login: haizaar
- count: 13
- avatarUrl: https://avatars.githubusercontent.com/u/58201?u=dd40d99a3e1935d0b768f122bfe2258d6ea53b2b&v=4
- url: https://github.com/haizaar
-- login: valentin994
+- login: waynerv
+ count: 14
+ avatarUrl: https://avatars.githubusercontent.com/u/39515546?u=ec35139777597cdbbbddda29bf8b9d4396b429a9&v=4
+ url: https://github.com/waynerv
+- login: mbroton
count: 13
- avatarUrl: https://avatars.githubusercontent.com/u/42819267?u=fdeeaa9242a59b243f8603496b00994f6951d5a2&v=4
- url: https://github.com/valentin994
-- login: David-Lor
- count: 12
- avatarUrl: https://avatars.githubusercontent.com/u/17401854?u=474680c02b94cba810cb9032fb7eb787d9cc9d22&v=4
- url: https://github.com/David-Lor
-- login: n8sty
- count: 12
- avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4
- url: https://github.com/n8sty
+ avatarUrl: https://avatars.githubusercontent.com/u/50829834?u=a48610bf1bffaa9c75d03228926e2eb08a2e24ee&v=4
+ url: https://github.com/mbroton
last_month_active:
+- login: mr-st0rm
+ count: 7
+ avatarUrl: https://avatars.githubusercontent.com/u/48455163?u=6b83550e4e70bea57cd2fdb41e717aeab7f64a91&v=4
+ url: https://github.com/mr-st0rm
+- login: caeser1996
+ count: 7
+ avatarUrl: https://avatars.githubusercontent.com/u/16540232?u=05d2beb8e034d584d0a374b99d8826327bd7f614&v=4
+ url: https://github.com/caeser1996
+- login: ebottos94
+ count: 6
+ avatarUrl: https://avatars.githubusercontent.com/u/100039558?u=e2c672da5a7977fd24d87ce6ab35f8bf5b1ed9fa&v=4
+ url: https://github.com/ebottos94
- login: jgould22
- count: 9
+ count: 6
avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4
url: https://github.com/jgould22
-- login: yinziyan1206
- count: 9
- avatarUrl: https://avatars.githubusercontent.com/u/37829370?u=da44ca53aefd5c23f346fab8e9fd2e108294c179&v=4
- url: https://github.com/yinziyan1206
-- login: iudeen
- count: 8
- avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4
- url: https://github.com/iudeen
- login: Kludex
count: 5
avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4
url: https://github.com/Kludex
-- login: JarroVGIT
- count: 5
- avatarUrl: https://avatars.githubusercontent.com/u/13659033?u=e8bea32d07a5ef72f7dde3b2079ceb714923ca05&v=4
- url: https://github.com/JarroVGIT
-- login: TheJumpyWizard
+- login: clemens-tolboom
count: 4
- avatarUrl: https://avatars.githubusercontent.com/u/90986815?u=67e9c13c9f063dd4313db7beb64eaa2f3a37f1fe&v=4
- url: https://github.com/TheJumpyWizard
-- login: mbroton
+ avatarUrl: https://avatars.githubusercontent.com/u/371014?v=4
+ url: https://github.com/clemens-tolboom
+- login: williamjamir
+ count: 4
+ avatarUrl: https://avatars.githubusercontent.com/u/5083518?u=b76ca8e08b906a86fa195fb817dd94e8d9d3d8f6&v=4
+ url: https://github.com/williamjamir
+- login: nymous
count: 3
- avatarUrl: https://avatars.githubusercontent.com/u/50829834?u=a48610bf1bffaa9c75d03228926e2eb08a2e24ee&v=4
- url: https://github.com/mbroton
-- login: mateoradman
+ avatarUrl: https://avatars.githubusercontent.com/u/4216559?u=360a36fb602cded27273cbfc0afc296eece90662&v=4
+ url: https://github.com/nymous
+- login: frankie567
count: 3
- avatarUrl: https://avatars.githubusercontent.com/u/48420316?u=066f36b8e8e263b0d90798113b0f291d3266db7c&v=4
- url: https://github.com/mateoradman
+ avatarUrl: https://avatars.githubusercontent.com/u/1144727?u=85c025e3fcc7bd79a5665c63ee87cdf8aae13374&v=4
+ url: https://github.com/frankie567
top_contributors:
- login: waynerv
count: 25
@@ -239,6 +243,10 @@ top_contributors:
count: 22
avatarUrl: https://avatars.githubusercontent.com/u/41147016?u=55010621aece725aa702270b54fed829b6a1fe60&v=4
url: https://github.com/tokusumi
+- login: Kludex
+ count: 17
+ avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4
+ url: https://github.com/Kludex
- login: jaystone776
count: 17
avatarUrl: https://avatars.githubusercontent.com/u/11191137?u=299205a95e9b6817a43144a48b643346a5aac5cc&v=4
@@ -247,10 +255,6 @@ top_contributors:
count: 16
avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=58ed2a45798a4339700e2f62b2e12e6e54bf0396&v=4
url: https://github.com/dmontagu
-- login: Kludex
- count: 15
- avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4
- url: https://github.com/Kludex
- login: euri10
count: 13
avatarUrl: https://avatars.githubusercontent.com/u/1104190?u=321a2e953e6645a7d09b732786c7a8061e0f8a8b&v=4
@@ -269,7 +273,7 @@ top_contributors:
url: https://github.com/Serrones
- login: RunningIkkyu
count: 7
- avatarUrl: https://avatars.githubusercontent.com/u/31848542?u=efb5b45b55584450507834f279ce48d4d64dea2f&v=4
+ avatarUrl: https://avatars.githubusercontent.com/u/31848542?u=494ecc298e3f26197495bb357ad0f57cfd5f7a32&v=4
url: https://github.com/RunningIkkyu
- login: hard-coders
count: 7
@@ -279,6 +283,10 @@ top_contributors:
count: 7
avatarUrl: https://avatars.githubusercontent.com/u/56785022?u=d5c3a02567c8649e146fcfc51b6060ccaf8adef8&v=4
url: https://github.com/rjNemo
+- login: batlopes
+ count: 6
+ avatarUrl: https://avatars.githubusercontent.com/u/33462923?u=0fb3d7acb316764616f11e4947faf080e49ad8d9&v=4
+ url: https://github.com/batlopes
- login: wshayes
count: 5
avatarUrl: https://avatars.githubusercontent.com/u/365303?u=07ca03c5ee811eb0920e633cc3c3db73dbec1aa5&v=4
@@ -295,10 +303,14 @@ top_contributors:
count: 5
avatarUrl: https://avatars.githubusercontent.com/u/43503750?u=f440bc9062afb3c43b9b9c6cdfdcfe31d58699ef&v=4
url: https://github.com/ComicShrimp
-- login: batlopes
+- login: NinaHwang
count: 5
- avatarUrl: https://avatars.githubusercontent.com/u/33462923?u=0fb3d7acb316764616f11e4947faf080e49ad8d9&v=4
- url: https://github.com/batlopes
+ avatarUrl: https://avatars.githubusercontent.com/u/79563565?u=eee6bfe9224c71193025ab7477f4f96ceaa05c62&v=4
+ url: https://github.com/NinaHwang
+- login: Xewus
+ count: 5
+ avatarUrl: https://avatars.githubusercontent.com/u/85196001?u=f8e2dc7e5104f109cef944af79050ea8d1b8f914&v=4
+ url: https://github.com/Xewus
- login: jekirl
count: 4
avatarUrl: https://avatars.githubusercontent.com/u/2546697?u=a027452387d85bd4a14834e19d716c99255fb3b7&v=4
@@ -327,25 +339,21 @@ top_contributors:
count: 4
avatarUrl: https://avatars.githubusercontent.com/u/61513630?u=320e43fe4dc7bc6efc64e9b8f325f8075634fd20&v=4
url: https://github.com/lsglucas
-- login: NinaHwang
- count: 4
- avatarUrl: https://avatars.githubusercontent.com/u/79563565?u=1741703bd6c8f491503354b363a86e879b4c1cab&v=4
- url: https://github.com/NinaHwang
top_reviewers:
- login: Kludex
- count: 109
+ count: 111
avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4
url: https://github.com/Kludex
- login: BilalAlpaslan
- count: 70
+ count: 75
avatarUrl: https://avatars.githubusercontent.com/u/47563997?u=63ed66e304fe8d765762c70587d61d9196e5c82d&v=4
url: https://github.com/BilalAlpaslan
- login: yezz123
- count: 59
+ count: 71
avatarUrl: https://avatars.githubusercontent.com/u/52716203?u=636b4f79645176df4527dd45c12d5dbb5a4193cf&v=4
url: https://github.com/yezz123
- login: tokusumi
- count: 50
+ count: 51
avatarUrl: https://avatars.githubusercontent.com/u/41147016?u=55010621aece725aa702270b54fed829b6a1fe60&v=4
url: https://github.com/tokusumi
- login: waynerv
@@ -360,6 +368,10 @@ top_reviewers:
count: 45
avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=bba5af018423a2858d49309bed2a899bb5c34ac5&v=4
url: https://github.com/ycd
+- login: iudeen
+ count: 44
+ avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4
+ url: https://github.com/iudeen
- login: cikay
count: 41
avatarUrl: https://avatars.githubusercontent.com/u/24587499?u=e772190a051ab0eaa9c8542fcff1892471638f2b&v=4
@@ -372,22 +384,18 @@ top_reviewers:
count: 33
avatarUrl: https://avatars.githubusercontent.com/u/1024932?u=b2ea249c6b41ddf98679c8d110d0f67d4a3ebf93&v=4
url: https://github.com/AdrianDeAnda
-- login: iudeen
- count: 33
- avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4
- url: https://github.com/iudeen
- login: ArcLightSlavik
count: 31
avatarUrl: https://avatars.githubusercontent.com/u/31127044?u=b0f2c37142f4b762e41ad65dc49581813422bd71&v=4
url: https://github.com/ArcLightSlavik
+- login: cassiobotaro
+ count: 28
+ avatarUrl: https://avatars.githubusercontent.com/u/3127847?u=b0a652331da17efeb85cd6e3a4969182e5004804&v=4
+ url: https://github.com/cassiobotaro
- login: komtaki
count: 27
avatarUrl: https://avatars.githubusercontent.com/u/39375566?u=260ad6b1a4b34c07dbfa728da5e586f16f6d1824&v=4
url: https://github.com/komtaki
-- login: cassiobotaro
- count: 26
- avatarUrl: https://avatars.githubusercontent.com/u/3127847?u=b0a652331da17efeb85cd6e3a4969182e5004804&v=4
- url: https://github.com/cassiobotaro
- login: lsglucas
count: 26
avatarUrl: https://avatars.githubusercontent.com/u/61513630?u=320e43fe4dc7bc6efc64e9b8f325f8075634fd20&v=4
@@ -396,6 +404,14 @@ top_reviewers:
count: 23
avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=58ed2a45798a4339700e2f62b2e12e6e54bf0396&v=4
url: https://github.com/dmontagu
+- login: LorhanSohaky
+ count: 22
+ avatarUrl: https://avatars.githubusercontent.com/u/16273730?u=095b66f243a2cd6a0aadba9a095009f8aaf18393&v=4
+ url: https://github.com/LorhanSohaky
+- login: rjNemo
+ count: 20
+ avatarUrl: https://avatars.githubusercontent.com/u/56785022?u=d5c3a02567c8649e146fcfc51b6060ccaf8adef8&v=4
+ url: https://github.com/rjNemo
- login: hard-coders
count: 20
avatarUrl: https://avatars.githubusercontent.com/u/9651103?u=95db33927bbff1ed1c07efddeb97ac2ff33068ed&v=4
@@ -404,10 +420,10 @@ top_reviewers:
count: 19
avatarUrl: https://avatars.githubusercontent.com/u/63915557?u=47debaa860fd52c9b98c97ef357ddcec3b3fb399&v=4
url: https://github.com/0417taehyun
-- login: rjNemo
- count: 17
- avatarUrl: https://avatars.githubusercontent.com/u/56785022?u=d5c3a02567c8649e146fcfc51b6060ccaf8adef8&v=4
- url: https://github.com/rjNemo
+- login: odiseo0
+ count: 19
+ avatarUrl: https://avatars.githubusercontent.com/u/87550035?u=16f9255804161c6ff3c8b7ef69848f0126bcd405&v=4
+ url: https://github.com/odiseo0
- login: Smlep
count: 17
avatarUrl: https://avatars.githubusercontent.com/u/16785985?v=4
@@ -436,22 +452,26 @@ top_reviewers:
count: 15
avatarUrl: https://avatars.githubusercontent.com/u/63476957?u=6c86e59b48e0394d4db230f37fc9ad4d7e2c27c7&v=4
url: https://github.com/delhi09
-- login: odiseo0
+- login: Ryandaydev
count: 15
- avatarUrl: https://avatars.githubusercontent.com/u/87550035?u=16f9255804161c6ff3c8b7ef69848f0126bcd405&v=4
- url: https://github.com/odiseo0
+ avatarUrl: https://avatars.githubusercontent.com/u/4292423?u=809f3d1074d04bbc28012a7f17f06ea56f5bd71a&v=4
+ url: https://github.com/Ryandaydev
+- login: Xewus
+ count: 14
+ avatarUrl: https://avatars.githubusercontent.com/u/85196001?u=f8e2dc7e5104f109cef944af79050ea8d1b8f914&v=4
+ url: https://github.com/Xewus
- login: sh0nk
count: 13
avatarUrl: https://avatars.githubusercontent.com/u/6478810?u=af15d724875cec682ed8088a86d36b2798f981c0&v=4
url: https://github.com/sh0nk
+- login: peidrao
+ count: 13
+ avatarUrl: https://avatars.githubusercontent.com/u/32584628?u=5401640e0b961cc199dee39ec79e162c7833cd6b&v=4
+ url: https://github.com/peidrao
- login: RunningIkkyu
count: 12
- avatarUrl: https://avatars.githubusercontent.com/u/31848542?u=efb5b45b55584450507834f279ce48d4d64dea2f&v=4
+ avatarUrl: https://avatars.githubusercontent.com/u/31848542?u=494ecc298e3f26197495bb357ad0f57cfd5f7a32&v=4
url: https://github.com/RunningIkkyu
-- login: LorhanSohaky
- count: 11
- avatarUrl: https://avatars.githubusercontent.com/u/16273730?u=095b66f243a2cd6a0aadba9a095009f8aaf18393&v=4
- url: https://github.com/LorhanSohaky
- login: solomein-sv
count: 11
avatarUrl: https://avatars.githubusercontent.com/u/46193920?u=46acfb4aeefb1d7b9fdc5a8cbd9eb8744683c47a&v=4
@@ -472,10 +492,10 @@ top_reviewers:
count: 10
avatarUrl: https://avatars.githubusercontent.com/u/43503750?u=f440bc9062afb3c43b9b9c6cdfdcfe31d58699ef&v=4
url: https://github.com/ComicShrimp
-- login: peidrao
+- login: r0b2g1t
count: 10
- avatarUrl: https://avatars.githubusercontent.com/u/32584628?u=88c2cb42a99e0f50cdeae3606992568184783ee5&v=4
- url: https://github.com/peidrao
+ avatarUrl: https://avatars.githubusercontent.com/u/5357541?u=6428442d875d5d71aaa1bb38bb11c4be1a526bc2&v=4
+ url: https://github.com/r0b2g1t
- login: izaguerreiro
count: 9
avatarUrl: https://avatars.githubusercontent.com/u/2241504?v=4
@@ -496,10 +516,18 @@ top_reviewers:
count: 9
avatarUrl: https://avatars.githubusercontent.com/u/69092910?u=4ac58eab99bd37d663f3d23551df96d4fbdbf760&v=4
url: https://github.com/bezaca
+- login: dimaqq
+ count: 9
+ avatarUrl: https://avatars.githubusercontent.com/u/662249?v=4
+ url: https://github.com/dimaqq
- login: raphaelauv
count: 8
avatarUrl: https://avatars.githubusercontent.com/u/10202690?u=e6f86f5c0c3026a15d6b51792fa3e532b12f1371&v=4
url: https://github.com/raphaelauv
+- login: axel584
+ count: 8
+ avatarUrl: https://avatars.githubusercontent.com/u/1334088?v=4
+ url: https://github.com/axel584
- login: blt232018
count: 8
avatarUrl: https://avatars.githubusercontent.com/u/43393471?u=172b0e0391db1aa6c1706498d6dfcb003c8a4857&v=4
@@ -508,23 +536,3 @@ top_reviewers:
count: 8
avatarUrl: https://avatars.githubusercontent.com/u/5690226?v=4
url: https://github.com/rogerbrinkmann
-- login: NinaHwang
- count: 8
- avatarUrl: https://avatars.githubusercontent.com/u/79563565?u=1741703bd6c8f491503354b363a86e879b4c1cab&v=4
- url: https://github.com/NinaHwang
-- login: dimaqq
- count: 8
- avatarUrl: https://avatars.githubusercontent.com/u/662249?v=4
- url: https://github.com/dimaqq
-- login: Xewus
- count: 8
- avatarUrl: https://avatars.githubusercontent.com/u/85196001?u=4bdd4a0300530a504987db27488ba79c37f2fb18&v=4
- url: https://github.com/Xewus
-- login: Serrones
- count: 7
- avatarUrl: https://avatars.githubusercontent.com/u/22691749?u=4795b880e13ca33a73e52fc0ef7dc9c60c8fce47&v=4
- url: https://github.com/Serrones
-- login: jovicon
- count: 7
- avatarUrl: https://avatars.githubusercontent.com/u/21287303?u=b049eac3e51a4c0473c2efe66b4d28a7d8f2b572&v=4
- url: https://github.com/jovicon
diff --git a/docs/en/data/sponsors.yml b/docs/en/data/sponsors.yml
index 749f528c5..6e81e4890 100644
--- a/docs/en/data/sponsors.yml
+++ b/docs/en/data/sponsors.yml
@@ -1,16 +1,7 @@
gold:
- - url: https://bit.ly/3dmXC5S
- title: The data structure for unstructured multimodal data
- img: https://fastapi.tiangolo.com/img/sponsors/docarray.svg
- - url: https://bit.ly/3JJ7y5C
- title: Build cross-modal and multimodal applications on the cloud
- img: https://fastapi.tiangolo.com/img/sponsors/jina2.svg
- url: https://cryptapi.io/
title: "CryptAPI: Your easy to use, secure and privacy oriented payment gateway."
img: https://fastapi.tiangolo.com/img/sponsors/cryptapi.svg
- - url: https://doist.com/careers/9B437B1615-wa-senior-backend-engineer-python
- title: Help us migrate doist to FastAPI
- img: https://fastapi.tiangolo.com/img/sponsors/doist.svg
silver:
- url: https://www.deta.sh/?ref=fastapi
title: The launchpad for all your (team's) ideas
@@ -27,16 +18,16 @@ silver:
- url: https://github.com/deepset-ai/haystack/
title: Build powerful search from composable, open source building blocks
img: https://fastapi.tiangolo.com/img/sponsors/haystack-fastapi.svg
- - url: https://www.udemy.com/course/fastapi-rest/
- title: Learn FastAPI by building a complete project. Extend your knowledge on advanced web development-AWS, Payments, Emails.
- img: https://fastapi.tiangolo.com/img/sponsors/ines-course.jpg
- - url: https://careers.budget-insight.com/
- title: Budget Insight is hiring!
- img: https://fastapi.tiangolo.com/img/sponsors/budget-insight.svg
+ - url: https://careers.powens.com/
+ title: Powens is hiring!
+ img: https://fastapi.tiangolo.com/img/sponsors/powens.png
+ - url: https://www.svix.com/
+ title: Svix - Webhooks as a service
+ img: https://fastapi.tiangolo.com/img/sponsors/svix.svg
+ - url: https://databento.com/
+ title: Pay as you go for market data
+ img: https://fastapi.tiangolo.com/img/sponsors/databento.svg
bronze:
- url: https://www.exoflare.com/open-source/?utm_source=FastAPI&utm_campaign=open_source
title: Biosecurity risk assessments made easy.
img: https://fastapi.tiangolo.com/img/sponsors/exoflare.png
- - url: https://bit.ly/3ccLCmM
- title: https://striveworks.us/careers
- img: https://fastapi.tiangolo.com/img/sponsors/striveworks2.png
diff --git a/docs/en/data/sponsors_badge.yml b/docs/en/data/sponsors_badge.yml
index a8bfb0b1b..a95af177c 100644
--- a/docs/en/data/sponsors_badge.yml
+++ b/docs/en/data/sponsors_badge.yml
@@ -5,11 +5,13 @@ logins:
- mikeckennedy
- deepset-ai
- cryptapi
- - Striveworks
- xoflare
- - InesIvanova
- DropbaseHQ
- VincentParedes
- BLUE-DEVIL1134
- ObliviousAI
- Doist
+ - nihpo
+ - svix
+ - armand-sauzay
+ - databento-bot
diff --git a/docs/en/docs/advanced/additional-status-codes.md b/docs/en/docs/advanced/additional-status-codes.md
index b61f88b93..416444d3b 100644
--- a/docs/en/docs/advanced/additional-status-codes.md
+++ b/docs/en/docs/advanced/additional-status-codes.md
@@ -14,9 +14,41 @@ But you also want it to accept new items. And when the items didn't exist before
To achieve that, import `JSONResponse`, and return your content there directly, setting the `status_code` that you want:
-```Python hl_lines="4 25"
-{!../../../docs_src/additional_status_codes/tutorial001.py!}
-```
+=== "Python 3.10+"
+
+ ```Python hl_lines="4 25"
+ {!> ../../../docs_src/additional_status_codes/tutorial001_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="4 25"
+ {!> ../../../docs_src/additional_status_codes/tutorial001_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="4 26"
+ {!> ../../../docs_src/additional_status_codes/tutorial001_an.py!}
+ ```
+
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="2 23"
+ {!> ../../../docs_src/additional_status_codes/tutorial001_py310.py!}
+ ```
+
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="4 25"
+ {!> ../../../docs_src/additional_status_codes/tutorial001.py!}
+ ```
!!! warning
When you return a `Response` directly, like in the example above, it will be returned directly.
diff --git a/docs/en/docs/advanced/advanced-dependencies.md b/docs/en/docs/advanced/advanced-dependencies.md
index 5e79776ca..402c5d755 100644
--- a/docs/en/docs/advanced/advanced-dependencies.md
+++ b/docs/en/docs/advanced/advanced-dependencies.md
@@ -18,9 +18,26 @@ Not the class itself (which is already a callable), but an instance of that clas
To do that, we declare a method `__call__`:
-```Python hl_lines="10"
-{!../../../docs_src/dependencies/tutorial011.py!}
-```
+=== "Python 3.9+"
+
+ ```Python hl_lines="12"
+ {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="11"
+ {!> ../../../docs_src/dependencies/tutorial011_an.py!}
+ ```
+
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="10"
+ {!> ../../../docs_src/dependencies/tutorial011.py!}
+ ```
In this case, this `__call__` is what **FastAPI** will use to check for additional parameters and sub-dependencies, and this is what will be called to pass a value to the parameter in your *path operation function* later.
@@ -28,9 +45,26 @@ In this case, this `__call__` is what **FastAPI** will use to check for addition
And now, we can use `__init__` to declare the parameters of the instance that we can use to "parameterize" the dependency:
-```Python hl_lines="7"
-{!../../../docs_src/dependencies/tutorial011.py!}
-```
+=== "Python 3.9+"
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="8"
+ {!> ../../../docs_src/dependencies/tutorial011_an.py!}
+ ```
+
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="7"
+ {!> ../../../docs_src/dependencies/tutorial011.py!}
+ ```
In this case, **FastAPI** won't ever touch or care about `__init__`, we will use it directly in our code.
@@ -38,9 +72,26 @@ In this case, **FastAPI** won't ever touch or care about `__init__`, we will use
We could create an instance of this class with:
-```Python hl_lines="16"
-{!../../../docs_src/dependencies/tutorial011.py!}
-```
+=== "Python 3.9+"
+
+ ```Python hl_lines="18"
+ {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="17"
+ {!> ../../../docs_src/dependencies/tutorial011_an.py!}
+ ```
+
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="16"
+ {!> ../../../docs_src/dependencies/tutorial011.py!}
+ ```
And that way we are able to "parameterize" our dependency, that now has `"bar"` inside of it, as the attribute `checker.fixed_content`.
@@ -56,9 +107,26 @@ checker(q="somequery")
...and pass whatever that returns as the value of the dependency in our *path operation function* as the parameter `fixed_content_included`:
-```Python hl_lines="20"
-{!../../../docs_src/dependencies/tutorial011.py!}
-```
+=== "Python 3.9+"
+
+ ```Python hl_lines="22"
+ {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="21"
+ {!> ../../../docs_src/dependencies/tutorial011_an.py!}
+ ```
+
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="20"
+ {!> ../../../docs_src/dependencies/tutorial011.py!}
+ ```
!!! tip
All this might seem contrived. And it might not be very clear how is it useful yet.
diff --git a/docs/en/docs/advanced/behind-a-proxy.md b/docs/en/docs/advanced/behind-a-proxy.md
index 766a218aa..03198851a 100644
--- a/docs/en/docs/advanced/behind-a-proxy.md
+++ b/docs/en/docs/advanced/behind-a-proxy.md
@@ -251,7 +251,7 @@ We get the same response:
but this time at the URL with the prefix path provided by the proxy: `/api/v1`.
-Of course, the idea here is that everyone would access the app through the proxy, so the version with the path prefix `/app/v1` is the "correct" one.
+Of course, the idea here is that everyone would access the app through the proxy, so the version with the path prefix `/api/v1` is the "correct" one.
And the version without the path prefix (`http://127.0.0.1:8000/app`), provided by Uvicorn directly, would be exclusively for the _proxy_ (Traefik) to access it.
diff --git a/docs/en/docs/advanced/events.md b/docs/en/docs/advanced/events.md
index 7cd2998f0..6b7de4130 100644
--- a/docs/en/docs/advanced/events.md
+++ b/docs/en/docs/advanced/events.md
@@ -1,13 +1,108 @@
-# Events: startup - shutdown
+# Lifespan Events
-You can define event handlers (functions) that need to be executed before the application starts up, or when the application is shutting down.
+You can define logic (code) that should be executed before the application **starts up**. This means that this code will be executed **once**, **before** the application **starts receiving requests**.
-These functions can be declared with `async def` or normal `def`.
+The same way, you can define logic (code) that should be executed when the application is **shutting down**. In this case, this code will be executed **once**, **after** having handled possibly **many requests**.
+
+Because this code is executed before the application **starts** taking requests, and right after it **finishes** handling requests, it covers the whole application **lifespan** (the word "lifespan" will be important in a second 😉).
+
+This can be very useful for setting up **resources** that you need to use for the whole app, and that are **shared** among requests, and/or that you need to **clean up** afterwards. For example, a database connection pool, or loading a shared machine learning model.
+
+## Use Case
+
+Let's start with an example **use case** and then see how to solve it with this.
+
+Let's imagine that you have some **machine learning models** that you want to use to handle requests. 🤖
+
+The same models are shared among requests, so, it's not one model per request, or one per user or something similar.
+
+Let's imagine that loading the model can **take quite some time**, because it has to read a lot of **data from disk**. So you don't want to do it for every request.
+
+You could load it at the top level of the module/file, but that would also mean that it would **load the model** even if you are just running a simple automated test, then that test would be **slow** because it would have to wait for the model to load before being able to run an independent part of the code.
+
+That's what we'll solve, let's load the model before the requests are handled, but only right before the application starts receiving requests, not while the code is being loaded.
+
+## Lifespan
+
+You can define this *startup* and *shutdown* logic using the `lifespan` parameter of the `FastAPI` app, and a "context manager" (I'll show you what that is in a second).
+
+Let's start with an example and then see it in detail.
+
+We create an async function `lifespan()` with `yield` like this:
+
+```Python hl_lines="16 19"
+{!../../../docs_src/events/tutorial003.py!}
+```
+
+Here we are simulating the expensive *startup* operation of loading the model by putting the (fake) model function in the dictionary with machine learning models before the `yield`. This code will be executed **before** the application **starts taking requests**, during the *startup*.
+
+And then, right after the `yield`, we unload the model. This code will be executed **after** the application **finishes handling requests**, right before the *shutdown*. This could, for example, release resources like memory or a GPU.
+
+!!! tip
+ The `shutdown` would happen when you are **stopping** the application.
+
+ Maybe you need to start a new version, or you just got tired of running it. 🤷
+
+### Lifespan function
+
+The first thing to notice, is that we are defining an async function with `yield`. This is very similar to Dependencies with `yield`.
+
+```Python hl_lines="14-19"
+{!../../../docs_src/events/tutorial003.py!}
+```
+
+The first part of the function, before the `yield`, will be executed **before** the application starts.
+
+And the part after the `yield` will be executed **after** the application has finished.
+
+### Async Context Manager
+
+If you check, the function is decorated with an `@asynccontextmanager`.
+
+That converts the function into something called an "**async context manager**".
+
+```Python hl_lines="1 13"
+{!../../../docs_src/events/tutorial003.py!}
+```
+
+A **context manager** in Python is something that you can use in a `with` statement, for example, `open()` can be used as a context manager:
+
+```Python
+with open("file.txt") as file:
+ file.read()
+```
+
+In recent versions of Python, there's also an **async context manager**. You would use it with `async with`:
+
+```Python
+async with lifespan(app):
+ await do_stuff()
+```
+
+When you create a context manager or an async context manager like above, what it does is that, before entering the `with` block, it will execute the code before the `yield`, and after exiting the `with` block, it will execute the code after the `yield`.
+
+In our code example above, we don't use it directly, but we pass it to FastAPI for it to use it.
+
+The `lifespan` parameter of the `FastAPI` app takes an **async context manager**, so we can pass our new `lifespan` async context manager to it.
+
+```Python hl_lines="22"
+{!../../../docs_src/events/tutorial003.py!}
+```
+
+## Alternative Events (deprecated)
!!! warning
- Only event handlers for the main application will be executed, not for [Sub Applications - Mounts](./sub-applications.md){.internal-link target=_blank}.
+ The recommended way to handle the *startup* and *shutdown* is using the `lifespan` parameter of the `FastAPI` app as described above.
+
+ You can probably skip this part.
-## `startup` event
+There's an alternative way to define this logic to be executed during *startup* and during *shutdown*.
+
+You can define event handlers (functions) that need to be executed before the application starts up, or when the application is shutting down.
+
+These functions can be declared with `async def` or normal `def`.
+
+### `startup` event
To add a function that should be run before the application starts, declare it with the event `"startup"`:
@@ -21,7 +116,7 @@ You can add more than one event handler function.
And your application won't start receiving requests until all the `startup` event handlers have completed.
-## `shutdown` event
+### `shutdown` event
To add a function that should be run when the application is shutting down, declare it with the event `"shutdown"`:
@@ -43,5 +138,25 @@ Here, the `shutdown` event handler function will write a text line `"Application
So, we declare the event handler function with standard `def` instead of `async def`.
+### `startup` and `shutdown` together
+
+There's a high chance that the logic for your *startup* and *shutdown* is connected, you might want to start something and then finish it, acquire a resource and then release it, etc.
+
+Doing that in separated functions that don't share logic or variables together is more difficult as you would need to store values in global variables or similar tricks.
+
+Because of that, it's now recommended to instead use the `lifespan` as explained above.
+
+## Technical Details
+
+Just a technical detail for the curious nerds. 🤓
+
+Underneath, in the ASGI technical specification, this is part of the Lifespan Protocol, and it defines events called `startup` and `shutdown`.
+
!!! info
- You can read more about these event handlers in Starlette's Events' docs.
+ You can read more about the Starlette `lifespan` handlers in Starlette's Lifespan' docs.
+
+ Including how to handle lifespan state that can be used in other areas of your code.
+
+## Sub Applications
+
+🚨 Have in mind that these lifespan events (startup and shutdown) will only be executed for the main application, not for [Sub Applications - Mounts](./sub-applications.md){.internal-link target=_blank}.
diff --git a/docs/en/docs/advanced/generate-clients.md b/docs/en/docs/advanced/generate-clients.md
index f31a248d0..f62c0b57c 100644
--- a/docs/en/docs/advanced/generate-clients.md
+++ b/docs/en/docs/advanced/generate-clients.md
@@ -16,16 +16,16 @@ If you are building a **frontend**, a very interesting alternative is ../../../docs_src/generate_clients/tutorial001.py!}
+ ```Python hl_lines="7-9 12-13 16-17 21"
+ {!> ../../../docs_src/generate_clients/tutorial001_py39.py!}
```
-=== "Python 3.9 and above"
+=== "Python 3.6+"
- ```Python hl_lines="7-9 12-13 16-17 21"
- {!> ../../../docs_src/generate_clients/tutorial001_py39.py!}
+ ```Python hl_lines="9-11 14-15 18 19 23"
+ {!> ../../../docs_src/generate_clients/tutorial001.py!}
```
Notice that the *path operations* define the models they use for request payload and response payload, using the models `Item` and `ResponseMessage`.
@@ -128,17 +128,16 @@ In many cases your FastAPI app will be bigger, and you will probably use tags to
For example, you could have a section for **items** and another section for **users**, and they could be separated by tags:
+=== "Python 3.9+"
-=== "Python 3.6 and above"
-
- ```Python hl_lines="23 28 36"
- {!> ../../../docs_src/generate_clients/tutorial002.py!}
+ ```Python hl_lines="21 26 34"
+ {!> ../../../docs_src/generate_clients/tutorial002_py39.py!}
```
-=== "Python 3.9 and above"
+=== "Python 3.6+"
- ```Python hl_lines="21 26 34"
- {!> ../../../docs_src/generate_clients/tutorial002_py39.py!}
+ ```Python hl_lines="23 28 36"
+ {!> ../../../docs_src/generate_clients/tutorial002.py!}
```
### Generate a TypeScript Client with Tags
@@ -186,16 +185,16 @@ For example, here it is using the first tag (you will probably have only one tag
You can then pass that custom function to **FastAPI** as the `generate_unique_id_function` parameter:
-=== "Python 3.6 and above"
+=== "Python 3.9+"
- ```Python hl_lines="8-9 12"
- {!> ../../../docs_src/generate_clients/tutorial003.py!}
+ ```Python hl_lines="6-7 10"
+ {!> ../../../docs_src/generate_clients/tutorial003_py39.py!}
```
-=== "Python 3.9 and above"
+=== "Python 3.6+"
- ```Python hl_lines="6-7 10"
- {!> ../../../docs_src/generate_clients/tutorial003_py39.py!}
+ ```Python hl_lines="8-9 12"
+ {!> ../../../docs_src/generate_clients/tutorial003.py!}
```
### Generate a TypeScript Client with Custom Operation IDs
diff --git a/docs/en/docs/advanced/middleware.md b/docs/en/docs/advanced/middleware.md
index 3bf49e392..9219f1d2c 100644
--- a/docs/en/docs/advanced/middleware.md
+++ b/docs/en/docs/advanced/middleware.md
@@ -92,7 +92,7 @@ There are many other ASGI middlewares.
For example:
-* Sentry
+* Sentry
* Uvicorn's `ProxyHeadersMiddleware`
* MessagePack
diff --git a/docs/en/docs/advanced/security/http-basic-auth.md b/docs/en/docs/advanced/security/http-basic-auth.md
index 90c516808..8177a4b28 100644
--- a/docs/en/docs/advanced/security/http-basic-auth.md
+++ b/docs/en/docs/advanced/security/http-basic-auth.md
@@ -20,9 +20,26 @@ Then, when you type that username and password, the browser sends them in the he
* It returns an object of type `HTTPBasicCredentials`:
* It contains the `username` and `password` sent.
-```Python hl_lines="2 6 10"
-{!../../../docs_src/security/tutorial006.py!}
-```
+=== "Python 3.9+"
+
+ ```Python hl_lines="4 8 12"
+ {!> ../../../docs_src/security/tutorial006_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="2 7 11"
+ {!> ../../../docs_src/security/tutorial006_an.py!}
+ ```
+
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="2 6 10"
+ {!> ../../../docs_src/security/tutorial006.py!}
+ ```
When you try to open the URL for the first time (or click the "Execute" button in the docs) the browser will ask you for your username and password:
@@ -42,9 +59,26 @@ To handle that, we first convert the `username` and `password` to `bytes` encodi
Then we can use `secrets.compare_digest()` to ensure that `credentials.username` is `"stanleyjobson"`, and that `credentials.password` is `"swordfish"`.
-```Python hl_lines="1 11-21"
-{!../../../docs_src/security/tutorial007.py!}
-```
+=== "Python 3.9+"
+
+ ```Python hl_lines="1 12-24"
+ {!> ../../../docs_src/security/tutorial007_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="1 12-24"
+ {!> ../../../docs_src/security/tutorial007_an.py!}
+ ```
+
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="1 11-21"
+ {!> ../../../docs_src/security/tutorial007.py!}
+ ```
This would be similar to:
@@ -108,6 +142,23 @@ 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="23-27"
-{!../../../docs_src/security/tutorial007.py!}
-```
+=== "Python 3.9+"
+
+ ```Python hl_lines="26-30"
+ {!> ../../../docs_src/security/tutorial007_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="26-30"
+ {!> ../../../docs_src/security/tutorial007_an.py!}
+ ```
+
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="23-27"
+ {!> ../../../docs_src/security/tutorial007.py!}
+ ```
diff --git a/docs/en/docs/advanced/security/oauth2-scopes.md b/docs/en/docs/advanced/security/oauth2-scopes.md
index be51325cd..41cd61683 100644
--- a/docs/en/docs/advanced/security/oauth2-scopes.md
+++ b/docs/en/docs/advanced/security/oauth2-scopes.md
@@ -56,9 +56,50 @@ They are normally used to declare specific security permissions, for example:
First, let's quickly see the parts that change from the examples in the main **Tutorial - User Guide** for [OAuth2 with Password (and hashing), Bearer with JWT tokens](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. Now using OAuth2 scopes:
-```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 153"
-{!../../../docs_src/security/tutorial005.py!}
-```
+=== "Python 3.10+"
+
+ ```Python hl_lines="4 8 12 46 64 105 107-115 121-124 128-134 139 155"
+ {!> ../../../docs_src/security/tutorial005_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155"
+ {!> ../../../docs_src/security/tutorial005_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="2 4 8 12 47 65 106 108-116 122-125 129-135 140 156"
+ {!> ../../../docs_src/security/tutorial005_an.py!}
+ ```
+
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="3 7 11 45 63 104 106-114 120-123 127-133 138 152"
+ {!> ../../../docs_src/security/tutorial005_py310.py!}
+ ```
+
+=== "Python 3.9+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 153"
+ {!> ../../../docs_src/security/tutorial005_py39.py!}
+ ```
+
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 153"
+ {!> ../../../docs_src/security/tutorial005.py!}
+ ```
Now let's review those changes step by step.
@@ -68,9 +109,51 @@ The first change is that now we are declaring the OAuth2 security scheme with tw
The `scopes` parameter receives a `dict` with each scope as a key and the description as the value:
-```Python hl_lines="62-65"
-{!../../../docs_src/security/tutorial005.py!}
-```
+=== "Python 3.10+"
+
+ ```Python hl_lines="62-65"
+ {!> ../../../docs_src/security/tutorial005_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="62-65"
+ {!> ../../../docs_src/security/tutorial005_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="63-66"
+ {!> ../../../docs_src/security/tutorial005_an.py!}
+ ```
+
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="61-64"
+ {!> ../../../docs_src/security/tutorial005_py310.py!}
+ ```
+
+
+=== "Python 3.9+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="62-65"
+ {!> ../../../docs_src/security/tutorial005_py39.py!}
+ ```
+
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="62-65"
+ {!> ../../../docs_src/security/tutorial005.py!}
+ ```
Because we are now declaring those scopes, they will show up in the API docs when you log-in/authorize.
@@ -93,9 +176,50 @@ And we return the scopes as part of the JWT token.
But in your application, for security, you should make sure you only add the scopes that the user is actually able to have, or the ones you have predefined.
-```Python hl_lines="153"
-{!../../../docs_src/security/tutorial005.py!}
-```
+=== "Python 3.10+"
+
+ ```Python hl_lines="155"
+ {!> ../../../docs_src/security/tutorial005_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="155"
+ {!> ../../../docs_src/security/tutorial005_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="156"
+ {!> ../../../docs_src/security/tutorial005_an.py!}
+ ```
+
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="152"
+ {!> ../../../docs_src/security/tutorial005_py310.py!}
+ ```
+
+=== "Python 3.9+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="153"
+ {!> ../../../docs_src/security/tutorial005_py39.py!}
+ ```
+
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="153"
+ {!> ../../../docs_src/security/tutorial005.py!}
+ ```
## Declare scopes in *path operations* and dependencies
@@ -118,9 +242,50 @@ In this case, it requires the scope `me` (it could require more than one scope).
We are doing it here to demonstrate how **FastAPI** handles scopes declared at different levels.
-```Python hl_lines="4 139 166"
-{!../../../docs_src/security/tutorial005.py!}
-```
+=== "Python 3.10+"
+
+ ```Python hl_lines="4 139 170"
+ {!> ../../../docs_src/security/tutorial005_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="4 139 170"
+ {!> ../../../docs_src/security/tutorial005_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="4 140 171"
+ {!> ../../../docs_src/security/tutorial005_an.py!}
+ ```
+
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="3 138 165"
+ {!> ../../../docs_src/security/tutorial005_py310.py!}
+ ```
+
+=== "Python 3.9+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="4 139 166"
+ {!> ../../../docs_src/security/tutorial005_py39.py!}
+ ```
+
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="4 139 166"
+ {!> ../../../docs_src/security/tutorial005.py!}
+ ```
!!! info "Technical Details"
`Security` is actually a subclass of `Depends`, and it has just one extra parameter that we'll see later.
@@ -143,9 +308,50 @@ We also declare a special parameter of type `SecurityScopes`, imported from `fas
This `SecurityScopes` class is similar to `Request` (`Request` was used to get the request object directly).
-```Python hl_lines="8 105"
-{!../../../docs_src/security/tutorial005.py!}
-```
+=== "Python 3.10+"
+
+ ```Python hl_lines="8 105"
+ {!> ../../../docs_src/security/tutorial005_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="8 105"
+ {!> ../../../docs_src/security/tutorial005_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="8 106"
+ {!> ../../../docs_src/security/tutorial005_an.py!}
+ ```
+
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="7 104"
+ {!> ../../../docs_src/security/tutorial005_py310.py!}
+ ```
+
+=== "Python 3.9+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="8 105"
+ {!> ../../../docs_src/security/tutorial005_py39.py!}
+ ```
+
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="8 105"
+ {!> ../../../docs_src/security/tutorial005.py!}
+ ```
## Use the `scopes`
@@ -159,9 +365,50 @@ We create an `HTTPException` that we can re-use (`raise`) later at several point
In this exception, we include the scopes required (if any) as a string separated by spaces (using `scope_str`). We put that string containing the scopes in the `WWW-Authenticate` header (this is part of the spec).
-```Python hl_lines="105 107-115"
-{!../../../docs_src/security/tutorial005.py!}
-```
+=== "Python 3.10+"
+
+ ```Python hl_lines="105 107-115"
+ {!> ../../../docs_src/security/tutorial005_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="105 107-115"
+ {!> ../../../docs_src/security/tutorial005_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="106 108-116"
+ {!> ../../../docs_src/security/tutorial005_an.py!}
+ ```
+
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="104 106-114"
+ {!> ../../../docs_src/security/tutorial005_py310.py!}
+ ```
+
+=== "Python 3.9+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="105 107-115"
+ {!> ../../../docs_src/security/tutorial005_py39.py!}
+ ```
+
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="105 107-115"
+ {!> ../../../docs_src/security/tutorial005.py!}
+ ```
## Verify the `username` and data shape
@@ -177,9 +424,50 @@ Instead of, for example, a `dict`, or something else, as it could break the appl
We also verify that we have a user with that username, and if not, we raise that same exception we created before.
-```Python hl_lines="46 116-127"
-{!../../../docs_src/security/tutorial005.py!}
-```
+=== "Python 3.10+"
+
+ ```Python hl_lines="46 116-127"
+ {!> ../../../docs_src/security/tutorial005_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="46 116-127"
+ {!> ../../../docs_src/security/tutorial005_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="47 117-128"
+ {!> ../../../docs_src/security/tutorial005_an.py!}
+ ```
+
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="45 115-126"
+ {!> ../../../docs_src/security/tutorial005_py310.py!}
+ ```
+
+=== "Python 3.9+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="46 116-127"
+ {!> ../../../docs_src/security/tutorial005_py39.py!}
+ ```
+
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="46 116-127"
+ {!> ../../../docs_src/security/tutorial005.py!}
+ ```
## Verify the `scopes`
@@ -187,9 +475,50 @@ We now verify that all the scopes required, by this dependency and all the depen
For this, we use `security_scopes.scopes`, that contains a `list` with all these scopes as `str`.
-```Python hl_lines="128-134"
-{!../../../docs_src/security/tutorial005.py!}
-```
+=== "Python 3.10+"
+
+ ```Python hl_lines="128-134"
+ {!> ../../../docs_src/security/tutorial005_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="128-134"
+ {!> ../../../docs_src/security/tutorial005_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="129-135"
+ {!> ../../../docs_src/security/tutorial005_an.py!}
+ ```
+
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="127-133"
+ {!> ../../../docs_src/security/tutorial005_py310.py!}
+ ```
+
+=== "Python 3.9+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="128-134"
+ {!> ../../../docs_src/security/tutorial005_py39.py!}
+ ```
+
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="128-134"
+ {!> ../../../docs_src/security/tutorial005.py!}
+ ```
## Dependency tree and scopes
diff --git a/docs/en/docs/advanced/settings.md b/docs/en/docs/advanced/settings.md
index d5151b585..60ec9c92c 100644
--- a/docs/en/docs/advanced/settings.md
+++ b/docs/en/docs/advanced/settings.md
@@ -216,9 +216,26 @@ Notice that now we don't create a default instance `settings = Settings()`.
Now we create a dependency that returns a new `config.Settings()`.
-```Python hl_lines="5 11-12"
-{!../../../docs_src/settings/app02/main.py!}
-```
+=== "Python 3.9+"
+
+ ```Python hl_lines="6 12-13"
+ {!> ../../../docs_src/settings/app02_an_py39/main.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="6 12-13"
+ {!> ../../../docs_src/settings/app02_an/main.py!}
+ ```
+
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="5 11-12"
+ {!> ../../../docs_src/settings/app02/main.py!}
+ ```
!!! tip
We'll discuss the `@lru_cache()` in a bit.
@@ -227,9 +244,26 @@ Now we create a dependency that returns a new `config.Settings()`.
And then we can require it from the *path operation function* as a dependency and use it anywhere we need it.
-```Python hl_lines="16 18-20"
-{!../../../docs_src/settings/app02/main.py!}
-```
+=== "Python 3.9+"
+
+ ```Python hl_lines="17 19-21"
+ {!> ../../../docs_src/settings/app02_an_py39/main.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="17 19-21"
+ {!> ../../../docs_src/settings/app02_an/main.py!}
+ ```
+
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="16 18-20"
+ {!> ../../../docs_src/settings/app02/main.py!}
+ ```
### Settings and testing
@@ -304,9 +338,26 @@ we would create that object for each request, and we would be reading the `.env`
But as we are using the `@lru_cache()` decorator on top, the `Settings` object will be created only once, the first time it's called. ✔️
-```Python hl_lines="1 10"
-{!../../../docs_src/settings/app03/main.py!}
-```
+=== "Python 3.9+"
+
+ ```Python hl_lines="1 11"
+ {!> ../../../docs_src/settings/app03_an_py39/main.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="1 11"
+ {!> ../../../docs_src/settings/app03_an/main.py!}
+ ```
+
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="1 10"
+ {!> ../../../docs_src/settings/app03/main.py!}
+ ```
Then for any subsequent calls of `get_settings()` in the dependencies for the next requests, instead of executing the internal code of `get_settings()` and creating a new `Settings` object, it will return the same object that was returned on the first call, again and again.
diff --git a/docs/en/docs/advanced/testing-dependencies.md b/docs/en/docs/advanced/testing-dependencies.md
index 7bba82fb7..ee48a735d 100644
--- a/docs/en/docs/advanced/testing-dependencies.md
+++ b/docs/en/docs/advanced/testing-dependencies.md
@@ -28,9 +28,41 @@ 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="28-29 32"
-{!../../../docs_src/dependency_testing/tutorial001.py!}
-```
+=== "Python 3.10+"
+
+ ```Python hl_lines="26-27 30"
+ {!> ../../../docs_src/dependency_testing/tutorial001_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="28-29 32"
+ {!> ../../../docs_src/dependency_testing/tutorial001_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="29-30 33"
+ {!> ../../../docs_src/dependency_testing/tutorial001_an.py!}
+ ```
+
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="24-25 28"
+ {!> ../../../docs_src/dependency_testing/tutorial001_py310.py!}
+ ```
+
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="28-29 32"
+ {!> ../../../docs_src/dependency_testing/tutorial001.py!}
+ ```
!!! tip
You can set a dependency override for a dependency used anywhere in your **FastAPI** application.
diff --git a/docs/en/docs/advanced/websockets.md b/docs/en/docs/advanced/websockets.md
index 3cf840819..94cf191d2 100644
--- a/docs/en/docs/advanced/websockets.md
+++ b/docs/en/docs/advanced/websockets.md
@@ -112,9 +112,41 @@ In WebSocket endpoints you can import from `fastapi` and use:
They work the same way as for other FastAPI endpoints/*path operations*:
-```Python hl_lines="66-77 76-91"
-{!../../../docs_src/websockets/tutorial002.py!}
-```
+=== "Python 3.10+"
+
+ ```Python hl_lines="68-69 82"
+ {!> ../../../docs_src/websockets/tutorial002_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="68-69 82"
+ {!> ../../../docs_src/websockets/tutorial002_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="69-70 83"
+ {!> ../../../docs_src/websockets/tutorial002_an.py!}
+ ```
+
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="66-67 79"
+ {!> ../../../docs_src/websockets/tutorial002_py310.py!}
+ ```
+
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="68-69 81"
+ {!> ../../../docs_src/websockets/tutorial002.py!}
+ ```
!!! info
As this is a WebSocket it doesn't really make sense to raise an `HTTPException`, instead we raise a `WebSocketException`.
@@ -153,9 +185,17 @@ With that you can connect the WebSocket and then send and receive messages:
When a WebSocket connection is closed, the `await websocket.receive_text()` will raise a `WebSocketDisconnect` exception, which you can then catch and handle like in this example.
-```Python hl_lines="81-83"
-{!../../../docs_src/websockets/tutorial003.py!}
-```
+=== "Python 3.9+"
+
+ ```Python hl_lines="79-81"
+ {!> ../../../docs_src/websockets/tutorial003_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="81-83"
+ {!> ../../../docs_src/websockets/tutorial003.py!}
+ ```
To try it out:
diff --git a/docs/en/docs/async.md b/docs/en/docs/async.md
index 6f34a9c9c..3d4b1956a 100644
--- a/docs/en/docs/async.md
+++ b/docs/en/docs/async.md
@@ -283,7 +283,7 @@ For example:
### Concurrency + Parallelism: Web + Machine Learning
-With **FastAPI** you can take the advantage of concurrency that is very common for web development (the same main attractive of NodeJS).
+With **FastAPI** you can take the advantage of concurrency that is very common for web development (the same main attraction of NodeJS).
But you can also exploit the benefits of parallelism and multiprocessing (having multiple processes running in parallel) for **CPU bound** workloads like those in Machine Learning systems.
diff --git a/docs/en/docs/contributing.md b/docs/en/docs/contributing.md
index 58a363220..a1a32a1fe 100644
--- a/docs/en/docs/contributing.md
+++ b/docs/en/docs/contributing.md
@@ -108,7 +108,7 @@ After activating the environment as described above:
```console
-$ pip install -e ."[dev,doc,test]"
+$ pip install -e ".[dev,doc,test]"
---> 100%
```
diff --git a/docs/en/docs/deployment/concepts.md b/docs/en/docs/deployment/concepts.md
index 22604ceeb..77419f8b0 100644
--- a/docs/en/docs/deployment/concepts.md
+++ b/docs/en/docs/deployment/concepts.md
@@ -235,7 +235,7 @@ Here are some possible combinations and strategies:
* One Uvicorn **process manager** would listen on the **IP** and **port**, and it would start **multiple Uvicorn worker processes**
* **Kubernetes** and other distributed **container systems**
* Something in the **Kubernetes** layer would listen on the **IP** and **port**. The replication would be by having **multiple containers**, each with **one Uvicorn process** running
-* **Cloud services** that handle this for your
+* **Cloud services** that handle this for you
* The cloud service will probably **handle replication for you**. It would possibly let you define **a process to run**, or a **container image** to use, in any case, it would most probably be **a single Uvicorn process**, and the cloud service would be in charge of replicating it.
!!! tip
diff --git a/docs/en/docs/external-links.md b/docs/en/docs/external-links.md
index 55db55599..0c91470bc 100644
--- a/docs/en/docs/external-links.md
+++ b/docs/en/docs/external-links.md
@@ -56,6 +56,15 @@ Here's an incomplete list of some of them.
{% endfor %}
{% endif %}
+### Taiwanese
+
+{% if external_links %}
+{% for article in external_links.articles.taiwanese %}
+
+* {{ article.title }} by {{ article.author }}.
+{% endfor %}
+{% endif %}
+
## Podcasts
{% if external_links %}
diff --git a/docs/en/docs/fastapi-people.md b/docs/en/docs/fastapi-people.md
index 0cbcb69c9..20caaa1ee 100644
--- a/docs/en/docs/fastapi-people.md
+++ b/docs/en/docs/fastapi-people.md
@@ -28,7 +28,7 @@ I'm the creator and maintainer of **FastAPI**. You can read more about that in [
These are the people that:
-* [Help others with issues (questions) in GitHub](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank}.
+* [Help others with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}.
* [Create Pull Requests](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}.
* Review Pull Requests, [especially important for translations](contributing.md#translations){.internal-link target=_blank}.
@@ -36,13 +36,13 @@ A round of applause to them. 👏 🙇
## Most active users last month
-These are the users that have been [helping others the most with issues (questions) in GitHub](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank} during the last month. ☕
+These are the users that have been [helping others the most with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} during the last month. ☕
{% if people %}
@@ -52,7 +52,7 @@ These are the users that have been [helping others the most with issues (questio
Here are the **FastAPI Experts**. 🤓
-These are the users that have [helped others the most with issues (questions) in GitHub](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank} through *all time*.
+These are the users that have [helped others the most with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} through *all time*.
They have proven to be experts by helping many others. ✨
@@ -60,7 +60,7 @@ They have proven to be experts by helping many others. ✨
@@ -169,7 +169,7 @@ They are supporting my work with **FastAPI** (and others), mainly through source code here.
diff --git a/docs/en/docs/help-fastapi.md b/docs/en/docs/help-fastapi.md
index a7ac9415f..e977dba20 100644
--- a/docs/en/docs/help-fastapi.md
+++ b/docs/en/docs/help-fastapi.md
@@ -69,11 +69,16 @@ I love to hear about how **FastAPI** is being used, what you have liked in it, i
* Vote for **FastAPI** in AlternativeTo.
* Say you use **FastAPI** on StackShare.
-## Help others with issues in GitHub
+## Help others with questions in GitHub
-You can see existing issues and try and help others, most of the times those issues are questions that you might already know the answer for. 🤓
+You can try and help others with their questions in:
-If you are helping a lot of people with issues, you might become an official [FastAPI Expert](fastapi-people.md#experts){.internal-link target=_blank}. 🎉
+* GitHub Discussions
+* GitHub Issues
+
+In many cases you might already know the answer for those questions. 🤓
+
+If you are helping a lot of people with their questions, you will become an official [FastAPI Expert](fastapi-people.md#experts){.internal-link target=_blank}. 🎉
Just remember, the most important point is: try to be kind. People come with their frustrations and in many cases don't ask in the best way, but try as best as you can to be kind. 🤗
@@ -81,7 +86,7 @@ The idea is for the **FastAPI** community to be kind and welcoming. At the same
---
-Here's how to help others with issues:
+Here's how to help others with questions (in discussions or issues):
### Understand the question
@@ -113,24 +118,27 @@ In many cases they will only copy a fragment of the code, but that's not enough
If they reply, there's a high chance you would have solved their problem, congrats, **you're a hero**! 🦸
-* Now you can ask them, if that solved their problem, to **close the issue**.
+* Now, if that solved their problem, you can ask them to:
+
+ * In GitHub Discussions: mark the comment as the **answer**.
+ * In GitHub Issues: **close** the issue.
## Watch the GitHub repository
You can "watch" FastAPI in GitHub (clicking the "watch" button at the top right): https://github.com/tiangolo/fastapi. 👀
-If you select "Watching" instead of "Releases only" you will receive notifications when someone creates a new issue.
+If you select "Watching" instead of "Releases only" you will receive notifications when someone creates a new issue or question. You can also specify that you only want to be notified about new issues, or discussions, or PRs, etc.
-Then you can try and help them solve those issues.
+Then you can try and help them solve those questions.
-## Create issues
+## Ask Questions
-You can create a new issue in the GitHub repository, for example to:
+You can create a new question in the GitHub repository, for example to:
* Ask a **question** or ask about a **problem**.
* Suggest a new **feature**.
-**Note**: if you create an issue, then I'm going to ask you to also help others. 😉
+**Note**: if you do it, then I'm going to ask you to also help others. 😉
## Review Pull Requests
@@ -144,7 +152,7 @@ Here's what to have in mind and how to review a pull request:
### Understand the problem
-* First, make sure you **understand the problem** that the pull request is trying to solve. It might have a longer discussion in an issue.
+* First, make sure you **understand the problem** that the pull request is trying to solve. It might have a longer discussion in a GitHub Discussion or issue.
* There's also a good chance that the pull request is not actually needed because the problem can be solved in a **different way**. Then you can suggest or ask about that.
@@ -207,7 +215,7 @@ There's a lot of work to do, and for most of it, **YOU** can do it.
The main tasks that you can do right now are:
-* [Help others with issues in GitHub](#help-others-with-issues-in-github){.internal-link target=_blank} (see the section above).
+* [Help others with questions in GitHub](#help-others-with-questions-in-github){.internal-link target=_blank} (see the section above).
* [Review Pull Requests](#review-pull-requests){.internal-link target=_blank} (see the section above).
Those two tasks are what **consume time the most**. That's the main work of maintaining FastAPI.
@@ -219,7 +227,7 @@ If you can help me with that, **you are helping me maintain FastAPI** and making
Join the 👥 Discord chat server 👥 and hang out with others in the FastAPI community.
!!! tip
- For questions, ask them in GitHub issues, there's a much better chance you will receive help by the [FastAPI Experts](fastapi-people.md#experts){.internal-link target=_blank}.
+ For questions, ask them in GitHub Discussions, there's a much better chance you will receive help by the [FastAPI Experts](fastapi-people.md#experts){.internal-link target=_blank}.
Use the chat only for other general conversations.
@@ -229,9 +237,9 @@ There is also the previous
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/docs/en/docs/img/sponsors/powens.png b/docs/en/docs/img/sponsors/powens.png
new file mode 100644
index 000000000..07fc6fa37
Binary files /dev/null and b/docs/en/docs/img/sponsors/powens.png differ
diff --git a/docs/en/docs/img/sponsors/svix.svg b/docs/en/docs/img/sponsors/svix.svg
new file mode 100644
index 000000000..845a860a2
--- /dev/null
+++ b/docs/en/docs/img/sponsors/svix.svg
@@ -0,0 +1,178 @@
+
+
diff --git a/docs/en/docs/index.md b/docs/en/docs/index.md
index deb8ab5d5..9a81f14d1 100644
--- a/docs/en/docs/index.md
+++ b/docs/en/docs/index.md
@@ -99,6 +99,12 @@ The key features are:
---
+"_If anyone is looking to build a production Python API, I would highly recommend **FastAPI**. It is **beautifully designed**, **simple to use** and **highly scalable**, it has become a **key component** in our API first development strategy and is driving many automations and services such as our Virtual TAC Engineer._"
+
+
+
+---
+
## **Typer**, the FastAPI of CLIs
diff --git a/docs/en/docs/project-generation.md b/docs/en/docs/project-generation.md
index 2f3d6c1d3..8ba34fa11 100644
--- a/docs/en/docs/project-generation.md
+++ b/docs/en/docs/project-generation.md
@@ -1,6 +1,6 @@
# Project Generation - Template
-You can use a project generator to get started, as it includes a lot of the initial set up, security, database and first API endpoints already done for you.
+You can use a project generator to get started, as it includes a lot of the initial set up, security, database and some API endpoints already done for you.
A project generator will always have a very opinionated setup that you should update and adapt for your own needs, but it might be a good starting point for your project.
diff --git a/docs/en/docs/python-types.md b/docs/en/docs/python-types.md
index 3d22ee620..693613a36 100644
--- a/docs/en/docs/python-types.md
+++ b/docs/en/docs/python-types.md
@@ -1,8 +1,8 @@
# Python Types Intro
-Python has support for optional "type hints".
+Python has support for optional "type hints" (also called "type annotations").
-These **"type hints"** are a special syntax that allow declaring the type of a variable.
+These **"type hints"** or annotations are a special syntax that allow declaring the type of a variable.
By declaring types for your variables, editors and tools can give you better support.
@@ -158,13 +158,31 @@ The syntax using `typing` is **compatible** with all versions, from Python 3.6 t
As Python advances, **newer versions** come with improved support for these type annotations and in many cases you won't even need to import and use the `typing` module to declare the type annotations.
-If you can choose a more recent version of Python for your project, you will be able to take advantage of that extra simplicity. See some examples below.
+If you can choose a more recent version of Python for your project, you will be able to take advantage of that extra simplicity.
+
+In all the docs there are examples compatible with each version of Python (when there's a difference).
+
+For example "**Python 3.6+**" means it's compatible with Python 3.6 or above (including 3.7, 3.8, 3.9, 3.10, etc). And "**Python 3.9+**" means it's compatible with Python 3.9 or above (including 3.10, etc).
+
+If you can use the **latest versions of Python**, use the examples for the latest version, those will have the **best and simplest syntax**, for example, "**Python 3.10+**".
#### List
For example, let's define a variable to be a `list` of `str`.
-=== "Python 3.6 and above"
+=== "Python 3.9+"
+
+ Declare the variable, with the same colon (`:`) syntax.
+
+ As the type, put `list`.
+
+ As the list is a type that contains some internal types, you put them in square brackets:
+
+ ```Python hl_lines="1"
+ {!> ../../../docs_src/python_types/tutorial006_py39.py!}
+ ```
+
+=== "Python 3.6+"
From `typing`, import `List` (with a capital `L`):
@@ -182,18 +200,6 @@ For example, let's define a variable to be a `list` of `str`.
{!> ../../../docs_src/python_types/tutorial006.py!}
```
-=== "Python 3.9 and above"
-
- Declare the variable, with the same colon (`:`) syntax.
-
- As the type, put `list`.
-
- As the list is a type that contains some internal types, you put them in square brackets:
-
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial006_py39.py!}
- ```
-
!!! info
Those internal types in the square brackets are called "type parameters".
@@ -218,16 +224,16 @@ And still, the editor knows it is a `str`, and provides support for that.
You would do the same to declare `tuple`s and `set`s:
-=== "Python 3.6 and above"
+=== "Python 3.9+"
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial007.py!}
+ ```Python hl_lines="1"
+ {!> ../../../docs_src/python_types/tutorial007_py39.py!}
```
-=== "Python 3.9 and above"
+=== "Python 3.6+"
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial007_py39.py!}
+ ```Python hl_lines="1 4"
+ {!> ../../../docs_src/python_types/tutorial007.py!}
```
This means:
@@ -243,16 +249,16 @@ The first type parameter is for the keys of the `dict`.
The second type parameter is for the values of the `dict`:
-=== "Python 3.6 and above"
+=== "Python 3.9+"
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial008.py!}
+ ```Python hl_lines="1"
+ {!> ../../../docs_src/python_types/tutorial008_py39.py!}
```
-=== "Python 3.9 and above"
+=== "Python 3.6+"
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial008_py39.py!}
+ ```Python hl_lines="1 4"
+ {!> ../../../docs_src/python_types/tutorial008.py!}
```
This means:
@@ -267,18 +273,18 @@ 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** where you can put the possible types separated by a vertical bar (`|`).
+In Python 3.10 there's also a **new syntax** where you can put the possible types separated by a vertical bar (`|`).
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial008b.py!}
+ ```Python hl_lines="1"
+ {!> ../../../docs_src/python_types/tutorial008b_py310.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial008b_py310.py!}
+ ```Python hl_lines="1 4"
+ {!> ../../../docs_src/python_types/tutorial008b.py!}
```
In both cases this means that `item` could be an `int` or a `str`.
@@ -299,22 +305,22 @@ Using `Optional[str]` instead of just `str` will let the editor help you detecti
This also means that in Python 3.10, you can use `Something | None`:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial009.py!}
+ ```Python hl_lines="1"
+ {!> ../../../docs_src/python_types/tutorial009_py310.py!}
```
-=== "Python 3.6 and above - alternative"
+=== "Python 3.6+"
```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial009b.py!}
+ {!> ../../../docs_src/python_types/tutorial009.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+ alternative"
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial009_py310.py!}
+ ```Python hl_lines="1 4"
+ {!> ../../../docs_src/python_types/tutorial009b.py!}
```
#### Using `Union` or `Optional`
@@ -360,17 +366,7 @@ And then you won't have to worry about names like `Optional` and `Union`. 😎
These types that take type parameters in square brackets are called **Generic types** or **Generics**, for example:
-=== "Python 3.6 and above"
-
- * `List`
- * `Tuple`
- * `Set`
- * `Dict`
- * `Union`
- * `Optional`
- * ...and others.
-
-=== "Python 3.9 and above"
+=== "Python 3.10+"
You can use the same builtin types as generics (with square brackets and types inside):
@@ -382,10 +378,12 @@ These types that take type parameters in square brackets are called **Generic ty
And the same as with Python 3.6, from the `typing` module:
* `Union`
- * `Optional`
+ * `Optional` (the same as with Python 3.6)
* ...and others.
-=== "Python 3.10 and above"
+ In Python 3.10, as an alternative to using the generics `Union` and `Optional`, you can use the vertical bar (`|`) to declare unions of types, that's a lot better and simpler.
+
+=== "Python 3.9+"
You can use the same builtin types as generics (with square brackets and types inside):
@@ -397,10 +395,18 @@ These types that take type parameters in square brackets are called **Generic ty
And the same as with Python 3.6, from the `typing` module:
* `Union`
- * `Optional` (the same as with Python 3.6)
+ * `Optional`
* ...and others.
- In Python 3.10, as an alternative to using the generics `Union` and `Optional`, you can use the vertical bar (`|`) to declare unions of types.
+=== "Python 3.6+"
+
+ * `List`
+ * `Tuple`
+ * `Set`
+ * `Dict`
+ * `Union`
+ * `Optional`
+ * ...and others.
### Classes as types
@@ -422,6 +428,10 @@ And then, again, you get all the editor support:
+Notice that this means "`one_person` is an **instance** of the class `Person`".
+
+It doesn't mean "`one_person` is the **class** called `Person`".
+
## Pydantic models
Pydantic is a Python library to perform data validation.
@@ -436,22 +446,22 @@ And you get all the editor support with that resulting object.
An example from the official Pydantic docs:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
```Python
- {!> ../../../docs_src/python_types/tutorial011.py!}
+ {!> ../../../docs_src/python_types/tutorial011_py310.py!}
```
-=== "Python 3.9 and above"
+=== "Python 3.9+"
```Python
{!> ../../../docs_src/python_types/tutorial011_py39.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
```Python
- {!> ../../../docs_src/python_types/tutorial011_py310.py!}
+ {!> ../../../docs_src/python_types/tutorial011.py!}
```
!!! info
@@ -464,6 +474,43 @@ You will see a lot more of all this in practice in the [Tutorial - User Guide](t
!!! tip
Pydantic has a special behavior when you use `Optional` or `Union[Something, None]` without a default value, you can read more about it in the Pydantic docs about Required Optional fields.
+## Type Hints with Metadata Annotations
+
+Python also has a feature that allows putting **additional metadata** in these type hints using `Annotated`.
+
+=== "Python 3.9+"
+
+ In Python 3.9, `Annotated` is part of the standard library, so you can import it from `typing`.
+
+ ```Python hl_lines="1 4"
+ {!> ../../../docs_src/python_types/tutorial013_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ In versions below Python 3.9, you import `Annotated` from `typing_extensions`.
+
+ It will already be installed with **FastAPI**.
+
+ ```Python hl_lines="1 4"
+ {!> ../../../docs_src/python_types/tutorial013.py!}
+ ```
+
+Python itself doesn't do anything with this `Annotated`. And for editors and other tools, the type is still `str`.
+
+But you can use this space in `Annotated` to provide **FastAPI** with additional metadata about how you want your application to behave.
+
+The important thing to remember is that **the first *type parameter*** you pass to `Annotated` is the **actual type**. The rest, is just metadata for other tools.
+
+For now, you just need to know that `Annotated` exists, and that it's standard Python. 😎
+
+Later you will see how **powerful** it can be.
+
+!!! tip
+ The fact that this is **standard Python** means that you will still get the **best possible developer experience** in your editor, with the tools you use to analyze and refactor your code, etc. ✨
+
+ And also that your code will be very compatible with many other Python tools and libraries. 🚀
+
## 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 b65460294..0a167b9c5 100644
--- a/docs/en/docs/release-notes.md
+++ b/docs/en/docs/release-notes.md
@@ -2,6 +2,408 @@
## Latest Changes
+* ✏ Fix command to install requirements in Windows. PR [#9445](https://github.com/tiangolo/fastapi/pull/9445) by [@MariiaRomanuik](https://github.com/MariiaRomanuik).
+* 🌐 Add French translation for `docs/fr/docs/advanced/response-directly.md`. PR [#9415](https://github.com/tiangolo/fastapi/pull/9415) by [@axel584](https://github.com/axel584).
+* 🌐 Initiate Czech translation setup. PR [#9288](https://github.com/tiangolo/fastapi/pull/9288) by [@3p1463k](https://github.com/3p1463k).
+* ✏ Fix typo in Portuguese docs for `docs/pt/docs/index.md`. PR [#9337](https://github.com/tiangolo/fastapi/pull/9337) by [@lucasbalieiro](https://github.com/lucasbalieiro).
+* 🌐 Add Russian translation for `docs/ru/docs/tutorial/response-status-code.md`. PR [#9370](https://github.com/tiangolo/fastapi/pull/9370) by [@nadia3373](https://github.com/nadia3373).
+* ⬆ Bump dawidd6/action-download-artifact from 2.26.0 to 2.27.0. PR [#9394](https://github.com/tiangolo/fastapi/pull/9394) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* 💚 Disable setup-python pip cache in CI. PR [#9438](https://github.com/tiangolo/fastapi/pull/9438) by [@tiangolo](https://github.com/tiangolo).
+* ⬆ Bump pypa/gh-action-pypi-publish from 1.6.4 to 1.8.5. PR [#9346](https://github.com/tiangolo/fastapi/pull/9346) by [@dependabot[bot]](https://github.com/apps/dependabot).
+
+## 0.95.1
+
+### Fixes
+
+* 🐛 Fix using `Annotated` in routers or path operations decorated multiple times. PR [#9315](https://github.com/tiangolo/fastapi/pull/9315) by [@sharonyogev](https://github.com/sharonyogev).
+
+### Docs
+
+* 🌐 🔠 📄 🐢 Translate docs to Emoji 🥳 🎉 💥 🤯 🤯. PR [#5385](https://github.com/tiangolo/fastapi/pull/5385) by [@LeeeeT](https://github.com/LeeeeT).
+* 📝 Add notification message warning about old versions of FastAPI not supporting `Annotated`. PR [#9298](https://github.com/tiangolo/fastapi/pull/9298) by [@grdworkin](https://github.com/grdworkin).
+* 📝 Fix typo in `docs/en/docs/advanced/behind-a-proxy.md`. PR [#5681](https://github.com/tiangolo/fastapi/pull/5681) by [@Leommjr](https://github.com/Leommjr).
+* ✏ Fix wrong import from typing module in Persian translations for `docs/fa/docs/index.md`. PR [#6083](https://github.com/tiangolo/fastapi/pull/6083) by [@Kimiaattaei](https://github.com/Kimiaattaei).
+* ✏️ Fix format, remove unnecessary asterisks in `docs/en/docs/help-fastapi.md`. PR [#9249](https://github.com/tiangolo/fastapi/pull/9249) by [@armgabrielyan](https://github.com/armgabrielyan).
+* ✏ Fix typo in `docs/en/docs/tutorial/query-params-str-validations.md`. PR [#9272](https://github.com/tiangolo/fastapi/pull/9272) by [@nicornk](https://github.com/nicornk).
+* ✏ Fix typo/bug in inline code example in `docs/en/docs/tutorial/query-params-str-validations.md`. PR [#9273](https://github.com/tiangolo/fastapi/pull/9273) by [@tim-habitat](https://github.com/tim-habitat).
+* ✏ Fix typo in `docs/en/docs/tutorial/path-params-numeric-validations.md`. PR [#9282](https://github.com/tiangolo/fastapi/pull/9282) by [@aadarsh977](https://github.com/aadarsh977).
+* ✏ Fix typo: 'wll' to 'will' in `docs/en/docs/tutorial/query-params-str-validations.md`. PR [#9380](https://github.com/tiangolo/fastapi/pull/9380) by [@dasstyxx](https://github.com/dasstyxx).
+
+### Translations
+
+* 🌐 Add French translation for `docs/fr/docs/advanced/index.md`. PR [#5673](https://github.com/tiangolo/fastapi/pull/5673) by [@axel584](https://github.com/axel584).
+* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/body-nested-models.md`. PR [#4053](https://github.com/tiangolo/fastapi/pull/4053) by [@luccasmmg](https://github.com/luccasmmg).
+* 🌐 Add Russian translation for `docs/ru/docs/alternatives.md`. PR [#5994](https://github.com/tiangolo/fastapi/pull/5994) by [@Xewus](https://github.com/Xewus).
+* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/extra-models.md`. PR [#5912](https://github.com/tiangolo/fastapi/pull/5912) by [@LorhanSohaky](https://github.com/LorhanSohaky).
+* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/path-operation-configuration.md`. PR [#5936](https://github.com/tiangolo/fastapi/pull/5936) by [@LorhanSohaky](https://github.com/LorhanSohaky).
+* 🌐 Add Russian translation for `docs/ru/docs/contributing.md`. PR [#6002](https://github.com/tiangolo/fastapi/pull/6002) by [@stigsanek](https://github.com/stigsanek).
+* 🌐 Add Korean translation for `docs/tutorial/dependencies/classes-as-dependencies.md`. PR [#9176](https://github.com/tiangolo/fastapi/pull/9176) by [@sehwan505](https://github.com/sehwan505).
+* 🌐 Add Russian translation for `docs/ru/docs/project-generation.md`. PR [#9243](https://github.com/tiangolo/fastapi/pull/9243) by [@Xewus](https://github.com/Xewus).
+* 🌐 Add French translation for `docs/fr/docs/index.md`. PR [#9265](https://github.com/tiangolo/fastapi/pull/9265) by [@frabc](https://github.com/frabc).
+* 🌐 Add Russian translation for `docs/ru/docs/tutorial/query-params-str-validations.md`. PR [#9267](https://github.com/tiangolo/fastapi/pull/9267) by [@dedkot01](https://github.com/dedkot01).
+* 🌐 Add Russian translation for `docs/ru/docs/benchmarks.md`. PR [#9271](https://github.com/tiangolo/fastapi/pull/9271) by [@Xewus](https://github.com/Xewus).
+
+### Internal
+
+* 🔧 Update sponsors: remove Jina. PR [#9388](https://github.com/tiangolo/fastapi/pull/9388) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update sponsors, add databento, remove Ines's course and StriveWorks. PR [#9351](https://github.com/tiangolo/fastapi/pull/9351) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.95.0
+
+### Highlights
+
+This release adds support for dependencies and parameters using `Annotated` and recommends its usage. ✨
+
+This has **several benefits**, one of the main ones is that now the parameters of your functions with `Annotated` would **not be affected** at all.
+
+If you call those functions in **other places in your code**, the actual **default values** will be kept, your editor will help you notice missing **required arguments**, Python will require you to pass required arguments at **runtime**, you will be able to **use the same functions** for different things and with different libraries (e.g. **Typer** will soon support `Annotated` too, then you could use the same function for an API and a CLI), etc.
+
+Because `Annotated` is **standard Python**, you still get all the **benefits** from editors and tools, like **autocompletion**, **inline errors**, etc.
+
+One of the **biggest benefits** is that now you can create `Annotated` dependencies that are then shared by multiple *path operation functions*, this will allow you to **reduce** a lot of **code duplication** in your codebase, while keeping all the support from editors and tools.
+
+For example, you could have code like this:
+
+```Python
+def get_current_user(token: str):
+ # authenticate user
+ return User()
+
+
+@app.get("/items/")
+def read_items(user: User = Depends(get_current_user)):
+ ...
+
+
+@app.post("/items/")
+def create_item(*, user: User = Depends(get_current_user), item: Item):
+ ...
+
+
+@app.get("/items/{item_id}")
+def read_item(*, user: User = Depends(get_current_user), item_id: int):
+ ...
+
+
+@app.delete("/items/{item_id}")
+def delete_item(*, user: User = Depends(get_current_user), item_id: int):
+ ...
+```
+
+There's a bit of code duplication for the dependency:
+
+```Python
+user: User = Depends(get_current_user)
+```
+
+...the bigger the codebase, the more noticeable it is.
+
+Now you can create an annotated dependency once, like this:
+
+```Python
+CurrentUser = Annotated[User, Depends(get_current_user)]
+```
+
+And then you can reuse this `Annotated` dependency:
+
+```Python
+CurrentUser = Annotated[User, Depends(get_current_user)]
+
+
+@app.get("/items/")
+def read_items(user: CurrentUser):
+ ...
+
+
+@app.post("/items/")
+def create_item(user: CurrentUser, item: Item):
+ ...
+
+
+@app.get("/items/{item_id}")
+def read_item(user: CurrentUser, item_id: int):
+ ...
+
+
+@app.delete("/items/{item_id}")
+def delete_item(user: CurrentUser, item_id: int):
+ ...
+```
+
+...and `CurrentUser` has all the typing information as `User`, so your editor will work as expected (autocompletion and everything), and **FastAPI** will be able to understand the dependency defined in `Annotated`. 😎
+
+Roughly **all the docs** have been rewritten to use `Annotated` as the main way to declare **parameters** and **dependencies**. All the **examples** in the docs now include a version with `Annotated` and a version without it, for each of the specific Python versions (when there are small differences/improvements in more recent versions). There were around 23K new lines added between docs, examples, and tests. 🚀
+
+The key updated docs are:
+
+* Python Types Intro:
+ * [Type Hints with Metadata Annotations](https://fastapi.tiangolo.com/python-types/#type-hints-with-metadata-annotations).
+* Tutorial:
+ * [Query Parameters and String Validations - Additional validation](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#additional-validation)
+ * [Advantages of `Annotated`](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#advantages-of-annotated)
+ * [Path Parameters and Numeric Validations - Order the parameters as you need, tricks](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#order-the-parameters-as-you-need-tricks)
+ * [Better with `Annotated`](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#better-with-annotated)
+ * [Dependencies - First Steps - Share `Annotated` dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/#share-annotated-dependencies)
+
+Special thanks to [@nzig](https://github.com/nzig) for the core implementation and to [@adriangb](https://github.com/adriangb) for the inspiration and idea with [Xpresso](https://github.com/adriangb/xpresso)! 🚀
+
+### Features
+
+* ✨Add support for PEP-593 `Annotated` for specifying dependencies and parameters. PR [#4871](https://github.com/tiangolo/fastapi/pull/4871) by [@nzig](https://github.com/nzig).
+
+### Docs
+
+* 📝 Tweak tip recommending `Annotated` in docs. PR [#9270](https://github.com/tiangolo/fastapi/pull/9270) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Update order of examples, latest Python version first, and simplify version tab names. PR [#9269](https://github.com/tiangolo/fastapi/pull/9269) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Update all docs to use `Annotated` as the main recommendation, with new examples and tests. PR [#9268](https://github.com/tiangolo/fastapi/pull/9268) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.94.1
+
+### Fixes
+
+* 🎨 Fix types for lifespan, upgrade Starlette to 0.26.1. PR [#9245](https://github.com/tiangolo/fastapi/pull/9245) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.94.0
+
+### Upgrades
+
+* ⬆ Upgrade python-multipart to support 0.0.6. PR [#9212](https://github.com/tiangolo/fastapi/pull/9212) by [@musicinmybrain](https://github.com/musicinmybrain).
+* ⬆️ Upgrade Starlette version, support new `lifespan` with state. PR [#9239](https://github.com/tiangolo/fastapi/pull/9239) by [@tiangolo](https://github.com/tiangolo).
+
+### Docs
+
+* 📝 Update Sentry link in docs. PR [#9218](https://github.com/tiangolo/fastapi/pull/9218) by [@smeubank](https://github.com/smeubank).
+
+### Translations
+
+* 🌐 Add Russian translation for `docs/ru/docs/history-design-future.md`. PR [#5986](https://github.com/tiangolo/fastapi/pull/5986) by [@Xewus](https://github.com/Xewus).
+
+### Internal
+
+* ➕ Add `pydantic` to PyPI classifiers. PR [#5914](https://github.com/tiangolo/fastapi/pull/5914) by [@yezz123](https://github.com/yezz123).
+* ⬆ Bump black from 22.10.0 to 23.1.0. PR [#5953](https://github.com/tiangolo/fastapi/pull/5953) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump types-ujson from 5.6.0.0 to 5.7.0.1. PR [#6027](https://github.com/tiangolo/fastapi/pull/6027) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump dawidd6/action-download-artifact from 2.24.3 to 2.26.0. PR [#6034](https://github.com/tiangolo/fastapi/pull/6034) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#5709](https://github.com/tiangolo/fastapi/pull/5709) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
+
+## 0.93.0
+
+### Features
+
+* ✨ Add support for `lifespan` async context managers (superseding `startup` and `shutdown` events). Initial PR [#2944](https://github.com/tiangolo/fastapi/pull/2944) by [@uSpike](https://github.com/uSpike).
+
+Now, instead of using independent `startup` and `shutdown` events, you can define that logic in a single function with `yield` decorated with `@asynccontextmanager` (an async context manager).
+
+For example:
+
+```Python
+from contextlib import asynccontextmanager
+
+from fastapi import FastAPI
+
+
+def fake_answer_to_everything_ml_model(x: float):
+ return x * 42
+
+
+ml_models = {}
+
+
+@asynccontextmanager
+async def lifespan(app: FastAPI):
+ # Load the ML model
+ ml_models["answer_to_everything"] = fake_answer_to_everything_ml_model
+ yield
+ # Clean up the ML models and release the resources
+ ml_models.clear()
+
+
+app = FastAPI(lifespan=lifespan)
+
+
+@app.get("/predict")
+async def predict(x: float):
+ result = ml_models["answer_to_everything"](x)
+ return {"result": result}
+```
+
+**Note**: This is the recommended way going forward, instead of using `startup` and `shutdown` events.
+
+Read more about it in the new docs: [Advanced User Guide: Lifespan Events](https://fastapi.tiangolo.com/advanced/events/).
+
+### Docs
+
+* ✏ Fix formatting in `docs/en/docs/tutorial/metadata.md` for `ReDoc`. PR [#6005](https://github.com/tiangolo/fastapi/pull/6005) by [@eykamp](https://github.com/eykamp).
+
+### Translations
+
+* 🌐 Tamil translations - initial setup. PR [#5564](https://github.com/tiangolo/fastapi/pull/5564) by [@gusty1g](https://github.com/gusty1g).
+* 🌐 Add French translation for `docs/fr/docs/advanced/path-operation-advanced-configuration.md`. PR [#9221](https://github.com/tiangolo/fastapi/pull/9221) by [@axel584](https://github.com/axel584).
+* 🌐 Add French translation for `docs/tutorial/debugging.md`. PR [#9175](https://github.com/tiangolo/fastapi/pull/9175) by [@frabc](https://github.com/frabc).
+* 🌐 Initiate Armenian translation setup. PR [#5844](https://github.com/tiangolo/fastapi/pull/5844) by [@har8](https://github.com/har8).
+* 🌐 Add French translation for `deployment/manually.md`. PR [#3693](https://github.com/tiangolo/fastapi/pull/3693) by [@rjNemo](https://github.com/rjNemo).
+
+### Internal
+
+* 👷 Update translation bot messages. PR [#9206](https://github.com/tiangolo/fastapi/pull/9206) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Update translations bot to use Discussions, and notify when a PR is done. PR [#9183](https://github.com/tiangolo/fastapi/pull/9183) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update sponsors-badges. PR [#9182](https://github.com/tiangolo/fastapi/pull/9182) by [@tiangolo](https://github.com/tiangolo).
+* 👥 Update FastAPI People. PR [#9181](https://github.com/tiangolo/fastapi/pull/9181) by [@github-actions[bot]](https://github.com/apps/github-actions).
+* 🔊 Log GraphQL errors in FastAPI People, because it returns 200, with a payload with an error. PR [#9171](https://github.com/tiangolo/fastapi/pull/9171) by [@tiangolo](https://github.com/tiangolo).
+* 💚 Fix/workaround GitHub Actions in Docker with git for FastAPI People. PR [#9169](https://github.com/tiangolo/fastapi/pull/9169) by [@tiangolo](https://github.com/tiangolo).
+* ♻️ Refactor FastAPI Experts to use only discussions now that questions are migrated. PR [#9165](https://github.com/tiangolo/fastapi/pull/9165) by [@tiangolo](https://github.com/tiangolo).
+* ⬆️ Upgrade analytics. PR [#6025](https://github.com/tiangolo/fastapi/pull/6025) by [@tiangolo](https://github.com/tiangolo).
+* ⬆️ Upgrade and re-enable installing Typer-CLI. PR [#6008](https://github.com/tiangolo/fastapi/pull/6008) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.92.0
+
+🚨 This is a security fix. Please upgrade as soon as possible.
+
+### Upgrades
+
+* ⬆️ Upgrade Starlette to 0.25.0. PR [#5996](https://github.com/tiangolo/fastapi/pull/5996) by [@tiangolo](https://github.com/tiangolo).
+ * This solves a vulnerability that could allow denial of service attacks by using many small multipart fields/files (parts), consuming high CPU and memory.
+ * Only applications using forms (e.g. file uploads) could be affected.
+ * For most cases, upgrading won't have any breaking changes.
+
+## 0.91.0
+
+### Upgrades
+
+* ⬆️ Upgrade Starlette version to `0.24.0` and refactor internals for compatibility. PR [#5985](https://github.com/tiangolo/fastapi/pull/5985) by [@tiangolo](https://github.com/tiangolo).
+ * This can solve nuanced errors when using middlewares. Before Starlette `0.24.0`, a new instance of each middleware class would be created when a new middleware was added. That normally was not a problem, unless the middleware class expected to be created only once, with only one instance, that happened in some cases. This upgrade would solve those cases (thanks [@adriangb](https://github.com/adriangb)! Starlette PR [#2017](https://github.com/encode/starlette/pull/2017)). Now the middleware class instances are created once, right before the first request (the first time the app is called).
+ * If you depended on that previous behavior, you might need to update your code. As always, make sure your tests pass before merging the upgrade.
+
+## 0.90.1
+
+### Upgrades
+
+* ⬆️ Upgrade Starlette range to allow 0.23.1. PR [#5980](https://github.com/tiangolo/fastapi/pull/5980) by [@tiangolo](https://github.com/tiangolo).
+
+### Docs
+
+* ✏ Tweak wording to clarify `docs/en/docs/project-generation.md`. PR [#5930](https://github.com/tiangolo/fastapi/pull/5930) by [@chandra-deb](https://github.com/chandra-deb).
+* ✏ Update Pydantic GitHub URLs. PR [#5952](https://github.com/tiangolo/fastapi/pull/5952) by [@yezz123](https://github.com/yezz123).
+* 📝 Add opinion from Cisco. PR [#5981](https://github.com/tiangolo/fastapi/pull/5981) by [@tiangolo](https://github.com/tiangolo).
+
+### Translations
+
+* 🌐 Add Russian translation for `docs/ru/docs/tutorial/cookie-params.md`. PR [#5890](https://github.com/tiangolo/fastapi/pull/5890) by [@bnzone](https://github.com/bnzone).
+
+### Internal
+
+* ✏ Update `zip-docs.sh` internal script, remove extra space. PR [#5931](https://github.com/tiangolo/fastapi/pull/5931) by [@JuanPerdomo00](https://github.com/JuanPerdomo00).
+
+## 0.90.0
+
+### Upgrades
+
+* ⬆️ Bump Starlette from 0.22.0 to 0.23.0. Initial PR [#5739](https://github.com/tiangolo/fastapi/pull/5739) by [@Kludex](https://github.com/Kludex).
+
+### Docs
+
+* 📝 Add article "Tortoise ORM / FastAPI 整合快速筆記" to External Links. PR [#5496](https://github.com/tiangolo/fastapi/pull/5496) by [@Leon0824](https://github.com/Leon0824).
+* 👥 Update FastAPI People. PR [#5954](https://github.com/tiangolo/fastapi/pull/5954) by [@github-actions[bot]](https://github.com/apps/github-actions).
+* 📝 Micro-tweak help docs. PR [#5960](https://github.com/tiangolo/fastapi/pull/5960) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update new issue chooser to direct to GitHub Discussions. PR [#5948](https://github.com/tiangolo/fastapi/pull/5948) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Recommend GitHub Discussions for questions. PR [#5944](https://github.com/tiangolo/fastapi/pull/5944) by [@tiangolo](https://github.com/tiangolo).
+
+### Translations
+
+* 🌐 Add Russian translation for `docs/ru/docs/tutorial/body-fields.md`. PR [#5898](https://github.com/tiangolo/fastapi/pull/5898) by [@simatheone](https://github.com/simatheone).
+* 🌐 Add Russian translation for `docs/ru/docs/help-fastapi.md`. PR [#5970](https://github.com/tiangolo/fastapi/pull/5970) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/static-files.md`. PR [#5858](https://github.com/tiangolo/fastapi/pull/5858) by [@batlopes](https://github.com/batlopes).
+* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/encoder.md`. PR [#5525](https://github.com/tiangolo/fastapi/pull/5525) by [@felipebpl](https://github.com/felipebpl).
+* 🌐 Add Russian translation for `docs/ru/docs/contributing.md`. PR [#5870](https://github.com/tiangolo/fastapi/pull/5870) by [@Xewus](https://github.com/Xewus).
+
+### Internal
+
+* ⬆️ Upgrade Ubuntu version for docs workflow. PR [#5971](https://github.com/tiangolo/fastapi/pull/5971) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update sponsors badges. PR [#5943](https://github.com/tiangolo/fastapi/pull/5943) by [@tiangolo](https://github.com/tiangolo).
+* ✨ Compute FastAPI Experts including GitHub Discussions. PR [#5941](https://github.com/tiangolo/fastapi/pull/5941) by [@tiangolo](https://github.com/tiangolo).
+* ⬆️ Upgrade isort and update pre-commit. PR [#5940](https://github.com/tiangolo/fastapi/pull/5940) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Add template for questions in Discussions. PR [#5920](https://github.com/tiangolo/fastapi/pull/5920) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update Sponsor Budget Insight to Powens. PR [#5916](https://github.com/tiangolo/fastapi/pull/5916) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update GitHub Sponsors badge data. PR [#5915](https://github.com/tiangolo/fastapi/pull/5915) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.89.1
+
+### Fixes
+
+* 🐛 Ignore Response classes on return annotation. PR [#5855](https://github.com/tiangolo/fastapi/pull/5855) by [@Kludex](https://github.com/Kludex). See the new docs in the PR below.
+
+### Docs
+
+* 📝 Update docs and examples for Response Model with Return Type Annotations, and update runtime error. PR [#5873](https://github.com/tiangolo/fastapi/pull/5873) by [@tiangolo](https://github.com/tiangolo). New docs at [Response Model - Return Type: Other Return Type Annotations](https://fastapi.tiangolo.com/tutorial/response-model/#other-return-type-annotations).
+* 📝 Add External Link: FastAPI lambda container: serverless simplified. PR [#5784](https://github.com/tiangolo/fastapi/pull/5784) by [@rafrasenberg](https://github.com/rafrasenberg).
+
+### Translations
+
+* 🌐 Add Turkish translation for `docs/tr/docs/tutorial/first_steps.md`. PR [#5691](https://github.com/tiangolo/fastapi/pull/5691) by [@Kadermiyanyedi](https://github.com/Kadermiyanyedi).
+
+## 0.89.0
+
+### Features
+
+* ✨ Add support for function return type annotations to declare the `response_model`. Initial PR [#1436](https://github.com/tiangolo/fastapi/pull/1436) by [@uriyyo](https://github.com/uriyyo).
+
+Now you can declare the return type / `response_model` in the function return type annotation:
+
+```python
+from fastapi import FastAPI
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class Item(BaseModel):
+ name: str
+ price: float
+
+
+@app.get("/items/")
+async def read_items() -> list[Item]:
+ return [
+ Item(name="Portal Gun", price=42.0),
+ Item(name="Plumbus", price=32.0),
+ ]
+```
+
+FastAPI will use the return type annotation to perform:
+
+* Data validation
+* Automatic documentation
+ * It could power automatic client generators
+* **Data filtering**
+
+Before this version it was only supported via the `response_model` parameter.
+
+Read more about it in the new docs: [Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/).
+
+### Docs
+
+* 📝 Add External Link: Authorization on FastAPI with Casbin. PR [#5712](https://github.com/tiangolo/fastapi/pull/5712) by [@Xhy-5000](https://github.com/Xhy-5000).
+* ✏ Fix typo in `docs/en/docs/async.md`. PR [#5785](https://github.com/tiangolo/fastapi/pull/5785) by [@Kingdageek](https://github.com/Kingdageek).
+* ✏ Fix typo in `docs/en/docs/deployment/concepts.md`. PR [#5824](https://github.com/tiangolo/fastapi/pull/5824) by [@kelbyfaessler](https://github.com/kelbyfaessler).
+
+### Translations
+
+* 🌐 Add Russian translation for `docs/ru/docs/fastapi-people.md`. PR [#5577](https://github.com/tiangolo/fastapi/pull/5577) by [@Xewus](https://github.com/Xewus).
+* 🌐 Fix typo in Chinese translation for `docs/zh/docs/benchmarks.md`. PR [#4269](https://github.com/tiangolo/fastapi/pull/4269) by [@15027668g](https://github.com/15027668g).
+* 🌐 Add Korean translation for `docs/tutorial/cors.md`. PR [#3764](https://github.com/tiangolo/fastapi/pull/3764) by [@NinaHwang](https://github.com/NinaHwang).
+
+### Internal
+
+* ⬆ Update coverage[toml] requirement from <7.0,>=6.5.0 to >=6.5.0,<8.0. PR [#5801](https://github.com/tiangolo/fastapi/pull/5801) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Update uvicorn[standard] requirement from <0.19.0,>=0.12.0 to >=0.12.0,<0.21.0 for development. PR [#5795](https://github.com/tiangolo/fastapi/pull/5795) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump dawidd6/action-download-artifact from 2.24.2 to 2.24.3. PR [#5842](https://github.com/tiangolo/fastapi/pull/5842) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* 👥 Update FastAPI People. PR [#5825](https://github.com/tiangolo/fastapi/pull/5825) by [@github-actions[bot]](https://github.com/apps/github-actions).
+* ⬆ Bump types-ujson from 5.5.0 to 5.6.0.0. PR [#5735](https://github.com/tiangolo/fastapi/pull/5735) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump pypa/gh-action-pypi-publish from 1.5.2 to 1.6.4. PR [#5750](https://github.com/tiangolo/fastapi/pull/5750) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* 👷 Add GitHub Action gate/check. PR [#5492](https://github.com/tiangolo/fastapi/pull/5492) by [@webknjaz](https://github.com/webknjaz).
+* 🔧 Update sponsors, add Svix. PR [#5848](https://github.com/tiangolo/fastapi/pull/5848) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Remove Doist sponsor. PR [#5847](https://github.com/tiangolo/fastapi/pull/5847) by [@tiangolo](https://github.com/tiangolo).
+* ⬆ Update sqlalchemy requirement from <=1.4.41,>=1.3.18 to >=1.3.18,<1.4.43. PR [#5540](https://github.com/tiangolo/fastapi/pull/5540) by [@dependabot[bot]](https://github.com/apps/dependabot).
* ⬆ Bump nwtgck/actions-netlify from 1.2.4 to 2.0.0. PR [#5757](https://github.com/tiangolo/fastapi/pull/5757) by [@dependabot[bot]](https://github.com/apps/dependabot).
* 👷 Refactor CI artifact upload/download for docs previews. PR [#5793](https://github.com/tiangolo/fastapi/pull/5793) by [@tiangolo](https://github.com/tiangolo).
* ⬆ Bump pypa/gh-action-pypi-publish from 1.5.1 to 1.5.2. PR [#5714](https://github.com/tiangolo/fastapi/pull/5714) by [@dependabot[bot]](https://github.com/apps/dependabot).
@@ -1130,7 +1532,7 @@ Thanks to [Dima Boger](https://twitter.com/b0g3r) for the security report! 🙇
### Security fixes
-* 📌 Upgrade pydantic pin, to handle security vulnerability [CVE-2021-29510](https://github.com/samuelcolvin/pydantic/security/advisories/GHSA-5jqp-qgf6-3pvh). PR [#3213](https://github.com/tiangolo/fastapi/pull/3213) by [@tiangolo](https://github.com/tiangolo).
+* 📌 Upgrade pydantic pin, to handle security vulnerability [CVE-2021-29510](https://github.com/pydantic/pydantic/security/advisories/GHSA-5jqp-qgf6-3pvh). PR [#3213](https://github.com/tiangolo/fastapi/pull/3213) by [@tiangolo](https://github.com/tiangolo).
## 0.65.0
@@ -1685,11 +2087,11 @@ Note: all the previous parameters are still there, so it's still possible to dec
## 0.55.1
-* Fix handling of enums with their own schema in path parameters. To support [samuelcolvin/pydantic#1432](https://github.com/samuelcolvin/pydantic/pull/1432) in FastAPI. PR [#1463](https://github.com/tiangolo/fastapi/pull/1463).
+* Fix handling of enums with their own schema in path parameters. To support [pydantic/pydantic#1432](https://github.com/pydantic/pydantic/pull/1432) in FastAPI. PR [#1463](https://github.com/tiangolo/fastapi/pull/1463).
## 0.55.0
-* Allow enums to allow them to have their own schemas in OpenAPI. To support [samuelcolvin/pydantic#1432](https://github.com/samuelcolvin/pydantic/pull/1432) in FastAPI. PR [#1461](https://github.com/tiangolo/fastapi/pull/1461).
+* Allow enums to allow them to have their own schemas in OpenAPI. To support [pydantic/pydantic#1432](https://github.com/pydantic/pydantic/pull/1432) in FastAPI. PR [#1461](https://github.com/tiangolo/fastapi/pull/1461).
* Add links for funding through [GitHub sponsors](https://github.com/sponsors/tiangolo). PR [#1425](https://github.com/tiangolo/fastapi/pull/1425).
* Update issue template for for questions. PR [#1344](https://github.com/tiangolo/fastapi/pull/1344) by [@retnikt](https://github.com/retnikt).
* Update warning about storing passwords in docs. PR [#1336](https://github.com/tiangolo/fastapi/pull/1336) by [@skorokithakis](https://github.com/skorokithakis).
diff --git a/docs/en/docs/tutorial/background-tasks.md b/docs/en/docs/tutorial/background-tasks.md
index 191a4ca0f..178297192 100644
--- a/docs/en/docs/tutorial/background-tasks.md
+++ b/docs/en/docs/tutorial/background-tasks.md
@@ -57,18 +57,42 @@ Using `BackgroundTasks` also works with the dependency injection system, you can
**FastAPI** knows what to do in each case and how to re-use the same object, so that all the background tasks are merged together and are run in the background afterwards:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
```Python hl_lines="13 15 22 25"
- {!> ../../../docs_src/background_tasks/tutorial002.py!}
+ {!> ../../../docs_src/background_tasks/tutorial002_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="13 15 22 25"
+ {!> ../../../docs_src/background_tasks/tutorial002_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="14 16 23 26"
+ {!> ../../../docs_src/background_tasks/tutorial002_an.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="11 13 20 23"
{!> ../../../docs_src/background_tasks/tutorial002_py310.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="13 15 22 25"
+ {!> ../../../docs_src/background_tasks/tutorial002.py!}
+ ```
+
In this example, the messages will be written to the `log.txt` file *after* the response is sent.
If there was a query in the request, it will be written to the log in a background task.
diff --git a/docs/en/docs/tutorial/bigger-applications.md b/docs/en/docs/tutorial/bigger-applications.md
index d201953df..daa7353a2 100644
--- a/docs/en/docs/tutorial/bigger-applications.md
+++ b/docs/en/docs/tutorial/bigger-applications.md
@@ -112,9 +112,26 @@ So we put them in their own `dependencies` module (`app/dependencies.py`).
We will now use a simple dependency to read a custom `X-Token` header:
-```Python hl_lines="1 4-6"
-{!../../../docs_src/bigger_applications/app/dependencies.py!}
-```
+=== "Python 3.9+"
+
+ ```Python hl_lines="3 6-8"
+ {!> ../../../docs_src/bigger_applications/app_an_py39/dependencies.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="1 5-7"
+ {!> ../../../docs_src/bigger_applications/app_an/dependencies.py!}
+ ```
+
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="1 4-6"
+ {!> ../../../docs_src/bigger_applications/app/dependencies.py!}
+ ```
!!! tip
We are using an invented header to simplify this example.
@@ -189,7 +206,7 @@ The end result is that the item paths are now:
### Import the dependencies
-This codes lives in the module `app.routers.items`, the file `app/routers/items.py`.
+This code lives in the module `app.routers.items`, the file `app/routers/items.py`.
And we need to get the dependency function from the module `app.dependencies`, the file `app/dependencies.py`.
diff --git a/docs/en/docs/tutorial/body-fields.md b/docs/en/docs/tutorial/body-fields.md
index 0cfe576d6..8966032ff 100644
--- a/docs/en/docs/tutorial/body-fields.md
+++ b/docs/en/docs/tutorial/body-fields.md
@@ -6,18 +6,42 @@ The same way you can declare additional validation and metadata in *path operati
First, you have to import it:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001.py!}
+ {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="4"
+ {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="4"
+ {!> ../../../docs_src/body_fields/tutorial001_an.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="2"
{!> ../../../docs_src/body_fields/tutorial001_py310.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="4"
+ {!> ../../../docs_src/body_fields/tutorial001.py!}
+ ```
+
!!! warning
Notice that `Field` is imported directly from `pydantic`, not from `fastapi` as are all the rest (`Query`, `Path`, `Body`, etc).
@@ -25,18 +49,42 @@ First, you have to import it:
You can then use `Field` with model attributes:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001.py!}
+ {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="11-14"
+ {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="12-15"
+ {!> ../../../docs_src/body_fields/tutorial001_an.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="9-12"
{!> ../../../docs_src/body_fields/tutorial001_py310.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="11-14"
+ {!> ../../../docs_src/body_fields/tutorial001.py!}
+ ```
+
`Field` works the same way as `Query`, `Path` and `Body`, it has all the same parameters, etc.
!!! note "Technical Details"
diff --git a/docs/en/docs/tutorial/body-multiple-params.md b/docs/en/docs/tutorial/body-multiple-params.md
index 31dd27fed..b214092c9 100644
--- a/docs/en/docs/tutorial/body-multiple-params.md
+++ b/docs/en/docs/tutorial/body-multiple-params.md
@@ -8,18 +8,42 @@ First, of course, you can mix `Path`, `Query` and request body parameter declara
And you can also declare body parameters as optional, by setting the default to `None`:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
+
+ ```Python hl_lines="18-20"
+ {!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="18-20"
+ {!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
```Python hl_lines="19-21"
- {!> ../../../docs_src/body_multiple_params/tutorial001.py!}
+ {!> ../../../docs_src/body_multiple_params/tutorial001_an.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="17-19"
{!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="19-21"
+ {!> ../../../docs_src/body_multiple_params/tutorial001.py!}
+ ```
+
!!! note
Notice that, in this case, the `item` that would be taken from the body is optional. As it has a `None` default value.
@@ -38,16 +62,16 @@ In the previous example, the *path operations* would expect a JSON body with the
But you can also declare multiple body parameters, e.g. `item` and `user`:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="22"
- {!> ../../../docs_src/body_multiple_params/tutorial002.py!}
+ ```Python hl_lines="20"
+ {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!}
+ ```Python hl_lines="22"
+ {!> ../../../docs_src/body_multiple_params/tutorial002.py!}
```
In this case, **FastAPI** will notice that there are more than one body parameters in the function (two parameters that are Pydantic models).
@@ -87,18 +111,42 @@ If you declare it as is, because it is a singular value, **FastAPI** will assume
But you can instruct **FastAPI** to treat it as another body key using `Body`:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="22"
- {!> ../../../docs_src/body_multiple_params/tutorial003.py!}
+ ```Python hl_lines="23"
+ {!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.9+"
+
+ ```Python hl_lines="23"
+ {!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="24"
+ {!> ../../../docs_src/body_multiple_params/tutorial003_an.py!}
+ ```
+
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="20"
{!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="22"
+ {!> ../../../docs_src/body_multiple_params/tutorial003.py!}
+ ```
+
In this case, **FastAPI** will expect a body like:
```JSON
@@ -137,18 +185,42 @@ q: str | None = None
For example:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004.py!}
+ {!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.9+"
- ```Python hl_lines="26"
+ ```Python hl_lines="27"
+ {!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="28"
+ {!> ../../../docs_src/body_multiple_params/tutorial004_an.py!}
+ ```
+
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="25"
{!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="27"
+ {!> ../../../docs_src/body_multiple_params/tutorial004.py!}
+ ```
+
!!! info
`Body` also has all the same extra validation and metadata parameters as `Query`,`Path` and others you will see later.
@@ -166,18 +238,42 @@ item: Item = Body(embed=True)
as in:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
```Python hl_lines="17"
- {!> ../../../docs_src/body_multiple_params/tutorial005.py!}
+ {!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="17"
+ {!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="18"
+ {!> ../../../docs_src/body_multiple_params/tutorial005_an.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="15"
{!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="17"
+ {!> ../../../docs_src/body_multiple_params/tutorial005.py!}
+ ```
+
In this case **FastAPI** will expect a body like:
```JSON hl_lines="2"
diff --git a/docs/en/docs/tutorial/body-nested-models.md b/docs/en/docs/tutorial/body-nested-models.md
index d51f171d6..ffa0c0d0e 100644
--- a/docs/en/docs/tutorial/body-nested-models.md
+++ b/docs/en/docs/tutorial/body-nested-models.md
@@ -6,16 +6,16 @@ With **FastAPI**, you can define, validate, document, and use arbitrarily deeply
You can define an attribute to be a subtype. For example, a Python `list`:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial001.py!}
+ ```Python hl_lines="12"
+ {!> ../../../docs_src/body_nested_models/tutorial001_py310.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="12"
- {!> ../../../docs_src/body_nested_models/tutorial001_py310.py!}
+ ```Python hl_lines="14"
+ {!> ../../../docs_src/body_nested_models/tutorial001.py!}
```
This will make `tags` be a list, although it doesn't declare the type of the elements of the list.
@@ -61,22 +61,22 @@ Use that same standard syntax for model attributes with internal types.
So, in our example, we can make `tags` be specifically a "list of strings":
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial002.py!}
+ ```Python hl_lines="12"
+ {!> ../../../docs_src/body_nested_models/tutorial002_py310.py!}
```
-=== "Python 3.9 and above"
+=== "Python 3.9+"
```Python hl_lines="14"
{!> ../../../docs_src/body_nested_models/tutorial002_py39.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="12"
- {!> ../../../docs_src/body_nested_models/tutorial002_py310.py!}
+ ```Python hl_lines="14"
+ {!> ../../../docs_src/body_nested_models/tutorial002.py!}
```
## Set types
@@ -87,22 +87,22 @@ And Python has a special data type for sets of unique items, the `set`.
Then we can declare `tags` as a set of strings:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="1 14"
- {!> ../../../docs_src/body_nested_models/tutorial003.py!}
+ ```Python hl_lines="12"
+ {!> ../../../docs_src/body_nested_models/tutorial003_py310.py!}
```
-=== "Python 3.9 and above"
+=== "Python 3.9+"
```Python hl_lines="14"
{!> ../../../docs_src/body_nested_models/tutorial003_py39.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="12"
- {!> ../../../docs_src/body_nested_models/tutorial003_py310.py!}
+ ```Python hl_lines="1 14"
+ {!> ../../../docs_src/body_nested_models/tutorial003.py!}
```
With this, even if you receive a request with duplicate data, it will be converted to a set of unique items.
@@ -125,44 +125,44 @@ All that, arbitrarily nested.
For example, we can define an `Image` model:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="9-11"
- {!> ../../../docs_src/body_nested_models/tutorial004.py!}
+ ```Python hl_lines="7-9"
+ {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!}
```
-=== "Python 3.9 and above"
+=== "Python 3.9+"
```Python hl_lines="9-11"
{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="7-9"
- {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!}
+ ```Python hl_lines="9-11"
+ {!> ../../../docs_src/body_nested_models/tutorial004.py!}
```
### Use the submodel as a type
And then we can use it as the type of an attribute:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial004.py!}
+ ```Python hl_lines="18"
+ {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!}
```
-=== "Python 3.9 and above"
+=== "Python 3.9+"
```Python hl_lines="20"
{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="18"
- {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!}
+ ```Python hl_lines="20"
+ {!> ../../../docs_src/body_nested_models/tutorial004.py!}
```
This would mean that **FastAPI** would expect a body similar to:
@@ -196,22 +196,22 @@ To see all the options you have, checkout the docs for ../../../docs_src/body_nested_models/tutorial005.py!}
+ ```Python hl_lines="2 8"
+ {!> ../../../docs_src/body_nested_models/tutorial005_py310.py!}
```
-=== "Python 3.9 and above"
+=== "Python 3.9+"
```Python hl_lines="4 10"
{!> ../../../docs_src/body_nested_models/tutorial005_py39.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="2 8"
- {!> ../../../docs_src/body_nested_models/tutorial005_py310.py!}
+ ```Python hl_lines="4 10"
+ {!> ../../../docs_src/body_nested_models/tutorial005.py!}
```
The string will be checked to be a valid URL, and documented in JSON Schema / OpenAPI as such.
@@ -220,22 +220,22 @@ The string will be checked to be a valid URL, and documented in JSON Schema / Op
You can also use Pydantic models as subtypes of `list`, `set`, etc:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial006.py!}
+ ```Python hl_lines="18"
+ {!> ../../../docs_src/body_nested_models/tutorial006_py310.py!}
```
-=== "Python 3.9 and above"
+=== "Python 3.9+"
```Python hl_lines="20"
{!> ../../../docs_src/body_nested_models/tutorial006_py39.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="18"
- {!> ../../../docs_src/body_nested_models/tutorial006_py310.py!}
+ ```Python hl_lines="20"
+ {!> ../../../docs_src/body_nested_models/tutorial006.py!}
```
This will expect (convert, validate, document, etc) a JSON body like:
@@ -271,22 +271,22 @@ This will expect (convert, validate, document, etc) a JSON body like:
You can define arbitrarily deeply nested models:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="9 14 20 23 27"
- {!> ../../../docs_src/body_nested_models/tutorial007.py!}
+ ```Python hl_lines="7 12 18 21 25"
+ {!> ../../../docs_src/body_nested_models/tutorial007_py310.py!}
```
-=== "Python 3.9 and above"
+=== "Python 3.9+"
```Python hl_lines="9 14 20 23 27"
{!> ../../../docs_src/body_nested_models/tutorial007_py39.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="7 12 18 21 25"
- {!> ../../../docs_src/body_nested_models/tutorial007_py310.py!}
+ ```Python hl_lines="9 14 20 23 27"
+ {!> ../../../docs_src/body_nested_models/tutorial007.py!}
```
!!! info
@@ -308,16 +308,16 @@ images: list[Image]
as in:
-=== "Python 3.6 and above"
+=== "Python 3.9+"
- ```Python hl_lines="15"
- {!> ../../../docs_src/body_nested_models/tutorial008.py!}
+ ```Python hl_lines="13"
+ {!> ../../../docs_src/body_nested_models/tutorial008_py39.py!}
```
-=== "Python 3.9 and above"
+=== "Python 3.6+"
- ```Python hl_lines="13"
- {!> ../../../docs_src/body_nested_models/tutorial008_py39.py!}
+ ```Python hl_lines="15"
+ {!> ../../../docs_src/body_nested_models/tutorial008.py!}
```
## Editor support everywhere
@@ -348,16 +348,16 @@ That's what we are going to see here.
In this case, you would accept any `dict` as long as it has `int` keys with `float` values:
-=== "Python 3.6 and above"
+=== "Python 3.9+"
- ```Python hl_lines="9"
- {!> ../../../docs_src/body_nested_models/tutorial009.py!}
+ ```Python hl_lines="7"
+ {!> ../../../docs_src/body_nested_models/tutorial009_py39.py!}
```
-=== "Python 3.9 and above"
+=== "Python 3.6+"
- ```Python hl_lines="7"
- {!> ../../../docs_src/body_nested_models/tutorial009_py39.py!}
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/body_nested_models/tutorial009.py!}
```
!!! tip
diff --git a/docs/en/docs/tutorial/body-updates.md b/docs/en/docs/tutorial/body-updates.md
index 7d8675060..a32948db1 100644
--- a/docs/en/docs/tutorial/body-updates.md
+++ b/docs/en/docs/tutorial/body-updates.md
@@ -6,22 +6,22 @@ To update an item you can use the ../../../docs_src/body_updates/tutorial001.py!}
+ ```Python hl_lines="28-33"
+ {!> ../../../docs_src/body_updates/tutorial001_py310.py!}
```
-=== "Python 3.9 and above"
+=== "Python 3.9+"
```Python hl_lines="30-35"
{!> ../../../docs_src/body_updates/tutorial001_py39.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="28-33"
- {!> ../../../docs_src/body_updates/tutorial001_py310.py!}
+ ```Python hl_lines="30-35"
+ {!> ../../../docs_src/body_updates/tutorial001.py!}
```
`PUT` is used to receive data that should replace the existing data.
@@ -67,22 +67,22 @@ That would generate a `dict` with only the data that was set when creating the `
Then you can use this to generate a `dict` with only the data that was set (sent in the request), omitting default values:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="34"
- {!> ../../../docs_src/body_updates/tutorial002.py!}
+ ```Python hl_lines="32"
+ {!> ../../../docs_src/body_updates/tutorial002_py310.py!}
```
-=== "Python 3.9 and above"
+=== "Python 3.9+"
```Python hl_lines="34"
{!> ../../../docs_src/body_updates/tutorial002_py39.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="32"
- {!> ../../../docs_src/body_updates/tutorial002_py310.py!}
+ ```Python hl_lines="34"
+ {!> ../../../docs_src/body_updates/tutorial002.py!}
```
### Using Pydantic's `update` parameter
@@ -91,22 +91,22 @@ Now, you can create a copy of the existing model using `.copy()`, and pass the `
Like `stored_item_model.copy(update=update_data)`:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="35"
- {!> ../../../docs_src/body_updates/tutorial002.py!}
+ ```Python hl_lines="33"
+ {!> ../../../docs_src/body_updates/tutorial002_py310.py!}
```
-=== "Python 3.9 and above"
+=== "Python 3.9+"
```Python hl_lines="35"
{!> ../../../docs_src/body_updates/tutorial002_py39.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="33"
- {!> ../../../docs_src/body_updates/tutorial002_py310.py!}
+ ```Python hl_lines="35"
+ {!> ../../../docs_src/body_updates/tutorial002.py!}
```
### Partial updates recap
@@ -124,22 +124,22 @@ In summary, to apply partial updates you would:
* Save the data to your DB.
* Return the updated model.
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="30-37"
- {!> ../../../docs_src/body_updates/tutorial002.py!}
+ ```Python hl_lines="28-35"
+ {!> ../../../docs_src/body_updates/tutorial002_py310.py!}
```
-=== "Python 3.9 and above"
+=== "Python 3.9+"
```Python hl_lines="30-37"
{!> ../../../docs_src/body_updates/tutorial002_py39.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="28-35"
- {!> ../../../docs_src/body_updates/tutorial002_py310.py!}
+ ```Python hl_lines="30-37"
+ {!> ../../../docs_src/body_updates/tutorial002.py!}
```
!!! tip
diff --git a/docs/en/docs/tutorial/body.md b/docs/en/docs/tutorial/body.md
index 509005936..172b91fdf 100644
--- a/docs/en/docs/tutorial/body.md
+++ b/docs/en/docs/tutorial/body.md
@@ -19,16 +19,16 @@ To declare a **request** body, you use ../../../docs_src/body/tutorial001.py!}
+ ```Python hl_lines="2"
+ {!> ../../../docs_src/body/tutorial001_py310.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="2"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
+ ```Python hl_lines="4"
+ {!> ../../../docs_src/body/tutorial001.py!}
```
## Create your data model
@@ -37,16 +37,16 @@ Then you declare your data model as a class that inherits from `BaseModel`.
Use standard Python types for all the attributes:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="7-11"
- {!> ../../../docs_src/body/tutorial001.py!}
+ ```Python hl_lines="5-9"
+ {!> ../../../docs_src/body/tutorial001_py310.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="5-9"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
+ ```Python hl_lines="7-11"
+ {!> ../../../docs_src/body/tutorial001.py!}
```
The same as when declaring query parameters, when a model attribute has a default value, it is not required. Otherwise, it is required. Use `None` to make it just optional.
@@ -75,16 +75,16 @@ For example, this model above declares a JSON "`object`" (or Python `dict`) like
To add it to your *path operation*, declare it the same way you declared path and query parameters:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="18"
- {!> ../../../docs_src/body/tutorial001.py!}
+ ```Python hl_lines="16"
+ {!> ../../../docs_src/body/tutorial001_py310.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="16"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
+ ```Python hl_lines="18"
+ {!> ../../../docs_src/body/tutorial001.py!}
```
...and declare its type as the model you created, `Item`.
@@ -149,16 +149,16 @@ But you would get the same editor support with ../../../docs_src/body/tutorial002.py!}
+ ```Python hl_lines="19"
+ {!> ../../../docs_src/body/tutorial002_py310.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="19"
- {!> ../../../docs_src/body/tutorial002_py310.py!}
+ ```Python hl_lines="21"
+ {!> ../../../docs_src/body/tutorial002.py!}
```
## Request body + path parameters
@@ -167,16 +167,16 @@ You can declare path parameters and request body at the same time.
**FastAPI** will recognize that the function parameters that match path parameters should be **taken from the path**, and that function parameters that are declared to be Pydantic models should be **taken from the request body**.
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="17-18"
- {!> ../../../docs_src/body/tutorial003.py!}
+ ```Python hl_lines="15-16"
+ {!> ../../../docs_src/body/tutorial003_py310.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="15-16"
- {!> ../../../docs_src/body/tutorial003_py310.py!}
+ ```Python hl_lines="17-18"
+ {!> ../../../docs_src/body/tutorial003.py!}
```
## Request body + path + query parameters
@@ -185,16 +185,16 @@ You can also declare **body**, **path** and **query** parameters, all at the sam
**FastAPI** will recognize each of them and take the data from the correct place.
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="18"
- {!> ../../../docs_src/body/tutorial004.py!}
+ ```Python hl_lines="16"
+ {!> ../../../docs_src/body/tutorial004_py310.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="16"
- {!> ../../../docs_src/body/tutorial004_py310.py!}
+ ```Python hl_lines="18"
+ {!> ../../../docs_src/body/tutorial004.py!}
```
The function parameters will be recognized as follows:
diff --git a/docs/en/docs/tutorial/cookie-params.md b/docs/en/docs/tutorial/cookie-params.md
index 221cdfffb..111e93458 100644
--- a/docs/en/docs/tutorial/cookie-params.md
+++ b/docs/en/docs/tutorial/cookie-params.md
@@ -6,36 +6,84 @@ You can define Cookie parameters the same way you define `Query` and `Path` para
First import `Cookie`:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001.py!}
+ {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="3"
+ {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="3"
+ {!> ../../../docs_src/cookie_params/tutorial001_an.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="1"
{!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="3"
+ {!> ../../../docs_src/cookie_params/tutorial001.py!}
+ ```
+
## Declare `Cookie` parameters
Then declare the cookie parameters using the same structure as with `Path` and `Query`.
The first value is the default value, you can pass all the extra validation or annotation parameters:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
```Python hl_lines="9"
- {!> ../../../docs_src/cookie_params/tutorial001.py!}
+ {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="10"
+ {!> ../../../docs_src/cookie_params/tutorial001_an.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="7"
{!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/cookie_params/tutorial001.py!}
+ ```
+
!!! note "Technical Details"
`Cookie` is a "sister" class of `Path` and `Query`. It also inherits from the same common `Param` class.
diff --git a/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md
index fb41ba1f6..498d935fe 100644
--- a/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md
+++ b/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md
@@ -6,18 +6,42 @@ Before diving deeper into the **Dependency Injection** system, let's upgrade the
In the previous example, we were returning a `dict` from our dependency ("dependable"):
-=== "Python 3.6 and above"
+=== "Python 3.10+"
```Python hl_lines="9"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
+ {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="11"
+ {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="12"
+ {!> ../../../docs_src/dependencies/tutorial001_an.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="7"
{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="11"
+ {!> ../../../docs_src/dependencies/tutorial001.py!}
+ ```
+
But then we get a `dict` in the parameter `commons` of the *path operation function*.
And we know that editors can't provide a lot of support (like completion) for `dict`s, because they can't know their keys and value types.
@@ -79,46 +103,118 @@ That also applies to callables with no parameters at all. The same as it would b
Then, we can change the dependency "dependable" `common_parameters` from above to the class `CommonQueryParams`:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
```Python hl_lines="11-15"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
+ {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="11-15"
+ {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
+
+ ```Python hl_lines="12-16"
+ {!> ../../../docs_src/dependencies/tutorial002_an.py!}
+ ```
+
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="9-13"
{!> ../../../docs_src/dependencies/tutorial002_py310.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="11-15"
+ {!> ../../../docs_src/dependencies/tutorial002.py!}
+ ```
+
Pay attention to the `__init__` method used to create the instance of the class:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
```Python hl_lines="12"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
+ {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="12"
+ {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
+
+ ```Python hl_lines="13"
+ {!> ../../../docs_src/dependencies/tutorial002_an.py!}
+ ```
+
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="10"
{!> ../../../docs_src/dependencies/tutorial002_py310.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="12"
+ {!> ../../../docs_src/dependencies/tutorial002.py!}
+ ```
+
...it has the same parameters as our previous `common_parameters`:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
+
+ ```Python hl_lines="8"
+ {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
```Python hl_lines="9"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
+ {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
+
+ ```Python hl_lines="10"
+ {!> ../../../docs_src/dependencies/tutorial001_an.py!}
+ ```
+
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="6"
{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/dependencies/tutorial001.py!}
+ ```
+
Those parameters are what **FastAPI** will use to "solve" the dependency.
In both cases, it will have:
@@ -133,32 +229,67 @@ In both cases the data will be converted, validated, documented on the OpenAPI s
Now you can declare your dependency using this class.
-=== "Python 3.6 and above"
+=== "Python 3.10+"
```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
+ {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="19"
+ {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="20"
+ {!> ../../../docs_src/dependencies/tutorial002_an.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="17"
{!> ../../../docs_src/dependencies/tutorial002_py310.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="19"
+ {!> ../../../docs_src/dependencies/tutorial002.py!}
+ ```
+
**FastAPI** calls the `CommonQueryParams` class. This creates an "instance" of that class and the instance will be passed as the parameter `commons` to your function.
## Type annotation vs `Depends`
Notice how we write `CommonQueryParams` twice in the above code:
-```Python
-commons: CommonQueryParams = Depends(CommonQueryParams)
-```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python
+ commons: CommonQueryParams = Depends(CommonQueryParams)
+ ```
+
+=== "Python 3.6+"
+
+ ```Python
+ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+ ```
The last `CommonQueryParams`, in:
```Python
-... = Depends(CommonQueryParams)
+... Depends(CommonQueryParams)
```
...is what **FastAPI** will actually use to know what is the dependency.
@@ -169,32 +300,78 @@ From it is that FastAPI will extract the declared parameters and that is what Fa
In this case, the first `CommonQueryParams`, in:
-```Python
-commons: CommonQueryParams ...
-```
+=== "Python 3.6+"
+
+ ```Python
+ commons: Annotated[CommonQueryParams, ...
+ ```
-...doesn't have any special meaning for **FastAPI**. FastAPI won't use it for data conversion, validation, etc. (as it is using the `= Depends(CommonQueryParams)` for that).
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python
+ commons: CommonQueryParams ...
+ ```
+
+...doesn't have any special meaning for **FastAPI**. FastAPI won't use it for data conversion, validation, etc. (as it is using the `Depends(CommonQueryParams)` for that).
You could actually write just:
-```Python
-commons = Depends(CommonQueryParams)
-```
+=== "Python 3.6+"
+
+ ```Python
+ commons: Annotated[Any, Depends(CommonQueryParams)]
+ ```
+
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python
+ commons = Depends(CommonQueryParams)
+ ```
..as in:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial003.py!}
+ {!> ../../../docs_src/dependencies/tutorial003_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="19"
+ {!> ../../../docs_src/dependencies/tutorial003_an_py39.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
+
+ ```Python hl_lines="20"
+ {!> ../../../docs_src/dependencies/tutorial003_an.py!}
+ ```
+
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="17"
{!> ../../../docs_src/dependencies/tutorial003_py310.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="19"
+ {!> ../../../docs_src/dependencies/tutorial003.py!}
+ ```
+
But declaring the type is encouraged as that way your editor will know what will be passed as the parameter `commons`, and then it can help you with code completion, type checks, etc:
@@ -203,9 +380,20 @@ But declaring the type is encouraged as that way your editor will know what will
But you see that we are having some code repetition here, writing `CommonQueryParams` twice:
-```Python
-commons: CommonQueryParams = Depends(CommonQueryParams)
-```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python
+ commons: CommonQueryParams = Depends(CommonQueryParams)
+ ```
+
+=== "Python 3.6+"
+
+ ```Python
+ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+ ```
**FastAPI** provides a shortcut for these cases, in where the dependency is *specifically* a class that **FastAPI** will "call" to create an instance of the class itself.
@@ -213,32 +401,78 @@ For those specific cases, you can do the following:
Instead of writing:
-```Python
-commons: CommonQueryParams = Depends(CommonQueryParams)
-```
+=== "Python 3.6+"
+
+ ```Python
+ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+ ```
+
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python
+ commons: CommonQueryParams = Depends(CommonQueryParams)
+ ```
...you write:
-```Python
-commons: CommonQueryParams = Depends()
-```
+=== "Python 3.6+"
+
+ ```Python
+ commons: Annotated[CommonQueryParams, Depends()]
+ ```
-You declare the dependency as the type of the parameter, and you use `Depends()` as its "default" value (that after the `=`) for that function's parameter, without any parameter in `Depends()`, instead of having to write the full class *again* inside of `Depends(CommonQueryParams)`.
+=== "Python 3.6 non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python
+ commons: CommonQueryParams = Depends()
+ ```
+
+You declare the dependency as the type of the parameter, and you use `Depends()` without any parameter, instead of having to write the full class *again* inside of `Depends(CommonQueryParams)`.
The same example would then look like:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial004.py!}
+ {!> ../../../docs_src/dependencies/tutorial004_an_py310.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.9+"
+
+ ```Python hl_lines="19"
+ {!> ../../../docs_src/dependencies/tutorial004_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="20"
+ {!> ../../../docs_src/dependencies/tutorial004_an.py!}
+ ```
+
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="17"
{!> ../../../docs_src/dependencies/tutorial004_py310.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="19"
+ {!> ../../../docs_src/dependencies/tutorial004.py!}
+ ```
+
...and **FastAPI** will know what to do.
!!! tip
diff --git a/docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
index a1bbcc6c7..935555339 100644
--- a/docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
+++ b/docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
@@ -14,9 +14,26 @@ The *path operation decorator* receives an optional argument `dependencies`.
It should be a `list` of `Depends()`:
-```Python hl_lines="17"
-{!../../../docs_src/dependencies/tutorial006.py!}
-```
+=== "Python 3.9+"
+
+ ```Python hl_lines="19"
+ {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="18"
+ {!> ../../../docs_src/dependencies/tutorial006_an.py!}
+ ```
+
+=== "Python 3.6 non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="17"
+ {!> ../../../docs_src/dependencies/tutorial006.py!}
+ ```
These dependencies will be executed/solved the same way normal dependencies. But their value (if they return any) won't be passed to your *path operation function*.
@@ -40,17 +57,51 @@ You can use the same dependency *functions* you use normally.
They can declare request requirements (like headers) or other sub-dependencies:
-```Python hl_lines="6 11"
-{!../../../docs_src/dependencies/tutorial006.py!}
-```
+=== "Python 3.9+"
+
+ ```Python hl_lines="8 13"
+ {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="7 12"
+ {!> ../../../docs_src/dependencies/tutorial006_an.py!}
+ ```
+
+=== "Python 3.6 non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="6 11"
+ {!> ../../../docs_src/dependencies/tutorial006.py!}
+ ```
### Raise exceptions
These dependencies can `raise` exceptions, the same as normal dependencies:
-```Python hl_lines="8 13"
-{!../../../docs_src/dependencies/tutorial006.py!}
-```
+=== "Python 3.9+"
+
+ ```Python hl_lines="10 15"
+ {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="9 14"
+ {!> ../../../docs_src/dependencies/tutorial006_an.py!}
+ ```
+
+=== "Python 3.6 non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="8 13"
+ {!> ../../../docs_src/dependencies/tutorial006.py!}
+ ```
### Return values
@@ -58,9 +109,26 @@ And they can return values or not, the values won't be used.
So, you can re-use a normal dependency (that returns a value) you already use somewhere else, and even though the value won't be used, the dependency will be executed:
-```Python hl_lines="9 14"
-{!../../../docs_src/dependencies/tutorial006.py!}
-```
+=== "Python 3.9+"
+
+ ```Python hl_lines="11 16"
+ {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="10 15"
+ {!> ../../../docs_src/dependencies/tutorial006_an.py!}
+ ```
+
+=== "Python 3.6 non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="9 14"
+ {!> ../../../docs_src/dependencies/tutorial006.py!}
+ ```
## Dependencies for a group of *path operations*
diff --git a/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md
index a7300f0b7..8a5422ac8 100644
--- a/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md
+++ b/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md
@@ -66,9 +66,26 @@ You can have sub-dependencies and "trees" of sub-dependencies of any size and sh
For example, `dependency_c` can have a dependency on `dependency_b`, and `dependency_b` on `dependency_a`:
-```Python hl_lines="4 12 20"
-{!../../../docs_src/dependencies/tutorial008.py!}
-```
+=== "Python 3.9+"
+
+ ```Python hl_lines="6 14 22"
+ {!> ../../../docs_src/dependencies/tutorial008_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="5 13 21"
+ {!> ../../../docs_src/dependencies/tutorial008_an.py!}
+ ```
+
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="4 12 20"
+ {!> ../../../docs_src/dependencies/tutorial008.py!}
+ ```
And all of them can use `yield`.
@@ -76,9 +93,26 @@ In this case `dependency_c`, to execute its exit code, needs the value from `dep
And, in turn, `dependency_b` needs the value from `dependency_a` (here named `dep_a`) to be available for its exit code.
-```Python hl_lines="16-17 24-25"
-{!../../../docs_src/dependencies/tutorial008.py!}
-```
+=== "Python 3.9+"
+
+ ```Python hl_lines="18-19 26-27"
+ {!> ../../../docs_src/dependencies/tutorial008_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="17-18 25-26"
+ {!> ../../../docs_src/dependencies/tutorial008_an.py!}
+ ```
+
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="16-17 24-25"
+ {!> ../../../docs_src/dependencies/tutorial008.py!}
+ ```
The same way, you could have dependencies with `yield` and `return` mixed.
diff --git a/docs/en/docs/tutorial/dependencies/global-dependencies.md b/docs/en/docs/tutorial/dependencies/global-dependencies.md
index bcd61d52b..0989b31d4 100644
--- a/docs/en/docs/tutorial/dependencies/global-dependencies.md
+++ b/docs/en/docs/tutorial/dependencies/global-dependencies.md
@@ -6,9 +6,26 @@ Similar to the way you can [add `dependencies` to the *path operation decorators
In that case, they will be applied to all the *path operations* in the application:
-```Python hl_lines="15"
-{!../../../docs_src/dependencies/tutorial012.py!}
-```
+=== "Python 3.9+"
+
+ ```Python hl_lines="16"
+ {!> ../../../docs_src/dependencies/tutorial012_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="16"
+ {!> ../../../docs_src/dependencies/tutorial012_an.py!}
+ ```
+
+=== "Python 3.6 non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="15"
+ {!> ../../../docs_src/dependencies/tutorial012.py!}
+ ```
And all the ideas in the section about [adding `dependencies` to the *path operation decorators*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} still apply, but in this case, to all of the *path operations* in the app.
diff --git a/docs/en/docs/tutorial/dependencies/index.md b/docs/en/docs/tutorial/dependencies/index.md
index 5078c0096..4f5ecea66 100644
--- a/docs/en/docs/tutorial/dependencies/index.md
+++ b/docs/en/docs/tutorial/dependencies/index.md
@@ -31,18 +31,42 @@ Let's first focus on the dependency.
It is just a function that can take all the same parameters that a *path operation function* can take:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
+
+ ```Python hl_lines="8-9"
+ {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
```Python hl_lines="8-11"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
+ {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
+
+ ```Python hl_lines="9-12"
+ {!> ../../../docs_src/dependencies/tutorial001_an.py!}
+ ```
+
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="6-7"
{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="8-11"
+ {!> ../../../docs_src/dependencies/tutorial001.py!}
+ ```
+
That's it.
**2 lines**.
@@ -61,42 +85,99 @@ In this case, this dependency expects:
And then it just returns a `dict` containing those values.
+!!! info
+ FastAPI added support for `Annotated` (and started recommending it) in version 0.95.0.
+
+ If you have an older version, you would get errors when trying to use `Annotated`.
+
+ Make sure you [Upgrade the FastAPI version](../../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} to at least 0.95.1 before using `Annotated`.
+
### Import `Depends`
-=== "Python 3.6 and above"
+=== "Python 3.10+"
```Python hl_lines="3"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
+ {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="3"
+ {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="3"
+ {!> ../../../docs_src/dependencies/tutorial001_an.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="1"
{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="3"
+ {!> ../../../docs_src/dependencies/tutorial001.py!}
+ ```
+
### Declare the dependency, in the "dependant"
The same way you use `Body`, `Query`, etc. with your *path operation function* parameters, use `Depends` with a new parameter:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
+
+ ```Python hl_lines="13 18"
+ {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
```Python hl_lines="15 20"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
+ {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
+
+ ```Python hl_lines="16 21"
+ {!> ../../../docs_src/dependencies/tutorial001_an.py!}
+ ```
+
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="11 16"
{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="15 20"
+ {!> ../../../docs_src/dependencies/tutorial001.py!}
+ ```
+
Although you use `Depends` in the parameters of your function the same way you use `Body`, `Query`, etc, `Depends` works a bit differently.
You only give `Depends` a single parameter.
This parameter must be something like a function.
+You **don't call it** directly (don't add the parenthesis at the end), you just pass it as a parameter to `Depends()`.
+
And that function takes parameters in the same way that *path operation functions* do.
!!! tip
@@ -126,6 +207,45 @@ This way you write shared code once and **FastAPI** takes care of calling it for
You just pass it to `Depends` and **FastAPI** knows how to do the rest.
+## Share `Annotated` dependencies
+
+In the examples above, you see that there's a tiny bit of **code duplication**.
+
+When you need to use the `common_parameters()` dependency, you have to write the whole parameter with the type annotation and `Depends()`:
+
+```Python
+commons: Annotated[dict, Depends(common_parameters)]
+```
+
+But because we are using `Annotated`, we can store that `Annotated` value in a variable and use it in multiple places:
+
+=== "Python 3.10+"
+
+ ```Python hl_lines="12 16 21"
+ {!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="14 18 23"
+ {!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="15 19 24"
+ {!> ../../../docs_src/dependencies/tutorial001_02_an.py!}
+ ```
+
+!!! tip
+ This is just standard Python, it's called a "type alias", it's actually not specific to **FastAPI**.
+
+ But because **FastAPI** is based on the Python standards, including `Annotated`, you can use this trick in your code. 😎
+
+The dependencies will keep working as expected, and the **best part** is that the **type information will be preserved**, which means that your editor will be able to keep providing you with **autocompletion**, **inline errors**, etc. The same for other tools like `mypy`.
+
+This will be especially useful when you use it in a **large code base** where you use **the same dependencies** over and over again in **many *path operations***.
+
## To `async` or not to `async`
As dependencies will also be called by **FastAPI** (the same as your *path operation functions*), the same rules apply while defining your functions.
diff --git a/docs/en/docs/tutorial/dependencies/sub-dependencies.md b/docs/en/docs/tutorial/dependencies/sub-dependencies.md
index a5b40c9ad..b50de1a46 100644
--- a/docs/en/docs/tutorial/dependencies/sub-dependencies.md
+++ b/docs/en/docs/tutorial/dependencies/sub-dependencies.md
@@ -10,18 +10,42 @@ They can be as **deep** as you need them to be.
You could create a first dependency ("dependable") like:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
```Python hl_lines="8-9"
- {!> ../../../docs_src/dependencies/tutorial005.py!}
+ {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.9+"
+
+ ```Python hl_lines="8-9"
+ {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="9-10"
+ {!> ../../../docs_src/dependencies/tutorial005_an.py!}
+ ```
+
+=== "Python 3.10 non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="6-7"
{!> ../../../docs_src/dependencies/tutorial005_py310.py!}
```
+=== "Python 3.6 non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="8-9"
+ {!> ../../../docs_src/dependencies/tutorial005.py!}
+ ```
+
It declares an optional query parameter `q` as a `str`, and then it just returns it.
This is quite simple (not very useful), but will help us focus on how the sub-dependencies work.
@@ -30,18 +54,42 @@ This is quite simple (not very useful), but will help us focus on how the sub-de
Then you can create another dependency function (a "dependable") that at the same time declares a dependency of its own (so it is a "dependant" too):
-=== "Python 3.6 and above"
+=== "Python 3.10+"
```Python hl_lines="13"
- {!> ../../../docs_src/dependencies/tutorial005.py!}
+ {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="13"
+ {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
+
+ ```Python hl_lines="14"
+ {!> ../../../docs_src/dependencies/tutorial005_an.py!}
+ ```
+
+=== "Python 3.10 non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="11"
{!> ../../../docs_src/dependencies/tutorial005_py310.py!}
```
+=== "Python 3.6 non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="13"
+ {!> ../../../docs_src/dependencies/tutorial005.py!}
+ ```
+
Let's focus on the parameters declared:
* Even though this function is a dependency ("dependable") itself, it also declares another dependency (it "depends" on something else).
@@ -53,18 +101,42 @@ Let's focus on the parameters declared:
Then we can use the dependency with:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="22"
- {!> ../../../docs_src/dependencies/tutorial005.py!}
+ ```Python hl_lines="23"
+ {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.9+"
+
+ ```Python hl_lines="23"
+ {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="24"
+ {!> ../../../docs_src/dependencies/tutorial005_an.py!}
+ ```
+
+=== "Python 3.10 non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="19"
{!> ../../../docs_src/dependencies/tutorial005_py310.py!}
```
+=== "Python 3.6 non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="22"
+ {!> ../../../docs_src/dependencies/tutorial005.py!}
+ ```
+
!!! info
Notice that we are only declaring one dependency in the *path operation function*, the `query_or_cookie_extractor`.
@@ -89,10 +161,22 @@ And it will save the returned value in a ../../../docs_src/encoder/tutorial001.py!}
+ ```Python hl_lines="4 21"
+ {!> ../../../docs_src/encoder/tutorial001_py310.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="4 21"
- {!> ../../../docs_src/encoder/tutorial001_py310.py!}
+ ```Python hl_lines="5 22"
+ {!> ../../../docs_src/encoder/tutorial001.py!}
```
In this example, it would convert the Pydantic model to a `dict`, and the `datetime` to a `str`.
diff --git a/docs/en/docs/tutorial/extra-data-types.md b/docs/en/docs/tutorial/extra-data-types.md
index fb3efd318..7d6ffbc78 100644
--- a/docs/en/docs/tutorial/extra-data-types.md
+++ b/docs/en/docs/tutorial/extra-data-types.md
@@ -55,28 +55,76 @@ Here are some of the additional data types you can use:
Here's an example *path operation* with parameters using some of the above types.
-=== "Python 3.6 and above"
+=== "Python 3.10+"
```Python hl_lines="1 3 12-16"
- {!> ../../../docs_src/extra_data_types/tutorial001.py!}
+ {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="1 3 12-16"
+ {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="1 3 13-17"
+ {!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="1 2 11-15"
{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="1 2 12-16"
+ {!> ../../../docs_src/extra_data_types/tutorial001.py!}
+ ```
+
Note that the parameters inside the function have their natural data type, and you can, for example, perform normal date manipulations, like:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
```Python hl_lines="18-19"
- {!> ../../../docs_src/extra_data_types/tutorial001.py!}
+ {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.9+"
+
+ ```Python hl_lines="18-19"
+ {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="19-20"
+ {!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
+ ```
+
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="17-18"
{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
```
+
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="18-19"
+ {!> ../../../docs_src/extra_data_types/tutorial001.py!}
+ ```
diff --git a/docs/en/docs/tutorial/extra-models.md b/docs/en/docs/tutorial/extra-models.md
index 72fc74894..e91e879e4 100644
--- a/docs/en/docs/tutorial/extra-models.md
+++ b/docs/en/docs/tutorial/extra-models.md
@@ -17,16 +17,16 @@ This is especially the case for user models, because:
Here's a general idea of how the models could look like with their password fields and the places where they are used:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41"
- {!> ../../../docs_src/extra_models/tutorial001.py!}
+ ```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39"
+ {!> ../../../docs_src/extra_models/tutorial001_py310.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39"
- {!> ../../../docs_src/extra_models/tutorial001_py310.py!}
+ ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41"
+ {!> ../../../docs_src/extra_models/tutorial001.py!}
```
### About `**user_in.dict()`
@@ -158,16 +158,16 @@ All the data conversion, validation, documentation, etc. will still work as norm
That way, we can declare just the differences between the models (with plaintext `password`, with `hashed_password` and without password):
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="9 15-16 19-20 23-24"
- {!> ../../../docs_src/extra_models/tutorial002.py!}
+ ```Python hl_lines="7 13-14 17-18 21-22"
+ {!> ../../../docs_src/extra_models/tutorial002_py310.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="7 13-14 17-18 21-22"
- {!> ../../../docs_src/extra_models/tutorial002_py310.py!}
+ ```Python hl_lines="9 15-16 19-20 23-24"
+ {!> ../../../docs_src/extra_models/tutorial002.py!}
```
## `Union` or `anyOf`
@@ -181,16 +181,16 @@ To do that, use the standard Python type hint `Union`, include the most specific type first, followed by the less specific type. In the example below, the more specific `PlaneItem` comes before `CarItem` in `Union[PlaneItem, CarItem]`.
-=== "Python 3.6 and above"
+=== "Python 3.10+"
```Python hl_lines="1 14-15 18-20 33"
- {!> ../../../docs_src/extra_models/tutorial003.py!}
+ {!> ../../../docs_src/extra_models/tutorial003_py310.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
```Python hl_lines="1 14-15 18-20 33"
- {!> ../../../docs_src/extra_models/tutorial003_py310.py!}
+ {!> ../../../docs_src/extra_models/tutorial003.py!}
```
### `Union` in Python 3.10
@@ -213,16 +213,16 @@ The same way, you can declare responses of lists of objects.
For that, use the standard Python `typing.List` (or just `list` in Python 3.9 and above):
-=== "Python 3.6 and above"
+=== "Python 3.9+"
- ```Python hl_lines="1 20"
- {!> ../../../docs_src/extra_models/tutorial004.py!}
+ ```Python hl_lines="18"
+ {!> ../../../docs_src/extra_models/tutorial004_py39.py!}
```
-=== "Python 3.9 and above"
+=== "Python 3.6+"
- ```Python hl_lines="18"
- {!> ../../../docs_src/extra_models/tutorial004_py39.py!}
+ ```Python hl_lines="1 20"
+ {!> ../../../docs_src/extra_models/tutorial004.py!}
```
## Response with arbitrary `dict`
@@ -233,16 +233,16 @@ This is useful if you don't know the valid field/attribute names (that would be
In this case, you can use `typing.Dict` (or just `dict` in Python 3.9 and above):
-=== "Python 3.6 and above"
+=== "Python 3.9+"
- ```Python hl_lines="1 8"
- {!> ../../../docs_src/extra_models/tutorial005.py!}
+ ```Python hl_lines="6"
+ {!> ../../../docs_src/extra_models/tutorial005_py39.py!}
```
-=== "Python 3.9 and above"
+=== "Python 3.6+"
- ```Python hl_lines="6"
- {!> ../../../docs_src/extra_models/tutorial005_py39.py!}
+ ```Python hl_lines="1 8"
+ {!> ../../../docs_src/extra_models/tutorial005.py!}
```
## Recap
diff --git a/docs/en/docs/tutorial/header-params.md b/docs/en/docs/tutorial/header-params.md
index 8e294416c..9e928cdc6 100644
--- a/docs/en/docs/tutorial/header-params.md
+++ b/docs/en/docs/tutorial/header-params.md
@@ -6,36 +6,84 @@ You can define Header parameters the same way you define `Query`, `Path` and `Co
First import `Header`:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
```Python hl_lines="3"
- {!> ../../../docs_src/header_params/tutorial001.py!}
+ {!> ../../../docs_src/header_params/tutorial001_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="3"
+ {!> ../../../docs_src/header_params/tutorial001_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="3"
+ {!> ../../../docs_src/header_params/tutorial001_an.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="1"
{!> ../../../docs_src/header_params/tutorial001_py310.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="3"
+ {!> ../../../docs_src/header_params/tutorial001.py!}
+ ```
+
## Declare `Header` parameters
Then declare the header parameters using the same structure as with `Path`, `Query` and `Cookie`.
The first value is the default value, you can pass all the extra validation or annotation parameters:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial001.py!}
+ {!> ../../../docs_src/header_params/tutorial001_an_py310.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.9+"
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/header_params/tutorial001_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="10"
+ {!> ../../../docs_src/header_params/tutorial001_an.py!}
+ ```
+
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="7"
{!> ../../../docs_src/header_params/tutorial001_py310.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/header_params/tutorial001.py!}
+ ```
+
!!! note "Technical Details"
`Header` is a "sister" class of `Path`, `Query` and `Cookie`. It also inherits from the same common `Param` class.
@@ -60,18 +108,42 @@ So, you can use `user_agent` as you normally would in Python code, instead of ne
If for some reason you need to disable automatic conversion of underscores to hyphens, set the parameter `convert_underscores` of `Header` to `False`:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
```Python hl_lines="10"
- {!> ../../../docs_src/header_params/tutorial002.py!}
+ {!> ../../../docs_src/header_params/tutorial002_an_py310.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.9+"
+
+ ```Python hl_lines="11"
+ {!> ../../../docs_src/header_params/tutorial002_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="12"
+ {!> ../../../docs_src/header_params/tutorial002_an.py!}
+ ```
+
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="8"
{!> ../../../docs_src/header_params/tutorial002_py310.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="10"
+ {!> ../../../docs_src/header_params/tutorial002.py!}
+ ```
+
!!! warning
Before setting `convert_underscores` to `False`, bear in mind that some HTTP proxies and servers disallow the usage of headers with underscores.
@@ -85,24 +157,51 @@ You will receive all the values from the duplicate header as a Python `list`.
For example, to declare a header of `X-Token` that can appear more than once, you can write:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial003.py!}
+ {!> ../../../docs_src/header_params/tutorial003_an_py310.py!}
```
-=== "Python 3.9 and above"
+=== "Python 3.9+"
```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial003_py39.py!}
+ {!> ../../../docs_src/header_params/tutorial003_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="10"
+ {!> ../../../docs_src/header_params/tutorial003_an.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="7"
{!> ../../../docs_src/header_params/tutorial003_py310.py!}
```
+=== "Python 3.9+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/header_params/tutorial003_py39.py!}
+ ```
+
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/header_params/tutorial003.py!}
+ ```
+
If you communicate with that *path operation* sending two HTTP headers like:
```
diff --git a/docs/en/docs/tutorial/metadata.md b/docs/en/docs/tutorial/metadata.md
index 78f17031a..cf13e7470 100644
--- a/docs/en/docs/tutorial/metadata.md
+++ b/docs/en/docs/tutorial/metadata.md
@@ -101,7 +101,7 @@ You can configure the two documentation user interfaces included:
* **Swagger UI**: served at `/docs`.
* You can set its URL with the parameter `docs_url`.
* You can disable it by setting `docs_url=None`.
-* ReDoc: served at `/redoc`.
+* **ReDoc**: served at `/redoc`.
* You can set its URL with the parameter `redoc_url`.
* You can disable it by setting `redoc_url=None`.
diff --git a/docs/en/docs/tutorial/path-operation-configuration.md b/docs/en/docs/tutorial/path-operation-configuration.md
index 884a762e2..7d4d4bcca 100644
--- a/docs/en/docs/tutorial/path-operation-configuration.md
+++ b/docs/en/docs/tutorial/path-operation-configuration.md
@@ -13,22 +13,22 @@ You can pass directly the `int` code, like `404`.
But if you don't remember what each number code is for, you can use the shortcut constants in `status`:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="3 17"
- {!> ../../../docs_src/path_operation_configuration/tutorial001.py!}
+ ```Python hl_lines="1 15"
+ {!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!}
```
-=== "Python 3.9 and above"
+=== "Python 3.9+"
```Python hl_lines="3 17"
{!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="1 15"
- {!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!}
+ ```Python hl_lines="3 17"
+ {!> ../../../docs_src/path_operation_configuration/tutorial001.py!}
```
That status code will be used in the response and will be added to the OpenAPI schema.
@@ -42,22 +42,22 @@ That status code will be used in the response and will be added to the OpenAPI s
You can add tags to your *path operation*, pass the parameter `tags` with a `list` of `str` (commonly just one `str`):
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="17 22 27"
- {!> ../../../docs_src/path_operation_configuration/tutorial002.py!}
+ ```Python hl_lines="15 20 25"
+ {!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!}
```
-=== "Python 3.9 and above"
+=== "Python 3.9+"
```Python hl_lines="17 22 27"
{!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="15 20 25"
- {!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!}
+ ```Python hl_lines="17 22 27"
+ {!> ../../../docs_src/path_operation_configuration/tutorial002.py!}
```
They will be added to the OpenAPI schema and used by the automatic documentation interfaces:
@@ -80,22 +80,22 @@ In these cases, it could make sense to store the tags in an `Enum`.
You can add a `summary` and `description`:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="20-21"
- {!> ../../../docs_src/path_operation_configuration/tutorial003.py!}
+ ```Python hl_lines="18-19"
+ {!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!}
```
-=== "Python 3.9 and above"
+=== "Python 3.9+"
```Python hl_lines="20-21"
{!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!}
+ ```Python hl_lines="20-21"
+ {!> ../../../docs_src/path_operation_configuration/tutorial003.py!}
```
## Description from docstring
@@ -104,22 +104,22 @@ As descriptions tend to be long and cover multiple lines, you can declare the *p
You can write Markdown in the docstring, it will be interpreted and displayed correctly (taking into account docstring indentation).
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="19-27"
- {!> ../../../docs_src/path_operation_configuration/tutorial004.py!}
+ ```Python hl_lines="17-25"
+ {!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!}
```
-=== "Python 3.9 and above"
+=== "Python 3.9+"
```Python hl_lines="19-27"
{!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="17-25"
- {!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!}
+ ```Python hl_lines="19-27"
+ {!> ../../../docs_src/path_operation_configuration/tutorial004.py!}
```
It will be used in the interactive docs:
@@ -130,22 +130,22 @@ It will be used in the interactive docs:
You can specify the response description with the parameter `response_description`:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="21"
- {!> ../../../docs_src/path_operation_configuration/tutorial005.py!}
+ ```Python hl_lines="19"
+ {!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!}
```
-=== "Python 3.9 and above"
+=== "Python 3.9+"
```Python hl_lines="21"
{!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="19"
- {!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!}
+ ```Python hl_lines="21"
+ {!> ../../../docs_src/path_operation_configuration/tutorial005.py!}
```
!!! info
diff --git a/docs/en/docs/tutorial/path-params-numeric-validations.md b/docs/en/docs/tutorial/path-params-numeric-validations.md
index cec54b0fb..9255875d6 100644
--- a/docs/en/docs/tutorial/path-params-numeric-validations.md
+++ b/docs/en/docs/tutorial/path-params-numeric-validations.md
@@ -4,38 +4,93 @@ In the same way that you can declare more validations and metadata for query par
## Import Path
-First, import `Path` from `fastapi`:
+First, import `Path` from `fastapi`, and import `Annotated`:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
+ ```Python hl_lines="1 3"
+ {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="1 3"
+ {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="3-4"
+ {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="1"
{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="3"
+ {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
+ ```
+
+!!! info
+ FastAPI added support for `Annotated` (and started recommending it) in version 0.95.0.
+
+ If you have an older version, you would get errors when trying to use `Annotated`.
+
+ Make sure you [Upgrade the FastAPI version](../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} to at least 0.95.1 before using `Annotated`.
+
## Declare metadata
You can declare all the same parameters as for `Query`.
For example, to declare a `title` metadata value for the path parameter `item_id` you can type:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
+ {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="10"
+ {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
+
+ ```Python hl_lines="11"
+ {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
+ ```
+
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="8"
{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="10"
+ {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
+ ```
+
!!! note
A path parameter is always required as it has to be part of the path.
@@ -45,11 +100,14 @@ For example, to declare a `title` metadata value for the path parameter `item_id
## Order the parameters as you need
+!!! tip
+ This is probably not as important or necessary if you use `Annotated`.
+
Let's say that you want to declare the query parameter `q` as a required `str`.
And you don't need to declare anything else for that parameter, so you don't really need to use `Query`.
-But you still need to use `Path` for the `item_id` path parameter.
+But you still need to use `Path` for the `item_id` path parameter. And you don't want to use `Annotated` for some reason.
Python will complain if you put a value with a "default" before a value that doesn't have a "default".
@@ -59,13 +117,44 @@ It doesn't matter for **FastAPI**. It will detect the parameters by their names,
So, you can declare your function as:
-```Python hl_lines="7"
-{!../../../docs_src/path_params_numeric_validations/tutorial002.py!}
-```
+=== "Python 3.6 non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="7"
+ {!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!}
+ ```
+
+But have in mind that if you use `Annotated`, you won't have this problem, it won't matter as you're not using the function parameter default values for `Query()` or `Path()`.
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="10"
+ {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!}
+ ```
## Order the parameters as you need, tricks
-If you want to declare the `q` query parameter without a `Query` nor any default value, and the path parameter `item_id` using `Path`, and have them in a different order, Python has a little special syntax for that.
+!!! tip
+ This is probably not as important or necessary if you use `Annotated`.
+
+Here's a **small trick** that can be handy, but you won't need it often.
+
+If you want to:
+
+* declare the `q` query parameter without a `Query` nor any default value
+* declare the path parameter `item_id` using `Path`
+* have them in a different order
+* not use `Annotated`
+
+...Python has a little special syntax for that.
Pass `*`, as the first parameter of the function.
@@ -75,15 +164,48 @@ Python won't do anything with that `*`, but it will know that all the following
{!../../../docs_src/path_params_numeric_validations/tutorial003.py!}
```
+### Better with `Annotated`
+
+Have in mind that if you use `Annotated`, as you are not using function parameter default values, you won't have this problem, and you probably won't need to use `*`.
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="10"
+ {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!}
+ ```
+
## Number validations: greater than or equal
With `Query` and `Path` (and others you'll see later) you can declare number constraints.
Here, with `ge=1`, `item_id` will need to be an integer number "`g`reater than or `e`qual" to `1`.
-```Python hl_lines="8"
-{!../../../docs_src/path_params_numeric_validations/tutorial004.py!}
-```
+=== "Python 3.9+"
+
+ ```Python hl_lines="10"
+ {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!}
+ ```
+
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="8"
+ {!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!}
+ ```
## Number validations: greater than and less than or equal
@@ -92,9 +214,26 @@ The same applies for:
* `gt`: `g`reater `t`han
* `le`: `l`ess than or `e`qual
-```Python hl_lines="9"
-{!../../../docs_src/path_params_numeric_validations/tutorial005.py!}
-```
+=== "Python 3.9+"
+
+ ```Python hl_lines="10"
+ {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!}
+ ```
+
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!}
+ ```
## Number validations: floats, greater than and less than
@@ -106,9 +245,26 @@ So, `0.5` would be a valid value. But `0.0` or `0` would not.
And the same for lt.
-```Python hl_lines="11"
-{!../../../docs_src/path_params_numeric_validations/tutorial006.py!}
-```
+=== "Python 3.9+"
+
+ ```Python hl_lines="13"
+ {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="12"
+ {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!}
+ ```
+
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="11"
+ {!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!}
+ ```
## Recap
diff --git a/docs/en/docs/tutorial/query-params-str-validations.md b/docs/en/docs/tutorial/query-params-str-validations.md
index 060e1d58a..c4b221cb1 100644
--- a/docs/en/docs/tutorial/query-params-str-validations.md
+++ b/docs/en/docs/tutorial/query-params-str-validations.md
@@ -4,16 +4,16 @@
Let's take this application as example:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial001.py!}
+ ```Python hl_lines="7"
+ {!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!}
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/query_params_str_validations/tutorial001.py!}
```
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.
@@ -27,39 +27,124 @@ The query parameter `q` is of type `Union[str, None]` (or `str | None` in Python
We are going to enforce that even though `q` is optional, whenever it is provided, **its length doesn't exceed 50 characters**.
-### Import `Query`
+### Import `Query` and `Annotated`
-To achieve that, first import `Query` from `fastapi`:
+To achieve that, first import:
-=== "Python 3.6 and above"
+* `Query` from `fastapi`
+* `Annotated` from `typing` (or from `typing_extensions` in Python below 3.9)
- ```Python hl_lines="3"
- {!> ../../../docs_src/query_params_str_validations/tutorial002.py!}
+=== "Python 3.10+"
+
+ In Python 3.9 or above, `Annotated` is part of the standard library, so you can import it from `typing`.
+
+ ```Python hl_lines="1 3"
+ {!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="1"
- {!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!}
+ In versions of Python below Python 3.9 you import `Annotation` from `typing_extensions`.
+
+ It will already be installed with FastAPI.
+
+ ```Python hl_lines="3-4"
+ {!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!}
+ ```
+
+!!! info
+ FastAPI added support for `Annotated` (and started recommending it) in version 0.95.0.
+
+ If you have an older version, you would get errors when trying to use `Annotated`.
+
+ Make sure you [Upgrade the FastAPI version](../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} to at least 0.95.1 before using `Annotated`.
+
+## Use `Annotated` in the type for the `q` parameter
+
+Remember I told you before that `Annotated` can be used to add metadata to your parameters in the [Python Types Intro](../python-types.md#type-hints-with-metadata-annotations){.internal-link target=_blank}?
+
+Now it's the time to use it with FastAPI. 🚀
+
+We had this type annotation:
+
+=== "Python 3.10+"
+
+ ```Python
+ q: str | None = None
+ ```
+
+=== "Python 3.6+"
+
+ ```Python
+ q: Union[str, None] = None
+ ```
+
+What we will do is wrap that with `Annotated`, so it becomes:
+
+=== "Python 3.10+"
+
+ ```Python
+ q: Annotated[str | None] = None
+ ```
+
+=== "Python 3.6+"
+
+ ```Python
+ q: Annotated[Union[str, None]] = None
```
-## Use `Query` as the default value
+Both of those versions mean the same thing, `q` is a parameter that can be a `str` or `None`, and by default, it is `None`.
-And now use it as the default value of your parameter, setting the parameter `max_length` to 50:
+Now let's jump to the fun stuff. 🎉
-=== "Python 3.6 and above"
+## Add `Query` to `Annotated` in the `q` parameter
+
+Now that we have this `Annotated` where we can put more metadata, add `Query` to it, and set the parameter `max_length` to 50:
+
+=== "Python 3.10+"
```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial002.py!}
+ {!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="10"
+ {!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!}
```
-=== "Python 3.10 and above"
+Notice that the default value is still `None`, so the parameter is still optional.
+
+But now, having `Query(max_length=50)` inside of `Annotated`, we are telling FastAPI that we want it to extract this value from the query parameters (this would have been the default anyway 🤷) and that we want to have **additional validation** for this value (that's why we do this, to get the additional validation). 😎
+
+FastAPI will now:
+
+* **Validate** the data making sure that the max length is 50 characters
+* Show a **clear error** for the client when the data is not valid
+* **Document** the parameter in the OpenAPI schema *path operation* (so it will show up in the **automatic docs UI**)
+
+## Alternative (old) `Query` as the default value
+
+Previous versions of FastAPI (before 0.95.0) required you to use `Query` as the default value of your parameter, instead of putting it in `Annotated`, there's a high chance that you will see code using it around, so I'll explain it to you.
+
+!!! tip
+ For new code and whenever possible, use `Annotated` as explained above. There are multiple advantages (explained below) and no disadvantages. 🍰
+
+This is how you would use `Query()` as the default value of your function parameter, setting the parameter `max_length` to 50:
+
+=== "Python 3.10+"
```Python hl_lines="7"
{!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!}
```
-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.
+=== "Python 3.6+"
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/query_params_str_validations/tutorial002.py!}
+ ```
+
+As in this case (without using `Annotated`) we have to replace the default value `None` in the function with `Query()`, we now need to set the default value with the parameter `Query(default=None)`, it serves the same purpose of defining that default value (at least for FastAPI).
So:
@@ -67,7 +152,7 @@ So:
q: Union[str, None] = Query(default=None)
```
-...makes the parameter optional, the same as:
+...makes the parameter optional, with a default value of `None`, the same as:
```Python
q: Union[str, None] = None
@@ -79,7 +164,7 @@ And in Python 3.10 and above:
q: str | None = Query(default=None)
```
-...makes the parameter optional, the same as:
+...makes the parameter optional, with a default value of `None`, the same as:
```Python
q: str | None = None
@@ -112,38 +197,124 @@ 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*.
+### `Query` as the default value or in `Annotated`
+
+Have in mind that when using `Query` inside of `Annotated` you cannot use the `default` parameter for `Query`.
+
+Instead use the actual default value of the function parameter. Otherwise, it would be inconsistent.
+
+For example, this is not allowed:
+
+```Python
+q: Annotated[str, Query(default="rick")] = "morty"
+```
+
+...because it's not clear if the default value should be `"rick"` or `"morty"`.
+
+So, you would use (preferably):
+
+```Python
+q: Annotated[str, Query()] = "rick"
+```
+
+...or in older code bases you will find:
+
+```Python
+q: str = Query(default="rick")
+```
+
+### Advantages of `Annotated`
+
+**Using `Annotated` is recommended** instead of the default value in function parameters, it is **better** for multiple reasons. 🤓
+
+The **default** value of the **function parameter** is the **actual default** value, that's more intuitive with Python in general. 😌
+
+You could **call** that same function in **other places** without FastAPI, and it would **work as expected**. If there's a **required** parameter (without a default value), your **editor** will let you know with an error, **Python** will also complain if you run it without passing the required parameter.
+
+When you don't use `Annotated` and instead use the **(old) default value style**, if you call that function without FastAPI in **other place**, you have to **remember** to pass the arguments to the function for it to work correctly, otherwise the values will be different from what you expect (e.g. `QueryInfo` or something similar instead of `str`). And your editor won't complain, and Python won't complain running that function, only when the operations inside error out.
+
+Because `Annotated` can have more than one metadata annotation, you could now even use the same function with other tools, like Typer. 🚀
+
## Add more validations
You can also add a parameter `min_length`:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial003.py!}
+ {!> ../../../docs_src/query_params_str_validations/tutorial003_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="10"
+ {!> ../../../docs_src/query_params_str_validations/tutorial003_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="11"
+ {!> ../../../docs_src/query_params_str_validations/tutorial003_an.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="7"
{!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="10"
+ {!> ../../../docs_src/query_params_str_validations/tutorial003.py!}
+ ```
+
## Add regular expressions
You can define a regular expression that the parameter should match:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial004.py!}
+ {!> ../../../docs_src/query_params_str_validations/tutorial004_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="11"
+ {!> ../../../docs_src/query_params_str_validations/tutorial004_an_py39.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
+
+ ```Python hl_lines="12"
+ {!> ../../../docs_src/query_params_str_validations/tutorial004_an.py!}
+ ```
+
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="9"
{!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="11"
+ {!> ../../../docs_src/query_params_str_validations/tutorial004.py!}
+ ```
+
This specific regular expression checks that the received parameter value:
* `^`: starts with the following characters, doesn't have characters before.
@@ -156,16 +327,33 @@ 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 value for the `default` parameter, you can pass other values.
+You can, of course, use default values other than `None`.
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"`:
-```Python hl_lines="7"
-{!../../../docs_src/query_params_str_validations/tutorial005.py!}
-```
+=== "Python 3.9+"
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/query_params_str_validations/tutorial005_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="8"
+ {!> ../../../docs_src/query_params_str_validations/tutorial005_an.py!}
+ ```
+
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="7"
+ {!> ../../../docs_src/query_params_str_validations/tutorial005.py!}
+ ```
!!! note
- Having a default value also makes the parameter optional.
+ Having a default value of any type, including `None`, makes the parameter optional (not required).
## Make it required
@@ -183,23 +371,70 @@ q: Union[str, None] = None
But we are now declaring it with `Query`, for example like:
-```Python
-q: Union[str, None] = Query(default=None, min_length=3)
-```
+=== "Annotated"
+
+ ```Python
+ q: Annotated[Union[str, None], Query(min_length=3)] = None
+ ```
+
+=== "non-Annotated"
+
+ ```Python
+ 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 simply not declare a default value:
-```Python hl_lines="7"
-{!../../../docs_src/query_params_str_validations/tutorial006.py!}
-```
+=== "Python 3.9+"
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/query_params_str_validations/tutorial006_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="8"
+ {!> ../../../docs_src/query_params_str_validations/tutorial006_an.py!}
+ ```
+
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="7"
+ {!> ../../../docs_src/query_params_str_validations/tutorial006.py!}
+ ```
+
+ !!! tip
+ Notice that, even though in this case the `Query()` is used as the function parameter default value, we don't pass the `default=None` to `Query()`.
+
+ Still, probably better to use the `Annotated` version. 😉
### 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 `...`:
+There's an alternative way to explicitly declare that a value is required. You can set the default to the literal value `...`:
-```Python hl_lines="7"
-{!../../../docs_src/query_params_str_validations/tutorial006b.py!}
-```
+=== "Python 3.9+"
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="8"
+ {!> ../../../docs_src/query_params_str_validations/tutorial006b_an.py!}
+ ```
+
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```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".
@@ -212,20 +447,44 @@ This will let **FastAPI** know that this parameter is required.
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=...`:
+To do that, you can declare that `None` is a valid type but still use `...` as the default:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial006c.py!}
+ {!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="10"
+ {!> ../../../docs_src/query_params_str_validations/tutorial006c_an.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="7"
{!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/query_params_str_validations/tutorial006c.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.
@@ -233,12 +492,29 @@ To do that, you can declare that `None` is a valid type but still use `default=.
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!}
-```
+=== "Python 3.9+"
+
+ ```Python hl_lines="4 10"
+ {!> ../../../docs_src/query_params_str_validations/tutorial006d_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="2 9"
+ {!> ../../../docs_src/query_params_str_validations/tutorial006d_an.py!}
+ ```
+
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```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`.
+ Remember that in most of the cases, when something is required, you can simply omit the default, so you normally don't have to use `...` nor `Required`.
## Query parameter list / multiple values
@@ -246,24 +522,51 @@ When you define a query parameter explicitly with `Query` you can also declare i
For example, to declare a query parameter `q` that can appear multiple times in the URL, you can write:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial011.py!}
+ {!> ../../../docs_src/query_params_str_validations/tutorial011_an_py310.py!}
```
-=== "Python 3.9 and above"
+=== "Python 3.9+"
```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!}
+ {!> ../../../docs_src/query_params_str_validations/tutorial011_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="10"
+ {!> ../../../docs_src/query_params_str_validations/tutorial011_an.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="7"
{!> ../../../docs_src/query_params_str_validations/tutorial011_py310.py!}
```
+=== "Python 3.9+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!}
+ ```
+
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/query_params_str_validations/tutorial011.py!}
+ ```
+
Then, with a URL like:
```
@@ -294,18 +597,36 @@ The interactive API docs will update accordingly, to allow multiple values:
And you can also define a default `list` of values if none are provided:
-=== "Python 3.6 and above"
+=== "Python 3.9+"
```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial012.py!}
+ {!> ../../../docs_src/query_params_str_validations/tutorial012_an_py39.py!}
```
-=== "Python 3.9 and above"
+=== "Python 3.6+"
+
+ ```Python hl_lines="10"
+ {!> ../../../docs_src/query_params_str_validations/tutorial012_an.py!}
+ ```
+
+=== "Python 3.9+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="7"
{!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/query_params_str_validations/tutorial012.py!}
+ ```
+
If you go to:
```
@@ -327,9 +648,26 @@ the default of `q` will be: `["foo", "bar"]` and your response will be:
You can also use `list` directly instead of `List[str]` (or `list[str]` in Python 3.9+):
-```Python hl_lines="7"
-{!../../../docs_src/query_params_str_validations/tutorial013.py!}
-```
+=== "Python 3.9+"
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/query_params_str_validations/tutorial013_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="8"
+ {!> ../../../docs_src/query_params_str_validations/tutorial013_an.py!}
+ ```
+
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="7"
+ {!> ../../../docs_src/query_params_str_validations/tutorial013.py!}
+ ```
!!! note
Have in mind that in this case, FastAPI won't check the contents of the list.
@@ -349,32 +687,80 @@ That information will be included in the generated OpenAPI and used by the docum
You can add a `title`:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial007.py!}
+ {!> ../../../docs_src/query_params_str_validations/tutorial007_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="10"
+ {!> ../../../docs_src/query_params_str_validations/tutorial007_an_py39.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
+
+ ```Python hl_lines="11"
+ {!> ../../../docs_src/query_params_str_validations/tutorial007_an.py!}
+ ```
+
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="8"
{!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="10"
+ {!> ../../../docs_src/query_params_str_validations/tutorial007.py!}
+ ```
+
And a `description`:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="13"
- {!> ../../../docs_src/query_params_str_validations/tutorial008.py!}
+ ```Python hl_lines="14"
+ {!> ../../../docs_src/query_params_str_validations/tutorial008_an_py310.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.9+"
+
+ ```Python hl_lines="14"
+ {!> ../../../docs_src/query_params_str_validations/tutorial008_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="15"
+ {!> ../../../docs_src/query_params_str_validations/tutorial008_an.py!}
+ ```
+
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="12"
{!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="13"
+ {!> ../../../docs_src/query_params_str_validations/tutorial008.py!}
+ ```
+
## Alias parameters
Imagine that you want the parameter to be `item-query`.
@@ -393,18 +779,42 @@ But you still need it to be exactly `item-query`...
Then you can declare an `alias`, and that alias is what will be used to find the parameter value:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial009.py!}
+ {!> ../../../docs_src/query_params_str_validations/tutorial009_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/query_params_str_validations/tutorial009_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="10"
+ {!> ../../../docs_src/query_params_str_validations/tutorial009_an.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="7"
{!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/query_params_str_validations/tutorial009.py!}
+ ```
+
## Deprecating parameters
Now let's say you don't like this parameter anymore.
@@ -413,18 +823,42 @@ You have to leave it there a while because there are clients using it, but you w
Then pass the parameter `deprecated=True` to `Query`:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="18"
- {!> ../../../docs_src/query_params_str_validations/tutorial010.py!}
+ ```Python hl_lines="19"
+ {!> ../../../docs_src/query_params_str_validations/tutorial010_an_py310.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.9+"
+
+ ```Python hl_lines="19"
+ {!> ../../../docs_src/query_params_str_validations/tutorial010_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="20"
+ {!> ../../../docs_src/query_params_str_validations/tutorial010_an.py!}
+ ```
+
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="17"
{!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="18"
+ {!> ../../../docs_src/query_params_str_validations/tutorial010.py!}
+ ```
+
The docs will show it like this:
@@ -433,18 +867,42 @@ The docs will show it like this:
To exclude a query parameter from the generated OpenAPI schema (and thus, from the automatic documentation systems), set the parameter `include_in_schema` of `Query` to `False`:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial014.py!}
+ {!> ../../../docs_src/query_params_str_validations/tutorial014_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="10"
+ {!> ../../../docs_src/query_params_str_validations/tutorial014_an_py39.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
+
+ ```Python hl_lines="11"
+ {!> ../../../docs_src/query_params_str_validations/tutorial014_an.py!}
+ ```
+
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="8"
{!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="10"
+ {!> ../../../docs_src/query_params_str_validations/tutorial014.py!}
+ ```
+
## Recap
You can declare additional validations and metadata for your parameters.
diff --git a/docs/en/docs/tutorial/query-params.md b/docs/en/docs/tutorial/query-params.md
index eec55502a..0b74b10f8 100644
--- a/docs/en/docs/tutorial/query-params.md
+++ b/docs/en/docs/tutorial/query-params.md
@@ -63,16 +63,16 @@ The parameter values in your function will be:
The same way, you can declare optional query parameters, by setting their default to `None`:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params/tutorial002.py!}
+ ```Python hl_lines="7"
+ {!> ../../../docs_src/query_params/tutorial002_py310.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params/tutorial002_py310.py!}
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/query_params/tutorial002.py!}
```
In this case, the function parameter `q` will be optional, and will be `None` by default.
@@ -84,16 +84,16 @@ In this case, the function parameter `q` will be optional, and will be `None` by
You can also declare `bool` types, and they will be converted:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params/tutorial003.py!}
+ ```Python hl_lines="7"
+ {!> ../../../docs_src/query_params/tutorial003_py310.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params/tutorial003_py310.py!}
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/query_params/tutorial003.py!}
```
In this case, if you go to:
@@ -137,16 +137,16 @@ And you don't have to declare them in any specific order.
They will be detected by name:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="8 10"
- {!> ../../../docs_src/query_params/tutorial004.py!}
+ ```Python hl_lines="6 8"
+ {!> ../../../docs_src/query_params/tutorial004_py310.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="6 8"
- {!> ../../../docs_src/query_params/tutorial004_py310.py!}
+ ```Python hl_lines="8 10"
+ {!> ../../../docs_src/query_params/tutorial004.py!}
```
## Required query parameters
@@ -203,16 +203,16 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
And of course, you can define some parameters as required, some as having a default value, and some entirely optional:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params/tutorial006.py!}
+ ```Python hl_lines="8"
+ {!> ../../../docs_src/query_params/tutorial006_py310.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params/tutorial006_py310.py!}
+ ```Python hl_lines="10"
+ {!> ../../../docs_src/query_params/tutorial006.py!}
```
In this case, there are 3 query parameters:
diff --git a/docs/en/docs/tutorial/request-files.md b/docs/en/docs/tutorial/request-files.md
index 783783c58..1fe1e7a33 100644
--- a/docs/en/docs/tutorial/request-files.md
+++ b/docs/en/docs/tutorial/request-files.md
@@ -13,17 +13,51 @@ You can define files to be uploaded by the client using `File`.
Import `File` and `UploadFile` from `fastapi`:
-```Python hl_lines="1"
-{!../../../docs_src/request_files/tutorial001.py!}
-```
+=== "Python 3.9+"
+
+ ```Python hl_lines="3"
+ {!> ../../../docs_src/request_files/tutorial001_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="1"
+ {!> ../../../docs_src/request_files/tutorial001_an.py!}
+ ```
+
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="1"
+ {!> ../../../docs_src/request_files/tutorial001.py!}
+ ```
## Define `File` Parameters
Create file parameters the same way you would for `Body` or `Form`:
-```Python hl_lines="7"
-{!../../../docs_src/request_files/tutorial001.py!}
-```
+=== "Python 3.9+"
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/request_files/tutorial001_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="8"
+ {!> ../../../docs_src/request_files/tutorial001_an.py!}
+ ```
+
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="7"
+ {!> ../../../docs_src/request_files/tutorial001.py!}
+ ```
!!! info
`File` is a class that inherits directly from `Form`.
@@ -45,9 +79,26 @@ But there are several cases in which you might benefit from using `UploadFile`.
Define a file parameter with a type of `UploadFile`:
-```Python hl_lines="12"
-{!../../../docs_src/request_files/tutorial001.py!}
-```
+=== "Python 3.9+"
+
+ ```Python hl_lines="14"
+ {!> ../../../docs_src/request_files/tutorial001_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="13"
+ {!> ../../../docs_src/request_files/tutorial001_an.py!}
+ ```
+
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="12"
+ {!> ../../../docs_src/request_files/tutorial001.py!}
+ ```
Using `UploadFile` has several advantages over `bytes`:
@@ -118,25 +169,66 @@ The way HTML forms (``) sends the data to the server normally uses
You can make a file optional by using standard type annotations and setting a default value of `None`:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
```Python hl_lines="9 17"
- {!> ../../../docs_src/request_files/tutorial001_02.py!}
+ {!> ../../../docs_src/request_files/tutorial001_02_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="9 17"
+ {!> ../../../docs_src/request_files/tutorial001_02_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="10 18"
+ {!> ../../../docs_src/request_files/tutorial001_02_an.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.10+ non-Annotated"
- ```Python hl_lines="7 14"
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="7 15"
{!> ../../../docs_src/request_files/tutorial001_02_py310.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="9 17"
+ {!> ../../../docs_src/request_files/tutorial001_02.py!}
+ ```
+
## `UploadFile` with Additional Metadata
You can also use `File()` with `UploadFile`, for example, to set additional metadata:
-```Python hl_lines="13"
-{!../../../docs_src/request_files/tutorial001_03.py!}
-```
+=== "Python 3.9+"
+
+ ```Python hl_lines="9 15"
+ {!> ../../../docs_src/request_files/tutorial001_03_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="8 14"
+ {!> ../../../docs_src/request_files/tutorial001_03_an.py!}
+ ```
+
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="7 13"
+ {!> ../../../docs_src/request_files/tutorial001_03.py!}
+ ```
## Multiple File Uploads
@@ -146,18 +238,36 @@ They would be associated to the same "form field" sent using "form data".
To use that, declare a list of `bytes` or `UploadFile`:
-=== "Python 3.6 and above"
+=== "Python 3.9+"
```Python hl_lines="10 15"
- {!> ../../../docs_src/request_files/tutorial002.py!}
+ {!> ../../../docs_src/request_files/tutorial002_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="11 16"
+ {!> ../../../docs_src/request_files/tutorial002_an.py!}
```
-=== "Python 3.9 and above"
+=== "Python 3.9+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="8 13"
{!> ../../../docs_src/request_files/tutorial002_py39.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="10 15"
+ {!> ../../../docs_src/request_files/tutorial002.py!}
+ ```
+
You will receive, as declared, a `list` of `bytes` or `UploadFile`s.
!!! note "Technical Details"
@@ -169,18 +279,36 @@ You will receive, as declared, a `list` of `bytes` or `UploadFile`s.
And the same way as before, you can use `File()` to set additional parameters, even for `UploadFile`:
-=== "Python 3.6 and above"
+=== "Python 3.9+"
- ```Python hl_lines="18"
- {!> ../../../docs_src/request_files/tutorial003.py!}
+ ```Python hl_lines="11 18-20"
+ {!> ../../../docs_src/request_files/tutorial003_an_py39.py!}
```
-=== "Python 3.9 and above"
+=== "Python 3.6+"
- ```Python hl_lines="16"
+ ```Python hl_lines="12 19-21"
+ {!> ../../../docs_src/request_files/tutorial003_an.py!}
+ ```
+
+=== "Python 3.9+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="9 16"
{!> ../../../docs_src/request_files/tutorial003_py39.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="11 18"
+ {!> ../../../docs_src/request_files/tutorial003.py!}
+ ```
+
## Recap
Use `File`, `bytes`, and `UploadFile` to declare files to be uploaded in the request, sent as form data.
diff --git a/docs/en/docs/tutorial/request-forms-and-files.md b/docs/en/docs/tutorial/request-forms-and-files.md
index 6844f8c65..1818946c4 100644
--- a/docs/en/docs/tutorial/request-forms-and-files.md
+++ b/docs/en/docs/tutorial/request-forms-and-files.md
@@ -9,17 +9,51 @@ You can define files and form fields at the same time using `File` and `Form`.
## Import `File` and `Form`
-```Python hl_lines="1"
-{!../../../docs_src/request_forms_and_files/tutorial001.py!}
-```
+=== "Python 3.9+"
+
+ ```Python hl_lines="3"
+ {!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="1"
+ {!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!}
+ ```
+
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="1"
+ {!> ../../../docs_src/request_forms_and_files/tutorial001.py!}
+ ```
## Define `File` and `Form` parameters
Create file and form parameters the same way you would for `Body` or `Query`:
-```Python hl_lines="8"
-{!../../../docs_src/request_forms_and_files/tutorial001.py!}
-```
+=== "Python 3.9+"
+
+ ```Python hl_lines="10-12"
+ {!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="9-11"
+ {!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!}
+ ```
+
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="8"
+ {!> ../../../docs_src/request_forms_and_files/tutorial001.py!}
+ ```
The files and form fields will be uploaded as form data and you will receive the files and form fields.
diff --git a/docs/en/docs/tutorial/request-forms.md b/docs/en/docs/tutorial/request-forms.md
index 26922685a..5d441a614 100644
--- a/docs/en/docs/tutorial/request-forms.md
+++ b/docs/en/docs/tutorial/request-forms.md
@@ -11,17 +11,51 @@ When you need to receive form fields instead of JSON, you can use `Form`.
Import `Form` from `fastapi`:
-```Python hl_lines="1"
-{!../../../docs_src/request_forms/tutorial001.py!}
-```
+=== "Python 3.9+"
+
+ ```Python hl_lines="3"
+ {!> ../../../docs_src/request_forms/tutorial001_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="1"
+ {!> ../../../docs_src/request_forms/tutorial001_an.py!}
+ ```
+
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="1"
+ {!> ../../../docs_src/request_forms/tutorial001.py!}
+ ```
## Define `Form` parameters
Create form parameters the same way you would for `Body` or `Query`:
-```Python hl_lines="7"
-{!../../../docs_src/request_forms/tutorial001.py!}
-```
+=== "Python 3.9+"
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/request_forms/tutorial001_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="8"
+ {!> ../../../docs_src/request_forms/tutorial001_an.py!}
+ ```
+
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="7"
+ {!> ../../../docs_src/request_forms/tutorial001.py!}
+ ```
For example, in one of the ways the OAuth2 specification can be used (called "password flow") it is required to send a `username` and `password` as form fields.
diff --git a/docs/en/docs/tutorial/response-model.md b/docs/en/docs/tutorial/response-model.md
index ab68314e8..2181cfb5a 100644
--- a/docs/en/docs/tutorial/response-model.md
+++ b/docs/en/docs/tutorial/response-model.md
@@ -1,6 +1,51 @@
-# Response Model
+# Response Model - Return Type
-You can declare the model used for the response with the parameter `response_model` in any of the *path operations*:
+You can declare the type used for the response by annotating the *path operation function* **return type**.
+
+You can use **type annotations** the same way you would for input data in function **parameters**, you can use Pydantic models, lists, dictionaries, scalar values like integers, booleans, etc.
+
+=== "Python 3.10+"
+
+ ```Python hl_lines="16 21"
+ {!> ../../../docs_src/response_model/tutorial001_01_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="18 23"
+ {!> ../../../docs_src/response_model/tutorial001_01_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="18 23"
+ {!> ../../../docs_src/response_model/tutorial001_01.py!}
+ ```
+
+FastAPI will use this return type to:
+
+* **Validate** the returned data.
+ * If the data is invalid (e.g. you are missing a field), it means that *your* app code is broken, not returning what it should, and it will return a server error instead of returning incorrect data. This way you and your clients can be certain that they will receive the data and the data shape expected.
+* Add a **JSON Schema** for the response, in the OpenAPI *path operation*.
+ * This will be used by the **automatic docs**.
+ * It will also be used by automatic client code generation tools.
+
+But most importantly:
+
+* It will **limit and filter** the output data to what is defined in the return type.
+ * This is particularly important for **security**, we'll see more of that below.
+
+## `response_model` Parameter
+
+There are some cases where you need or want to return some data that is not exactly what the type declares.
+
+For example, you could want to **return a dictionary** or a database object, but **declare it as a Pydantic model**. This way the Pydantic model would do all the data documentation, validation, etc. for the object that you returned (e.g. a dictionary or database object).
+
+If you added the return type annotation, tools and editors would complain with a (correct) error telling you that your function is returning a type (e.g. a dict) that is different from what you declared (e.g. a Pydantic model).
+
+In those cases, you can use the *path operation decorator* parameter `response_model` instead of the return type.
+
+You can use the `response_model` parameter in any of the *path operations*:
* `@app.get()`
* `@app.post()`
@@ -8,57 +53,58 @@ You can declare the model used for the response with the parameter `response_mod
* `@app.delete()`
* etc.
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="17"
- {!> ../../../docs_src/response_model/tutorial001.py!}
+ ```Python hl_lines="17 22 24-27"
+ {!> ../../../docs_src/response_model/tutorial001_py310.py!}
```
-=== "Python 3.9 and above"
+=== "Python 3.9+"
- ```Python hl_lines="17"
+ ```Python hl_lines="17 22 24-27"
{!> ../../../docs_src/response_model/tutorial001_py39.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="15"
- {!> ../../../docs_src/response_model/tutorial001_py310.py!}
+ ```Python hl_lines="17 22 24-27"
+ {!> ../../../docs_src/response_model/tutorial001.py!}
```
!!! note
Notice that `response_model` is a parameter of the "decorator" method (`get`, `post`, etc). Not of your *path operation function*, like all the parameters and body.
-It receives the same type you would declare for a Pydantic model attribute, so, it can be a Pydantic model, but it can also be, e.g. a `list` of Pydantic models, like `List[Item]`.
+`response_model` receives the same type you would declare for a Pydantic model field, so, it can be a Pydantic model, but it can also be, e.g. a `list` of Pydantic models, like `List[Item]`.
+
+FastAPI will use this `response_model` to do all the data documentation, validation, etc. and also to **convert and filter the output data** to its type declaration.
-FastAPI will use this `response_model` to:
+!!! tip
+ If you have strict type checks in your editor, mypy, etc, you can declare the function return type as `Any`.
-* Convert the output data to its type declaration.
-* Validate the data.
-* Add a JSON Schema for the response, in the OpenAPI *path operation*.
-* Will be used by the automatic documentation systems.
+ That way you tell the editor that you are intentionally returning anything. But FastAPI will still do the data documentation, validation, filtering, etc. with the `response_model`.
-But most importantly:
+### `response_model` Priority
-* Will limit the output data to that of the model. We'll see how that's important below.
+If you declare both a return type and a `response_model`, the `response_model` will take priority and be used by FastAPI.
-!!! note "Technical Details"
- The response model is declared in this parameter instead of as a function return type annotation, because the path function may not actually return that response model but rather return a `dict`, database object or some other model, and then use the `response_model` to perform the field limiting and serialization.
+This way you can add correct type annotations to your functions even when you are returning a type different than the response model, to be used by the editor and tools like mypy. And still you can have FastAPI do the data validation, documentation, etc. using the `response_model`.
+
+You can also use `response_model=None` to disable creating a response model for that *path operation*, you might need to do it if you are adding type annotations for things that are not valid Pydantic fields, you will see an example of that in one of the sections below.
## Return the same input data
Here we are declaring a `UserIn` model, it will contain a plaintext password:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="9 11"
- {!> ../../../docs_src/response_model/tutorial002.py!}
+ ```Python hl_lines="7 9"
+ {!> ../../../docs_src/response_model/tutorial002_py310.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="7 9"
- {!> ../../../docs_src/response_model/tutorial002_py310.py!}
+ ```Python hl_lines="9 11"
+ {!> ../../../docs_src/response_model/tutorial002.py!}
```
!!! info
@@ -69,72 +115,126 @@ Here we are declaring a `UserIn` model, it will contain a plaintext password:
And we are using this model to declare our input and the same model to declare our output:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="17-18"
- {!> ../../../docs_src/response_model/tutorial002.py!}
+ ```Python hl_lines="16"
+ {!> ../../../docs_src/response_model/tutorial002_py310.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="15-16"
- {!> ../../../docs_src/response_model/tutorial002_py310.py!}
+ ```Python hl_lines="18"
+ {!> ../../../docs_src/response_model/tutorial002.py!}
```
Now, whenever a browser is creating a user with a password, the API will return the same password in the response.
-In this case, it might not be a problem, because the user themself is sending the password.
+In this case, it might not be a problem, because it's the same user sending the password.
But if we use the same model for another *path operation*, we could be sending our user's passwords to every client.
!!! danger
- Never store the plain password of a user or send it in a response.
+ Never store the plain password of a user or send it in a response like this, unless you know all the caveats and you know what you are doing.
## Add an output model
We can instead create an input model with the plaintext password and an output model without it:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
```Python hl_lines="9 11 16"
- {!> ../../../docs_src/response_model/tutorial003.py!}
+ {!> ../../../docs_src/response_model/tutorial003_py310.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="7 9 14"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
+ ```Python hl_lines="9 11 16"
+ {!> ../../../docs_src/response_model/tutorial003.py!}
```
Here, even though our *path operation function* is returning the same input user that contains the password:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
+
+ ```Python hl_lines="24"
+ {!> ../../../docs_src/response_model/tutorial003_py310.py!}
+ ```
+
+=== "Python 3.6+"
```Python hl_lines="24"
{!> ../../../docs_src/response_model/tutorial003.py!}
```
-=== "Python 3.10 and above"
+...we declared the `response_model` to be our model `UserOut`, that doesn't include the password:
+
+=== "Python 3.10+"
```Python hl_lines="22"
{!> ../../../docs_src/response_model/tutorial003_py310.py!}
```
-...we declared the `response_model` to be our model `UserOut`, that doesn't include the password:
-
-=== "Python 3.6 and above"
+=== "Python 3.6+"
```Python hl_lines="22"
{!> ../../../docs_src/response_model/tutorial003.py!}
```
-=== "Python 3.10 and above"
+So, **FastAPI** will take care of filtering out all the data that is not declared in the output model (using Pydantic).
- ```Python hl_lines="20"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
+### `response_model` or Return Type
+
+In this case, because the two models are different, if we annotated the function return type as `UserOut`, the editor and tools would complain that we are returning an invalid type, as those are different classes.
+
+That's why in this example we have to declare it in the `response_model` parameter.
+
+...but continue reading below to see how to overcome that.
+
+## Return Type and Data Filtering
+
+Let's continue from the previous example. We wanted to **annotate the function with one type** but return something that includes **more data**.
+
+We want FastAPI to keep **filtering** the data using the response model.
+
+In the previous example, because the classes were different, we had to use the `response_model` parameter. But that also means that we don't get the support from the editor and tools checking the function return type.
+
+But in most of the cases where we need to do something like this, we want the model just to **filter/remove** some of the data as in this example.
+
+And in those cases, we can use classes and inheritance to take advantage of function **type annotations** to get better support in the editor and tools, and still get the FastAPI **data filtering**.
+
+=== "Python 3.10+"
+
+ ```Python hl_lines="7-10 13-14 18"
+ {!> ../../../docs_src/response_model/tutorial003_01_py310.py!}
```
-So, **FastAPI** will take care of filtering out all the data that is not declared in the output model (using Pydantic).
+=== "Python 3.6+"
+
+ ```Python hl_lines="9-13 15-16 20"
+ {!> ../../../docs_src/response_model/tutorial003_01.py!}
+ ```
+
+With this, we get tooling support, from editors and mypy as this code is correct in terms of types, but we also get the data filtering from FastAPI.
+
+How does this work? Let's check that out. 🤓
+
+### Type Annotations and Tooling
+
+First let's see how editors, mypy and other tools would see this.
+
+`BaseUser` has the base fields. Then `UserIn` inherits from `BaseUser` and adds the `password` field, so, it will include all the fields from both models.
+
+We annotate the function return type as `BaseUser`, but we are actually returning a `UserIn` instance.
+
+The editor, mypy, and other tools won't complain about this because, in typing terms, `UserIn` is a subclass of `BaseUser`, which means it's a *valid* type when what is expected is anything that is a `BaseUser`.
+
+### FastAPI Data Filtering
+
+Now, for FastAPI, it will see the return type and make sure that what you return includes **only** the fields that are declared in the type.
+
+FastAPI does several things internally with Pydantic to make sure that those same rules of class inheritance are not used for the returned data filtering, otherwise you could end up returning much more data than what you expected.
+
+This way, you can get the best of both worlds: type annotations with **tooling support** and **data filtering**.
## See it in the docs
@@ -146,26 +246,94 @@ And both models will be used for the interactive API documentation:
+## Other Return Type Annotations
+
+There might be cases where you return something that is not a valid Pydantic field and you annotate it in the function, only to get the support provided by tooling (the editor, mypy, etc).
+
+### Return a Response Directly
+
+The most common case would be [returning a Response directly as explained later in the advanced docs](../advanced/response-directly.md){.internal-link target=_blank}.
+
+```Python hl_lines="8 10-11"
+{!> ../../../docs_src/response_model/tutorial003_02.py!}
+```
+
+This simple case is handled automatically by FastAPI because the return type annotation is the class (or a subclass) of `Response`.
+
+And tools will also be happy because both `RedirectResponse` and `JSONResponse` are subclasses of `Response`, so the type annotation is correct.
+
+### Annotate a Response Subclass
+
+You can also use a subclass of `Response` in the type annotation:
+
+```Python hl_lines="8-9"
+{!> ../../../docs_src/response_model/tutorial003_03.py!}
+```
+
+This will also work because `RedirectResponse` is a subclass of `Response`, and FastAPI will automatically handle this simple case.
+
+### Invalid Return Type Annotations
+
+But when you return some other arbitrary object that is not a valid Pydantic type (e.g. a database object) and you annotate it like that in the function, FastAPI will try to create a Pydantic response model from that type annotation, and will fail.
+
+The same would happen if you had something like a union between different types where one or more of them are not valid Pydantic types, for example this would fail 💥:
+
+=== "Python 3.10+"
+
+ ```Python hl_lines="8"
+ {!> ../../../docs_src/response_model/tutorial003_04_py310.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="10"
+ {!> ../../../docs_src/response_model/tutorial003_04.py!}
+ ```
+
+...this fails because the type annotation is not a Pydantic type and is not just a single `Response` class or subclass, it's a union (any of the two) between a `Response` and a `dict`.
+
+### Disable Response Model
+
+Continuing from the example above, you might not want to have the default data validation, documentation, filtering, etc. that is performed by FastAPI.
+
+But you might want to still keep the return type annotation in the function to get the support from tools like editors and type checkers (e.g. mypy).
+
+In this case, you can disable the response model generation by setting `response_model=None`:
+
+=== "Python 3.10+"
+
+ ```Python hl_lines="7"
+ {!> ../../../docs_src/response_model/tutorial003_05_py310.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/response_model/tutorial003_05.py!}
+ ```
+
+This will make FastAPI skip the response model generation and that way you can have any return type annotations you need without it affecting your FastAPI application. 🤓
+
## Response Model encoding parameters
Your response model could have default values, like:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="11 13-14"
- {!> ../../../docs_src/response_model/tutorial004.py!}
+ ```Python hl_lines="9 11-12"
+ {!> ../../../docs_src/response_model/tutorial004_py310.py!}
```
-=== "Python 3.9 and above"
+=== "Python 3.9+"
```Python hl_lines="11 13-14"
{!> ../../../docs_src/response_model/tutorial004_py39.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="9 11-12"
- {!> ../../../docs_src/response_model/tutorial004_py310.py!}
+ ```Python hl_lines="11 13-14"
+ {!> ../../../docs_src/response_model/tutorial004.py!}
```
* `description: Union[str, None] = None` (or `str | None = None` in Python 3.10) has a default of `None`.
@@ -180,22 +348,22 @@ For example, if you have models with many optional attributes in a NoSQL databas
You can set the *path operation decorator* parameter `response_model_exclude_unset=True`:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial004.py!}
+ ```Python hl_lines="22"
+ {!> ../../../docs_src/response_model/tutorial004_py310.py!}
```
-=== "Python 3.9 and above"
+=== "Python 3.9+"
```Python hl_lines="24"
{!> ../../../docs_src/response_model/tutorial004_py39.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial004_py310.py!}
+ ```Python hl_lines="24"
+ {!> ../../../docs_src/response_model/tutorial004.py!}
```
and those default values won't be included in the response, only the values actually set.
@@ -273,16 +441,16 @@ This can be used as a quick shortcut if you have only one Pydantic model and wan
This also applies to `response_model_by_alias` that works similarly.
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="31 37"
- {!> ../../../docs_src/response_model/tutorial005.py!}
+ ```Python hl_lines="29 35"
+ {!> ../../../docs_src/response_model/tutorial005_py310.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="29 35"
- {!> ../../../docs_src/response_model/tutorial005_py310.py!}
+ ```Python hl_lines="31 37"
+ {!> ../../../docs_src/response_model/tutorial005.py!}
```
!!! tip
@@ -294,16 +462,16 @@ This can be used as a quick shortcut if you have only one Pydantic model and wan
If you forget to use a `set` and use a `list` or `tuple` instead, FastAPI will still convert it to a `set` and it will work correctly:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="31 37"
- {!> ../../../docs_src/response_model/tutorial006.py!}
+ ```Python hl_lines="29 35"
+ {!> ../../../docs_src/response_model/tutorial006_py310.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="29 35"
- {!> ../../../docs_src/response_model/tutorial006_py310.py!}
+ ```Python hl_lines="31 37"
+ {!> ../../../docs_src/response_model/tutorial006.py!}
```
## Recap
diff --git a/docs/en/docs/tutorial/schema-extra-example.md b/docs/en/docs/tutorial/schema-extra-example.md
index 94347018d..5312254d9 100644
--- a/docs/en/docs/tutorial/schema-extra-example.md
+++ b/docs/en/docs/tutorial/schema-extra-example.md
@@ -8,16 +8,16 @@ Here are several ways to do it.
You can declare an `example` for a Pydantic model using `Config` and `schema_extra`, as described in Pydantic's docs: Schema customization:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="15-23"
- {!> ../../../docs_src/schema_extra_example/tutorial001.py!}
+ ```Python hl_lines="13-21"
+ {!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="13-21"
- {!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!}
+ ```Python hl_lines="15-23"
+ {!> ../../../docs_src/schema_extra_example/tutorial001.py!}
```
That extra info will be added as-is to the output **JSON Schema** for that model, and it will be used in the API docs.
@@ -33,16 +33,16 @@ When using `Field()` with Pydantic models, you can also declare extra info for t
You can use this to add `example` for each field:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="4 10-13"
- {!> ../../../docs_src/schema_extra_example/tutorial002.py!}
+ ```Python hl_lines="2 8-11"
+ {!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="2 8-11"
- {!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!}
+ ```Python hl_lines="4 10-13"
+ {!> ../../../docs_src/schema_extra_example/tutorial002.py!}
```
!!! warning
@@ -66,18 +66,39 @@ you can also declare a data `example` or a group of `examples` with additional i
Here we pass an `example` of the data expected in `Body()`:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="20-25"
- {!> ../../../docs_src/schema_extra_example/tutorial003.py!}
+ ```Python hl_lines="22-27"
+ {!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="22-27"
+ {!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="23-28"
+ {!> ../../../docs_src/schema_extra_example/tutorial003_an.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.10+ non-Annotated"
```Python hl_lines="18-23"
{!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="20-25"
+ {!> ../../../docs_src/schema_extra_example/tutorial003.py!}
+ ```
+
### Example in the docs UI
With any of the methods above it would look like this in the `/docs`:
@@ -97,18 +118,39 @@ Each specific example `dict` in the `examples` can contain:
* `value`: This is the actual example shown, e.g. a `dict`.
* `externalValue`: alternative to `value`, a URL pointing to the example. Although this might not be supported by as many tools as `value`.
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="21-47"
- {!> ../../../docs_src/schema_extra_example/tutorial004.py!}
+ ```Python hl_lines="23-49"
+ {!> ../../../docs_src/schema_extra_example/tutorial004_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="23-49"
+ {!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="24-50"
+ {!> ../../../docs_src/schema_extra_example/tutorial004_an.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.10+ non-Annotated"
```Python hl_lines="19-45"
{!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="21-47"
+ {!> ../../../docs_src/schema_extra_example/tutorial004.py!}
+ ```
+
### Examples in the docs UI
With `examples` added to `Body()` the `/docs` would look like:
diff --git a/docs/en/docs/tutorial/security/first-steps.md b/docs/en/docs/tutorial/security/first-steps.md
index 45ffaab90..5765cf2d6 100644
--- a/docs/en/docs/tutorial/security/first-steps.md
+++ b/docs/en/docs/tutorial/security/first-steps.md
@@ -20,9 +20,27 @@ Let's first just use the code and see how it works, and then we'll come back to
Copy the example in a file `main.py`:
-```Python
-{!../../../docs_src/security/tutorial001.py!}
-```
+=== "Python 3.9+"
+
+ ```Python
+ {!> ../../../docs_src/security/tutorial001_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python
+ {!> ../../../docs_src/security/tutorial001_an.py!}
+ ```
+
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python
+ {!> ../../../docs_src/security/tutorial001.py!}
+ ```
+
## Run it
@@ -116,9 +134,26 @@ In this example we are going to use **OAuth2**, with the **Password** flow, usin
When we create an instance of the `OAuth2PasswordBearer` class we pass in the `tokenUrl` parameter. This parameter contains the URL that the client (the frontend running in the user's browser) will use to send the `username` and `password` in order to get a token.
-```Python hl_lines="6"
-{!../../../docs_src/security/tutorial001.py!}
-```
+=== "Python 3.9+"
+
+ ```Python hl_lines="8"
+ {!> ../../../docs_src/security/tutorial001_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="7"
+ {!> ../../../docs_src/security/tutorial001_an.py!}
+ ```
+
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="6"
+ {!> ../../../docs_src/security/tutorial001.py!}
+ ```
!!! tip
Here `tokenUrl="token"` refers to a relative URL `token` that we haven't created yet. As it's a relative URL, it's equivalent to `./token`.
@@ -150,9 +185,26 @@ So, it can be used with `Depends`.
Now you can pass that `oauth2_scheme` in a dependency with `Depends`.
-```Python hl_lines="10"
-{!../../../docs_src/security/tutorial001.py!}
-```
+=== "Python 3.9+"
+
+ ```Python hl_lines="12"
+ {!> ../../../docs_src/security/tutorial001_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="11"
+ {!> ../../../docs_src/security/tutorial001_an.py!}
+ ```
+
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="10"
+ {!> ../../../docs_src/security/tutorial001.py!}
+ ```
This dependency will provide a `str` that is assigned to the parameter `token` of the *path operation function*.
diff --git a/docs/en/docs/tutorial/security/get-current-user.md b/docs/en/docs/tutorial/security/get-current-user.md
index 13e867216..1a8c5d9a8 100644
--- a/docs/en/docs/tutorial/security/get-current-user.md
+++ b/docs/en/docs/tutorial/security/get-current-user.md
@@ -2,9 +2,26 @@
In the previous chapter the security system (which is based on the dependency injection system) was giving the *path operation function* a `token` as a `str`:
-```Python hl_lines="10"
-{!../../../docs_src/security/tutorial001.py!}
-```
+=== "Python 3.9+"
+
+ ```Python hl_lines="12"
+ {!> ../../../docs_src/security/tutorial001_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="11"
+ {!> ../../../docs_src/security/tutorial001_an.py!}
+ ```
+
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="10"
+ {!> ../../../docs_src/security/tutorial001.py!}
+ ```
But that is still not that useful.
@@ -16,18 +33,42 @@ First, let's create a Pydantic user model.
The same way we use Pydantic to declare bodies, we can use it anywhere else:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
```Python hl_lines="5 12-16"
- {!> ../../../docs_src/security/tutorial002.py!}
+ {!> ../../../docs_src/security/tutorial002_an_py310.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.9+"
+
+ ```Python hl_lines="5 12-16"
+ {!> ../../../docs_src/security/tutorial002_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="5 13-17"
+ {!> ../../../docs_src/security/tutorial002_an.py!}
+ ```
+
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="3 10-14"
{!> ../../../docs_src/security/tutorial002_py310.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="5 12-16"
+ {!> ../../../docs_src/security/tutorial002.py!}
+ ```
+
## Create a `get_current_user` dependency
Let's create a dependency `get_current_user`.
@@ -38,50 +79,122 @@ Remember that dependencies can have sub-dependencies?
The same as we were doing before in the *path operation* directly, our new dependency `get_current_user` will receive a `token` as a `str` from the sub-dependency `oauth2_scheme`:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
```Python hl_lines="25"
- {!> ../../../docs_src/security/tutorial002.py!}
+ {!> ../../../docs_src/security/tutorial002_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="25"
+ {!> ../../../docs_src/security/tutorial002_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="26"
+ {!> ../../../docs_src/security/tutorial002_an.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="23"
{!> ../../../docs_src/security/tutorial002_py310.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="25"
+ {!> ../../../docs_src/security/tutorial002.py!}
+ ```
+
## Get the user
`get_current_user` will use a (fake) utility function we created, that takes a token as a `str` and returns our Pydantic `User` model:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
```Python hl_lines="19-22 26-27"
- {!> ../../../docs_src/security/tutorial002.py!}
+ {!> ../../../docs_src/security/tutorial002_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="19-22 26-27"
+ {!> ../../../docs_src/security/tutorial002_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="20-23 27-28"
+ {!> ../../../docs_src/security/tutorial002_an.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="17-20 24-25"
{!> ../../../docs_src/security/tutorial002_py310.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="19-22 26-27"
+ {!> ../../../docs_src/security/tutorial002.py!}
+ ```
+
## Inject the current user
So now we can use the same `Depends` with our `get_current_user` in the *path operation*:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
```Python hl_lines="31"
- {!> ../../../docs_src/security/tutorial002.py!}
+ {!> ../../../docs_src/security/tutorial002_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="31"
+ {!> ../../../docs_src/security/tutorial002_an_py39.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
+
+ ```Python hl_lines="32"
+ {!> ../../../docs_src/security/tutorial002_an.py!}
+ ```
+
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="29"
{!> ../../../docs_src/security/tutorial002_py310.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="31"
+ {!> ../../../docs_src/security/tutorial002.py!}
+ ```
+
Notice that we declare the type of `current_user` as the Pydantic model `User`.
This will help us inside of the function with all the completion and type checks.
@@ -128,18 +241,42 @@ And all of them (or any portion of them that you want) can take the advantage of
And all these thousands of *path operations* can be as small as 3 lines:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
```Python hl_lines="30-32"
- {!> ../../../docs_src/security/tutorial002.py!}
+ {!> ../../../docs_src/security/tutorial002_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="30-32"
+ {!> ../../../docs_src/security/tutorial002_an_py39.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
+
+ ```Python hl_lines="31-33"
+ {!> ../../../docs_src/security/tutorial002_an.py!}
+ ```
+
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="28-30"
{!> ../../../docs_src/security/tutorial002_py310.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="30-32"
+ {!> ../../../docs_src/security/tutorial002.py!}
+ ```
+
## Recap
You can now get the current user directly in your *path operation function*.
diff --git a/docs/en/docs/tutorial/security/oauth2-jwt.md b/docs/en/docs/tutorial/security/oauth2-jwt.md
index 41f00fd41..deb722b96 100644
--- a/docs/en/docs/tutorial/security/oauth2-jwt.md
+++ b/docs/en/docs/tutorial/security/oauth2-jwt.md
@@ -109,18 +109,42 @@ And another utility to verify if a received password matches the hash stored.
And another one to authenticate and return a user.
-=== "Python 3.6 and above"
+=== "Python 3.10+"
```Python hl_lines="7 48 55-56 59-60 69-75"
- {!> ../../../docs_src/security/tutorial004.py!}
+ {!> ../../../docs_src/security/tutorial004_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="7 48 55-56 59-60 69-75"
+ {!> ../../../docs_src/security/tutorial004_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="7 49 56-57 60-61 70-76"
+ {!> ../../../docs_src/security/tutorial004_an.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="6 47 54-55 58-59 68-74"
{!> ../../../docs_src/security/tutorial004_py310.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="7 48 55-56 59-60 69-75"
+ {!> ../../../docs_src/security/tutorial004.py!}
+ ```
+
!!! note
If you check the new (fake) database `fake_users_db`, you will see how the hashed password looks like now: `"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`.
@@ -152,18 +176,42 @@ Define a Pydantic Model that will be used in the token endpoint for the response
Create a utility function to generate a new access token.
-=== "Python 3.6 and above"
+=== "Python 3.10+"
```Python hl_lines="6 12-14 28-30 78-86"
- {!> ../../../docs_src/security/tutorial004.py!}
+ {!> ../../../docs_src/security/tutorial004_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="6 12-14 28-30 78-86"
+ {!> ../../../docs_src/security/tutorial004_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="6 13-15 29-31 79-87"
+ {!> ../../../docs_src/security/tutorial004_an.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="5 11-13 27-29 77-85"
{!> ../../../docs_src/security/tutorial004_py310.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="6 12-14 28-30 78-86"
+ {!> ../../../docs_src/security/tutorial004.py!}
+ ```
+
## Update the dependencies
Update `get_current_user` to receive the same token as before, but this time, using JWT tokens.
@@ -172,36 +220,84 @@ Decode the received token, verify it, and return the current user.
If the token is invalid, return an HTTP error right away.
-=== "Python 3.6 and above"
+=== "Python 3.10+"
```Python hl_lines="89-106"
- {!> ../../../docs_src/security/tutorial004.py!}
+ {!> ../../../docs_src/security/tutorial004_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="89-106"
+ {!> ../../../docs_src/security/tutorial004_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="90-107"
+ {!> ../../../docs_src/security/tutorial004_an.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="88-105"
{!> ../../../docs_src/security/tutorial004_py310.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="89-106"
+ {!> ../../../docs_src/security/tutorial004.py!}
+ ```
+
## Update the `/token` *path operation*
Create a `timedelta` with the expiration time of the token.
-Create a real JWT access token and return it.
+Create a real JWT access token and return it
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="115-128"
- {!> ../../../docs_src/security/tutorial004.py!}
+ ```Python hl_lines="117-132"
+ {!> ../../../docs_src/security/tutorial004_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="117-132"
+ {!> ../../../docs_src/security/tutorial004_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="118-133"
+ {!> ../../../docs_src/security/tutorial004_an.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="114-127"
{!> ../../../docs_src/security/tutorial004_py310.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="115-128"
+ {!> ../../../docs_src/security/tutorial004.py!}
+ ```
+
### Technical details about the JWT "subject" `sub`
The JWT specification says that there's a key `sub`, with the subject of the token.
diff --git a/docs/en/docs/tutorial/security/simple-oauth2.md b/docs/en/docs/tutorial/security/simple-oauth2.md
index 505b223b1..abcf6b667 100644
--- a/docs/en/docs/tutorial/security/simple-oauth2.md
+++ b/docs/en/docs/tutorial/security/simple-oauth2.md
@@ -49,18 +49,42 @@ Now let's use the utilities provided by **FastAPI** to handle this.
First, import `OAuth2PasswordRequestForm`, and use it as a dependency with `Depends` in the *path operation* for `/token`:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="4 76"
- {!> ../../../docs_src/security/tutorial003.py!}
+ ```Python hl_lines="4 78"
+ {!> ../../../docs_src/security/tutorial003_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="4 78"
+ {!> ../../../docs_src/security/tutorial003_an_py39.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
+
+ ```Python hl_lines="4 79"
+ {!> ../../../docs_src/security/tutorial003_an.py!}
+ ```
+
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="2 74"
{!> ../../../docs_src/security/tutorial003_py310.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="4 76"
+ {!> ../../../docs_src/security/tutorial003.py!}
+ ```
+
`OAuth2PasswordRequestForm` is a class dependency that declares a form body with:
* The `username`.
@@ -98,18 +122,42 @@ If there is no such user, we return an error saying "incorrect username or passw
For the error, we use the exception `HTTPException`:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="3 77-79"
- {!> ../../../docs_src/security/tutorial003.py!}
+ ```Python hl_lines="3 79-81"
+ {!> ../../../docs_src/security/tutorial003_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="3 79-81"
+ {!> ../../../docs_src/security/tutorial003_an_py39.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
+
+ ```Python hl_lines="3 80-82"
+ {!> ../../../docs_src/security/tutorial003_an.py!}
+ ```
+
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="1 75-77"
{!> ../../../docs_src/security/tutorial003_py310.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="3 77-79"
+ {!> ../../../docs_src/security/tutorial003.py!}
+ ```
+
### Check the password
At this point we have the user data from our database, but we haven't checked the password.
@@ -134,18 +182,42 @@ If your database is stolen, the thief won't have your users' plaintext passwords
So, the thief won't be able to try to use those same passwords in another system (as many users use the same password everywhere, this would be dangerous).
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="80-83"
- {!> ../../../docs_src/security/tutorial003.py!}
+ ```Python hl_lines="82-85"
+ {!> ../../../docs_src/security/tutorial003_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="82-85"
+ {!> ../../../docs_src/security/tutorial003_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="83-86"
+ {!> ../../../docs_src/security/tutorial003_an.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="78-81"
{!> ../../../docs_src/security/tutorial003_py310.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="80-83"
+ {!> ../../../docs_src/security/tutorial003.py!}
+ ```
+
#### About `**user_dict`
`UserInDB(**user_dict)` means:
@@ -180,18 +252,42 @@ For this simple example, we are going to just be completely insecure and return
But for now, let's focus on the specific details we need.
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="85"
- {!> ../../../docs_src/security/tutorial003.py!}
+ ```Python hl_lines="87"
+ {!> ../../../docs_src/security/tutorial003_an_py310.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.9+"
+
+ ```Python hl_lines="87"
+ {!> ../../../docs_src/security/tutorial003_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="88"
+ {!> ../../../docs_src/security/tutorial003_an.py!}
+ ```
+
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python hl_lines="83"
{!> ../../../docs_src/security/tutorial003_py310.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="85"
+ {!> ../../../docs_src/security/tutorial003.py!}
+ ```
+
!!! tip
By the spec, you should return a JSON with an `access_token` and a `token_type`, the same as in this example.
@@ -213,18 +309,42 @@ Both of these dependencies will just return an HTTP error if the user doesn't ex
So, in our endpoint, we will only get a user if the user exists, was correctly authenticated, and is active:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="58-66 69-72 90"
- {!> ../../../docs_src/security/tutorial003.py!}
+ ```Python hl_lines="58-66 69-74 94"
+ {!> ../../../docs_src/security/tutorial003_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="58-66 69-74 94"
+ {!> ../../../docs_src/security/tutorial003_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="59-67 70-75 95"
+ {!> ../../../docs_src/security/tutorial003_an.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="55-64 67-70 88"
+ ```Python hl_lines="56-64 67-70 88"
{!> ../../../docs_src/security/tutorial003_py310.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="58-66 69-72 90"
+ {!> ../../../docs_src/security/tutorial003.py!}
+ ```
+
!!! info
The additional header `WWW-Authenticate` with value `Bearer` we are returning here is also part of the spec.
diff --git a/docs/en/docs/tutorial/sql-databases.md b/docs/en/docs/tutorial/sql-databases.md
index 5ccaf05ec..fd66c5add 100644
--- a/docs/en/docs/tutorial/sql-databases.md
+++ b/docs/en/docs/tutorial/sql-databases.md
@@ -262,22 +262,22 @@ So, the user will also have a `password` when creating it.
But for security, the `password` won't be in other Pydantic *models*, for example, it won't be sent from the API when reading a user.
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="3 6-8 11-12 23-24 27-28"
- {!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
+ ```Python hl_lines="1 4-6 9-10 21-22 25-26"
+ {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
```
-=== "Python 3.9 and above"
+=== "Python 3.9+"
```Python hl_lines="3 6-8 11-12 23-24 27-28"
{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="1 4-6 9-10 21-22 25-26"
- {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
+ ```Python hl_lines="3 6-8 11-12 23-24 27-28"
+ {!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
```
#### SQLAlchemy style and Pydantic style
@@ -306,22 +306,22 @@ The same way, when reading a user, we can now declare that `items` will contain
Not only the IDs of those items, but all the data that we defined in the Pydantic *model* for reading items: `Item`.
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="15-17 31-34"
- {!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
+ ```Python hl_lines="13-15 29-32"
+ {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
```
-=== "Python 3.9 and above"
+=== "Python 3.9+"
```Python hl_lines="15-17 31-34"
{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="13-15 29-32"
- {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
+ ```Python hl_lines="15-17 31-34"
+ {!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
```
!!! tip
@@ -335,22 +335,22 @@ This ../../../docs_src/sql_databases/sql_app/schemas.py!}
+ ```Python hl_lines="13 17-18 29 34-35"
+ {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
```
-=== "Python 3.9 and above"
+=== "Python 3.9+"
```Python hl_lines="15 19-20 31 36-37"
{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="13 17-18 29 34-35"
- {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
+ ```Python hl_lines="15 19-20 31 36-37"
+ {!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
```
!!! tip
@@ -481,16 +481,16 @@ And now in the file `sql_app/main.py` let's integrate and use all the other part
In a very simplistic way create the database tables:
-=== "Python 3.6 and above"
+=== "Python 3.9+"
- ```Python hl_lines="9"
- {!> ../../../docs_src/sql_databases/sql_app/main.py!}
+ ```Python hl_lines="7"
+ {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
```
-=== "Python 3.9 and above"
+=== "Python 3.6+"
- ```Python hl_lines="7"
- {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/sql_databases/sql_app/main.py!}
```
#### Alembic Note
@@ -515,16 +515,16 @@ For that, we will create a new dependency with `yield`, as explained before in t
Our dependency will create a new SQLAlchemy `SessionLocal` that will be used in a single request, and then close it once the request is finished.
-=== "Python 3.6 and above"
+=== "Python 3.9+"
- ```Python hl_lines="15-20"
- {!> ../../../docs_src/sql_databases/sql_app/main.py!}
+ ```Python hl_lines="13-18"
+ {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
```
-=== "Python 3.9 and above"
+=== "Python 3.6+"
- ```Python hl_lines="13-18"
- {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
+ ```Python hl_lines="15-20"
+ {!> ../../../docs_src/sql_databases/sql_app/main.py!}
```
!!! info
@@ -540,16 +540,16 @@ And then, when using the dependency in a *path operation function*, we declare i
This will then give us better editor support inside the *path operation function*, because the editor will know that the `db` parameter is of type `Session`:
-=== "Python 3.6 and above"
+=== "Python 3.9+"
- ```Python hl_lines="24 32 38 47 53"
- {!> ../../../docs_src/sql_databases/sql_app/main.py!}
+ ```Python hl_lines="22 30 36 45 51"
+ {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
```
-=== "Python 3.9 and above"
+=== "Python 3.6+"
- ```Python hl_lines="22 30 36 45 51"
- {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
+ ```Python hl_lines="24 32 38 47 53"
+ {!> ../../../docs_src/sql_databases/sql_app/main.py!}
```
!!! info "Technical Details"
@@ -561,16 +561,16 @@ This will then give us better editor support inside the *path operation function
Now, finally, here's the standard **FastAPI** *path operations* code.
-=== "Python 3.6 and above"
+=== "Python 3.9+"
- ```Python hl_lines="23-28 31-34 37-42 45-49 52-55"
- {!> ../../../docs_src/sql_databases/sql_app/main.py!}
+ ```Python hl_lines="21-26 29-32 35-40 43-47 50-53"
+ {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
```
-=== "Python 3.9 and above"
+=== "Python 3.6+"
- ```Python hl_lines="21-26 29-32 35-40 43-47 50-53"
- {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
+ ```Python hl_lines="23-28 31-34 37-42 45-49 52-55"
+ {!> ../../../docs_src/sql_databases/sql_app/main.py!}
```
We are creating the database session before each request in the dependency with `yield`, and then closing it afterwards.
@@ -654,22 +654,22 @@ For example, in a background task worker with ../../../docs_src/sql_databases/sql_app/schemas.py!}
+ {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
```
-=== "Python 3.9 and above"
+=== "Python 3.9+"
```Python
{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
```Python
- {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
+ {!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
```
* `sql_app/crud.py`:
@@ -680,16 +680,16 @@ For example, in a background task worker with ../../../docs_src/sql_databases/sql_app/main.py!}
+ {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
```
-=== "Python 3.9 and above"
+=== "Python 3.6+"
```Python
- {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
+ {!> ../../../docs_src/sql_databases/sql_app/main.py!}
```
## Check it
@@ -739,16 +739,16 @@ A "middleware" is basically a function that is always executed for each request,
The middleware we'll add (just a function) will create a new SQLAlchemy `SessionLocal` for each request, add it to the request and then close it once the request is finished.
-=== "Python 3.6 and above"
+=== "Python 3.9+"
- ```Python hl_lines="14-22"
- {!> ../../../docs_src/sql_databases/sql_app/alt_main.py!}
+ ```Python hl_lines="12-20"
+ {!> ../../../docs_src/sql_databases/sql_app_py39/alt_main.py!}
```
-=== "Python 3.9 and above"
+=== "Python 3.6+"
- ```Python hl_lines="12-20"
- {!> ../../../docs_src/sql_databases/sql_app_py39/alt_main.py!}
+ ```Python hl_lines="14-22"
+ {!> ../../../docs_src/sql_databases/sql_app/alt_main.py!}
```
!!! info
diff --git a/docs/en/docs/tutorial/testing.md b/docs/en/docs/tutorial/testing.md
index be07aab37..ec133a4d0 100644
--- a/docs/en/docs/tutorial/testing.md
+++ b/docs/en/docs/tutorial/testing.md
@@ -110,18 +110,42 @@ It has a `POST` operation that could return several errors.
Both *path operations* require an `X-Token` header.
-=== "Python 3.6 and above"
+=== "Python 3.10+"
```Python
- {!> ../../../docs_src/app_testing/app_b/main.py!}
+ {!> ../../../docs_src/app_testing/app_b_an_py310/main.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python
+ {!> ../../../docs_src/app_testing/app_b_an_py39/main.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python
+ {!> ../../../docs_src/app_testing/app_b_an/main.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
```Python
{!> ../../../docs_src/app_testing/app_b_py310/main.py!}
```
+=== "Python 3.6+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python
+ {!> ../../../docs_src/app_testing/app_b/main.py!}
+ ```
+
### Extended testing file
You could then update `test_main.py` with the extended tests:
diff --git a/docs/en/mkdocs.yml b/docs/en/mkdocs.yml
index 69ad29624..fd7decee8 100644
--- a/docs/en/mkdocs.yml
+++ b/docs/en/mkdocs.yml
@@ -40,11 +40,14 @@ nav:
- Languages:
- en: /
- az: /az/
+ - cs: /cs/
- de: /de/
+ - em: /em/
- es: /es/
- fa: /fa/
- fr: /fr/
- he: /he/
+ - hy: /hy/
- id: /id/
- it: /it/
- ja: /ja/
@@ -55,6 +58,7 @@ nav:
- ru: /ru/
- sq: /sq/
- sv: /sv/
+ - ta: /ta/
- tr: /tr/
- uk: /uk/
- zh: /zh/
@@ -187,7 +191,7 @@ markdown_extensions:
extra:
analytics:
provider: google
- property: UA-133183413-1
+ property: G-YNEVN69SC3
social:
- icon: fontawesome/brands/github-alt
link: https://github.com/tiangolo/fastapi
@@ -208,8 +212,12 @@ extra:
name: en - English
- link: /az/
name: az
+ - link: /cs/
+ name: cs
- link: /de/
name: de
+ - link: /em/
+ name: 😉
- link: /es/
name: es - español
- link: /fa/
@@ -218,6 +226,8 @@ extra:
name: fr - français
- link: /he/
name: he
+ - link: /hy/
+ name: hy
- link: /id/
name: id
- link: /it/
@@ -238,6 +248,8 @@ extra:
name: sq - shqip
- link: /sv/
name: sv - svenska
+ - link: /ta/
+ name: ta - தமிழ்
- link: /tr/
name: tr - Türkçe
- link: /uk/
diff --git a/docs/en/overrides/main.html b/docs/en/overrides/main.html
index e9b9f60eb..9125b1d46 100644
--- a/docs/en/overrides/main.html
+++ b/docs/en/overrides/main.html
@@ -22,30 +22,12 @@
{% endblock %}
diff --git a/docs/es/mkdocs.yml b/docs/es/mkdocs.yml
index d1d6215b6..85db87ad1 100644
--- a/docs/es/mkdocs.yml
+++ b/docs/es/mkdocs.yml
@@ -40,11 +40,14 @@ nav:
- Languages:
- en: /
- az: /az/
+ - cs: /cs/
- de: /de/
+ - em: /em/
- es: /es/
- fa: /fa/
- fr: /fr/
- he: /he/
+ - hy: /hy/
- id: /id/
- it: /it/
- ja: /ja/
@@ -55,6 +58,7 @@ nav:
- ru: /ru/
- sq: /sq/
- sv: /sv/
+ - ta: /ta/
- tr: /tr/
- uk: /uk/
- zh: /zh/
@@ -90,7 +94,7 @@ markdown_extensions:
extra:
analytics:
provider: google
- property: UA-133183413-1
+ property: G-YNEVN69SC3
social:
- icon: fontawesome/brands/github-alt
link: https://github.com/tiangolo/fastapi
@@ -111,8 +115,12 @@ extra:
name: en - English
- link: /az/
name: az
+ - link: /cs/
+ name: cs
- link: /de/
name: de
+ - link: /em/
+ name: 😉
- link: /es/
name: es - español
- link: /fa/
@@ -121,6 +129,8 @@ extra:
name: fr - français
- link: /he/
name: he
+ - link: /hy/
+ name: hy
- link: /id/
name: id
- link: /it/
@@ -141,6 +151,8 @@ extra:
name: sq - shqip
- link: /sv/
name: sv - svenska
+ - link: /ta/
+ name: ta - தமிழ்
- link: /tr/
name: tr - Türkçe
- link: /uk/
diff --git a/docs/fa/docs/index.md b/docs/fa/docs/index.md
index dfc4d24e3..ebaa8085a 100644
--- a/docs/fa/docs/index.md
+++ b/docs/fa/docs/index.md
@@ -143,7 +143,7 @@ $ pip install "uvicorn[standard]"
* فایلی به نام `main.py` با محتوای زیر ایجاد کنید :
```Python
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
diff --git a/docs/fa/mkdocs.yml b/docs/fa/mkdocs.yml
index 7c2fe5eab..5bb1a2ff5 100644
--- a/docs/fa/mkdocs.yml
+++ b/docs/fa/mkdocs.yml
@@ -40,11 +40,14 @@ nav:
- Languages:
- en: /
- az: /az/
+ - cs: /cs/
- de: /de/
+ - em: /em/
- es: /es/
- fa: /fa/
- fr: /fr/
- he: /he/
+ - hy: /hy/
- id: /id/
- it: /it/
- ja: /ja/
@@ -55,6 +58,7 @@ nav:
- ru: /ru/
- sq: /sq/
- sv: /sv/
+ - ta: /ta/
- tr: /tr/
- uk: /uk/
- zh: /zh/
@@ -80,7 +84,7 @@ markdown_extensions:
extra:
analytics:
provider: google
- property: UA-133183413-1
+ property: G-YNEVN69SC3
social:
- icon: fontawesome/brands/github-alt
link: https://github.com/tiangolo/fastapi
@@ -101,8 +105,12 @@ extra:
name: en - English
- link: /az/
name: az
+ - link: /cs/
+ name: cs
- link: /de/
name: de
+ - link: /em/
+ name: 😉
- link: /es/
name: es - español
- link: /fa/
@@ -111,6 +119,8 @@ extra:
name: fr - français
- link: /he/
name: he
+ - link: /hy/
+ name: hy
- link: /id/
name: id
- link: /it/
@@ -131,6 +141,8 @@ extra:
name: sq - shqip
- link: /sv/
name: sv - svenska
+ - link: /ta/
+ name: ta - தமிழ்
- link: /tr/
name: tr - Türkçe
- link: /uk/
diff --git a/docs/fr/docs/advanced/index.md b/docs/fr/docs/advanced/index.md
new file mode 100644
index 000000000..41737889a
--- /dev/null
+++ b/docs/fr/docs/advanced/index.md
@@ -0,0 +1,24 @@
+# Guide de l'utilisateur avancé - Introduction
+
+## Caractéristiques supplémentaires
+
+Le [Tutoriel - Guide de l'utilisateur](../tutorial/){.internal-link target=_blank} devrait suffire à vous faire découvrir toutes les fonctionnalités principales de **FastAPI**.
+
+Dans les sections suivantes, vous verrez des options, configurations et fonctionnalités supplémentaires.
+
+!!! Note
+ Les sections de ce chapitre ne sont **pas nécessairement "avancées"**.
+
+ Et il est possible que pour votre cas d'utilisation, la solution se trouve dans l'un d'entre eux.
+
+## Lisez d'abord le didacticiel
+
+Vous pouvez utiliser la plupart des fonctionnalités de **FastAPI** grâce aux connaissances du [Tutoriel - Guide de l'utilisateur](../tutorial/){.internal-link target=_blank}.
+
+Et les sections suivantes supposent que vous l'avez lu et que vous en connaissez les idées principales.
+
+## Cours TestDriven.io
+
+Si vous souhaitez suivre un cours pour débutants avancés pour compléter cette section de la documentation, vous pouvez consulter : Développement piloté par les tests avec FastAPI et Docker par **TestDriven.io**.
+
+10 % de tous les bénéfices de ce cours sont reversés au développement de **FastAPI**. 🎉 😄
diff --git a/docs/fr/docs/advanced/path-operation-advanced-configuration.md b/docs/fr/docs/advanced/path-operation-advanced-configuration.md
new file mode 100644
index 000000000..ace9f19f9
--- /dev/null
+++ b/docs/fr/docs/advanced/path-operation-advanced-configuration.md
@@ -0,0 +1,168 @@
+# Configuration avancée des paramètres de chemin
+
+## ID d'opération OpenAPI
+
+!!! Attention
+ Si vous n'êtes pas un "expert" en OpenAPI, vous n'en avez probablement pas besoin.
+
+Dans OpenAPI, les chemins sont des ressources, tels que /users/ ou /items/, exposées par votre API, et les opérations sont les méthodes HTTP utilisées pour manipuler ces chemins, telles que GET, POST ou DELETE. Les operationId sont des chaînes uniques facultatives utilisées pour identifier une opération d'un chemin. Vous pouvez définir l'OpenAPI `operationId` à utiliser dans votre *opération de chemin* avec le paramètre `operation_id`.
+
+Vous devez vous assurer qu'il est unique pour chaque opération.
+
+```Python hl_lines="6"
+{!../../../docs_src/path_operation_advanced_configuration/tutorial001.py!}
+```
+
+### Utilisation du nom *path operation function* comme operationId
+
+Si vous souhaitez utiliser les noms de fonction de vos API comme `operationId`, vous pouvez les parcourir tous et remplacer chaque `operation_id` de l'*opération de chemin* en utilisant leur `APIRoute.name`.
+
+Vous devriez le faire après avoir ajouté toutes vos *paramètres de chemin*.
+
+```Python hl_lines="2 12-21 24"
+{!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!}
+```
+
+!!! Astuce
+ Si vous appelez manuellement `app.openapi()`, vous devez mettre à jour les `operationId` avant.
+
+!!! Attention
+ Pour faire cela, vous devez vous assurer que chacun de vos *chemin* ait un nom unique.
+
+ Même s'ils se trouvent dans des modules différents (fichiers Python).
+
+## Exclusion d'OpenAPI
+
+Pour exclure un *chemin* du schéma OpenAPI généré (et donc des systèmes de documentation automatiques), utilisez le paramètre `include_in_schema` et assignez-lui la valeur `False` :
+
+```Python hl_lines="6"
+{!../../../docs_src/path_operation_advanced_configuration/tutorial003.py!}
+```
+
+## Description avancée de docstring
+
+Vous pouvez limiter le texte utilisé de la docstring d'une *fonction de chemin* qui sera affiché sur OpenAPI.
+
+L'ajout d'un `\f` (un caractère d'échappement "form feed") va permettre à **FastAPI** de tronquer la sortie utilisée pour OpenAPI à ce stade.
+
+Il n'apparaîtra pas dans la documentation, mais d'autres outils (tel que Sphinx) pourront utiliser le reste.
+
+```Python hl_lines="19-29"
+{!../../../docs_src/path_operation_advanced_configuration/tutorial004.py!}
+```
+
+## Réponses supplémentaires
+
+Vous avez probablement vu comment déclarer le `response_model` et le `status_code` pour une *opération de chemin*.
+
+Cela définit les métadonnées sur la réponse principale d'une *opération de chemin*.
+
+Vous pouvez également déclarer des réponses supplémentaires avec leurs modèles, codes de statut, etc.
+
+Il y a un chapitre entier ici dans la documentation à ce sujet, vous pouvez le lire sur [Réponses supplémentaires dans OpenAPI](./additional-responses.md){.internal-link target=_blank}.
+
+## OpenAPI supplémentaire
+
+Lorsque vous déclarez un *chemin* dans votre application, **FastAPI** génère automatiquement les métadonnées concernant ce *chemin* à inclure dans le schéma OpenAPI.
+
+!!! note "Détails techniques"
+ La spécification OpenAPI appelle ces métaonnées des Objets d'opération.
+
+Il contient toutes les informations sur le *chemin* et est utilisé pour générer automatiquement la documentation.
+
+Il inclut les `tags`, `parameters`, `requestBody`, `responses`, etc.
+
+Ce schéma OpenAPI spécifique aux *operations* est normalement généré automatiquement par **FastAPI**, mais vous pouvez également l'étendre.
+
+!!! Astuce
+ Si vous avez seulement besoin de déclarer des réponses supplémentaires, un moyen plus pratique de le faire est d'utiliser les [réponses supplémentaires dans OpenAPI](./additional-responses.md){.internal-link target=_blank}.
+
+Vous pouvez étendre le schéma OpenAPI pour une *opération de chemin* en utilisant le paramètre `openapi_extra`.
+
+### Extensions OpenAPI
+
+Cet `openapi_extra` peut être utile, par exemple, pour déclarer [OpenAPI Extensions](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions) :
+
+```Python hl_lines="6"
+{!../../../docs_src/path_operation_advanced_configuration/tutorial005.py!}
+```
+
+Si vous ouvrez la documentation automatique de l'API, votre extension apparaîtra au bas du *chemin* spécifique.
+
+
+
+Et dans le fichier openapi généré (`/openapi.json`), vous verrez également votre extension dans le cadre du *chemin* spécifique :
+
+```JSON hl_lines="22"
+{
+ "openapi": "3.0.2",
+ "info": {
+ "title": "FastAPI",
+ "version": "0.1.0"
+ },
+ "paths": {
+ "/items/": {
+ "get": {
+ "summary": "Read Items",
+ "operationId": "read_items_items__get",
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {}
+ }
+ }
+ }
+ },
+ "x-aperture-labs-portal": "blue"
+ }
+ }
+ }
+}
+```
+
+### Personnalisation du Schéma OpenAPI pour un chemin
+
+Le dictionnaire contenu dans la variable `openapi_extra` sera fusionné avec le schéma OpenAPI généré automatiquement pour l'*opération de chemin*.
+
+Ainsi, vous pouvez ajouter des données supplémentaires au schéma généré automatiquement.
+
+Par exemple, vous pouvez décider de lire et de valider la requête avec votre propre code, sans utiliser les fonctionnalités automatiques de validation proposée par Pydantic, mais vous pouvez toujours définir la requête dans le schéma OpenAPI.
+
+Vous pouvez le faire avec `openapi_extra` :
+
+```Python hl_lines="20-37 39-40"
+{!../../../docs_src/path_operation_advanced_configuration/tutorial006.py !}
+```
+
+Dans cet exemple, nous n'avons déclaré aucun modèle Pydantic. En fait, le corps de la requête n'est même pas parsé en tant que JSON, il est lu directement en tant que `bytes`, et la fonction `magic_data_reader()` serait chargé de l'analyser d'une manière ou d'une autre.
+
+Néanmoins, nous pouvons déclarer le schéma attendu pour le corps de la requête.
+
+### Type de contenu OpenAPI personnalisé
+
+En utilisant cette même astuce, vous pouvez utiliser un modèle Pydantic pour définir le schéma JSON qui est ensuite inclus dans la section de schéma OpenAPI personnalisée pour le *chemin* concerné.
+
+Et vous pouvez le faire même si le type de données dans la requête n'est pas au format JSON.
+
+Dans cet exemple, nous n'utilisons pas les fonctionnalités de FastAPI pour extraire le schéma JSON des modèles Pydantic ni la validation automatique pour JSON. En fait, nous déclarons le type de contenu de la requête en tant que YAML, et non JSON :
+
+```Python hl_lines="17-22 24"
+{!../../../docs_src/path_operation_advanced_configuration/tutorial007.py!}
+```
+
+Néanmoins, bien que nous n'utilisions pas la fonctionnalité par défaut, nous utilisons toujours un modèle Pydantic pour générer manuellement le schéma JSON pour les données que nous souhaitons recevoir en YAML.
+
+Ensuite, nous utilisons directement la requête et extrayons son contenu en tant qu'octets. Cela signifie que FastAPI n'essaiera même pas d'analyser le payload de la requête en tant que JSON.
+
+Et nous analysons directement ce contenu YAML, puis nous utilisons à nouveau le même modèle Pydantic pour valider le contenu YAML :
+
+```Python hl_lines="26-33"
+{!../../../docs_src/path_operation_advanced_configuration/tutorial007.py!}
+```
+
+!!! Astuce
+ Ici, nous réutilisons le même modèle Pydantic.
+
+ Mais nous aurions pu tout aussi bien pu le valider d'une autre manière.
diff --git a/docs/fr/docs/advanced/response-directly.md b/docs/fr/docs/advanced/response-directly.md
new file mode 100644
index 000000000..1c923fb82
--- /dev/null
+++ b/docs/fr/docs/advanced/response-directly.md
@@ -0,0 +1,63 @@
+# Renvoyer directement une réponse
+
+Lorsque vous créez une *opération de chemins* **FastAPI**, vous pouvez normalement retourner n'importe quelle donnée : un `dict`, une `list`, un modèle Pydantic, un modèle de base de données, etc.
+
+Par défaut, **FastAPI** convertirait automatiquement cette valeur de retour en JSON en utilisant le `jsonable_encoder` expliqué dans [JSON Compatible Encoder](../tutorial/encoder.md){.internal-link target=_blank}.
+
+Ensuite, en arrière-plan, il mettra ces données JSON-compatible (par exemple un `dict`) à l'intérieur d'un `JSONResponse` qui sera utilisé pour envoyer la réponse au client.
+
+Mais vous pouvez retourner une `JSONResponse` directement à partir de vos *opérations de chemin*.
+
+Cela peut être utile, par exemple, pour retourner des en-têtes personnalisés ou des cookies.
+
+## Renvoyer une `Response`
+
+En fait, vous pouvez retourner n'importe quelle `Response` ou n'importe quelle sous-classe de celle-ci.
+
+!!! Note
+ `JSONResponse` est elle-même une sous-classe de `Response`.
+
+Et quand vous retournez une `Response`, **FastAPI** la transmet directement.
+
+Elle ne fera aucune conversion de données avec les modèles Pydantic, elle ne convertira pas le contenu en un type quelconque.
+
+Cela vous donne beaucoup de flexibilité. Vous pouvez retourner n'importe quel type de données, surcharger n'importe quelle déclaration ou validation de données.
+
+## Utiliser le `jsonable_encoder` dans une `Response`
+
+Parce que **FastAPI** n'apporte aucune modification à une `Response` que vous retournez, vous devez vous assurer que son contenu est prêt à être utilisé (sérialisable).
+
+Par exemple, vous ne pouvez pas mettre un modèle Pydantic dans une `JSONResponse` sans d'abord le convertir en un `dict` avec tous les types de données (comme `datetime`, `UUID`, etc.) convertis en types compatibles avec JSON.
+
+Pour ces cas, vous pouvez spécifier un appel à `jsonable_encoder` pour convertir vos données avant de les passer à une réponse :
+
+```Python hl_lines="6-7 21-22"
+{!../../../docs_src/response_directly/tutorial001.py!}
+```
+
+!!! note "Détails techniques"
+ Vous pouvez aussi utiliser `from starlette.responses import JSONResponse`.
+
+ **FastAPI** fournit le même objet `starlette.responses` que `fastapi.responses` juste par commodité pour le développeur. Mais la plupart des réponses disponibles proviennent directement de Starlette.
+
+## Renvoyer une `Response` personnalisée
+
+L'exemple ci-dessus montre toutes les parties dont vous avez besoin, mais il n'est pas encore très utile, car vous auriez pu retourner l'`item` directement, et **FastAPI** l'aurait mis dans une `JSONResponse` pour vous, en le convertissant en `dict`, etc. Tout cela par défaut.
+
+Maintenant, voyons comment vous pourriez utiliser cela pour retourner une réponse personnalisée.
+
+Disons que vous voulez retourner une réponse XML.
+
+Vous pouvez mettre votre contenu XML dans une chaîne de caractères, la placer dans une `Response`, et la retourner :
+
+```Python hl_lines="1 18"
+{!../../../docs_src/response_directly/tutorial002.py!}
+```
+
+## Notes
+
+Lorsque vous renvoyez une `Response` directement, ses données ne sont pas validées, converties (sérialisées), ni documentées automatiquement.
+
+Mais vous pouvez toujours les documenter comme décrit dans [Additional Responses in OpenAPI](additional-responses.md){.internal-link target=_blank}.
+
+Vous pouvez voir dans les sections suivantes comment utiliser/déclarer ces `Response`s personnalisées tout en conservant la conversion automatique des données, la documentation, etc.
diff --git a/docs/fr/docs/deployment/manually.md b/docs/fr/docs/deployment/manually.md
new file mode 100644
index 000000000..c53e2db67
--- /dev/null
+++ b/docs/fr/docs/deployment/manually.md
@@ -0,0 +1,153 @@
+# Exécuter un serveur manuellement - Uvicorn
+
+La principale chose dont vous avez besoin pour exécuter une application **FastAPI** sur une machine serveur distante est un programme serveur ASGI tel que **Uvicorn**.
+
+Il existe 3 principales alternatives :
+
+* Uvicorn : un serveur ASGI haute performance.
+* Hypercorn : un serveur
+ ASGI compatible avec HTTP/2 et Trio entre autres fonctionnalités.
+* Daphne : le serveur ASGI
+ conçu pour Django Channels.
+
+## Machine serveur et programme serveur
+
+Il y a un petit détail sur les noms à garder à l'esprit. 💡
+
+Le mot "**serveur**" est couramment utilisé pour désigner à la fois l'ordinateur distant/cloud (la machine physique ou virtuelle) et également le programme qui s'exécute sur cette machine (par exemple, Uvicorn).
+
+Gardez cela à l'esprit lorsque vous lisez "serveur" en général, cela pourrait faire référence à l'une de ces deux choses.
+
+Lorsqu'on se réfère à la machine distante, il est courant de l'appeler **serveur**, mais aussi **machine**, **VM** (machine virtuelle), **nœud**. Tout cela fait référence à un type de machine distante, exécutant Linux, en règle générale, sur laquelle vous exécutez des programmes.
+
+
+## Installer le programme serveur
+
+Vous pouvez installer un serveur compatible ASGI avec :
+
+=== "Uvicorn"
+
+ * Uvicorn, un serveur ASGI rapide comme l'éclair, basé sur uvloop et httptools.
+
+
+
+ !!! tip "Astuce"
+ En ajoutant `standard`, Uvicorn va installer et utiliser quelques dépendances supplémentaires recommandées.
+
+ Cela inclut `uvloop`, le remplaçant performant de `asyncio`, qui fournit le gros gain de performance en matière de concurrence.
+
+=== "Hypercorn"
+
+ * Hypercorn, un serveur ASGI également compatible avec HTTP/2.
+
+
+
+ ...ou tout autre serveur ASGI.
+
+## Exécutez le programme serveur
+
+Vous pouvez ensuite exécuter votre application de la même manière que vous l'avez fait dans les tutoriels, mais sans l'option `--reload`, par exemple :
+
+=== "Uvicorn"
+
+
+
+ ```console
+ $ hypercorn main:app --bind 0.0.0.0:80
+
+ Running on 0.0.0.0:8080 over http (CTRL + C to quit)
+ ```
+
+
+
+!!! warning
+ N'oubliez pas de supprimer l'option `--reload` si vous l'utilisiez.
+
+ L'option `--reload` consomme beaucoup plus de ressources, est plus instable, etc.
+
+ Cela aide beaucoup pendant le **développement**, mais vous **ne devriez pas** l'utiliser en **production**.
+
+## Hypercorn avec Trio
+
+Starlette et **FastAPI** sont basés sur
+AnyIO, qui les rend
+compatibles avec asyncio, de la bibliothèque standard Python et
+Trio.
+
+Néanmoins, Uvicorn n'est actuellement compatible qu'avec asyncio, et il utilise normalement `uvloop`, le remplaçant hautes performances de `asyncio`.
+
+Mais si vous souhaitez utiliser directement **Trio**, vous pouvez utiliser **Hypercorn** car il le prend en charge. ✨
+
+### Installer Hypercorn avec Trio
+
+Vous devez d'abord installer Hypercorn avec le support Trio :
+
+
+
+Et cela démarrera Hypercorn avec votre application en utilisant Trio comme backend.
+
+Vous pouvez désormais utiliser Trio en interne dans votre application. Ou mieux encore, vous pouvez utiliser AnyIO pour que votre code reste compatible avec Trio et asyncio. 🎉
+
+## Concepts de déploiement
+
+Ces exemples lancent le programme serveur (e.g. Uvicorn), démarrant **un seul processus**, sur toutes les IPs (`0.0.
+0.0`) sur un port prédéfini (par example, `80`).
+
+C'est l'idée de base. Mais vous vous préoccuperez probablement de certains concepts supplémentaires, tels que ... :
+
+* la sécurité - HTTPS
+* l'exécution au démarrage
+* les redémarrages
+* la réplication (le nombre de processus en cours d'exécution)
+* la mémoire
+* les étapes précédant le démarrage
+
+Je vous en dirai plus sur chacun de ces concepts, sur la façon de les aborder, et donnerai quelques exemples concrets avec des stratégies pour les traiter dans les prochains chapitres. 🚀
diff --git a/docs/fr/docs/index.md b/docs/fr/docs/index.md
index e7fb9947d..5ee8b462f 100644
--- a/docs/fr/docs/index.md
+++ b/docs/fr/docs/index.md
@@ -1,48 +1,46 @@
-
-{!../../../docs/missing-translation.md!}
-
-
- FastAPI framework, high performance, easy to learn, fast to code, ready for production
+ Framework FastAPI, haute performance, facile à apprendre, rapide à coder, prêt pour la production
---
-**Documentation**: https://fastapi.tiangolo.com
+**Documentation** : https://fastapi.tiangolo.com
-**Source Code**: https://github.com/tiangolo/fastapi
+**Code Source** : 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.
+FastAPI est un framework web moderne et rapide (haute performance) pour la création d'API avec Python 3.7+, basé sur les annotations de type standard de Python.
-The key features are:
+Les principales fonctionnalités sont :
-* **Fast**: Very high performance, on par with **NodeJS** and **Go** (thanks to Starlette and Pydantic). [One of the fastest Python frameworks available](#performance).
+* **Rapidité** : De très hautes performances, au niveau de **NodeJS** et **Go** (grâce à Starlette et Pydantic). [L'un des frameworks Python les plus rapides](#performance).
+* **Rapide à coder** : Augmente la vitesse de développement des fonctionnalités d'environ 200 % à 300 %. *
+* **Moins de bugs** : Réduit d'environ 40 % les erreurs induites par le développeur. *
+* **Intuitif** : Excellente compatibilité avec les IDE. Complétion complète. Moins de temps passé à déboguer.
+* **Facile** : Conçu pour être facile à utiliser et à apprendre. Moins de temps passé à lire la documentation.
+* **Concis** : Diminue la duplication de code. De nombreuses fonctionnalités liées à la déclaration de chaque paramètre. Moins de bugs.
+* **Robuste** : Obtenez un code prêt pour la production. Avec une documentation interactive automatique.
+* **Basé sur des normes** : Basé sur (et entièrement compatible avec) les standards ouverts pour les APIs : OpenAPI (précédemment connu sous le nom de Swagger) et JSON Schema.
-* **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.
+* estimation basée sur des tests d'une équipe de développement interne, construisant des applications de production.
## Sponsors
@@ -63,60 +61,66 @@ The key features are:
## 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._"
+"_[...] J'utilise beaucoup **FastAPI** ces derniers temps. [...] Je prévois de l'utiliser dans mon équipe pour tous les **services de ML chez Microsoft**. Certains d'entre eux seront intégrés dans le coeur de **Windows** et dans certains produits **Office**._"
---
-"_We adopted the **FastAPI** library to spawn a **REST** server that can be queried to obtain **predictions**. [for Ludwig]_"
+"_Nous avons adopté la bibliothèque **FastAPI** pour créer un serveur **REST** qui peut être interrogé pour obtenir des **prédictions**. [pour Ludwig]_"
-
Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala - Uber(ref)
+
Piero Molino, Yaroslav Dudin et 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** a le plaisir d'annoncer la sortie en open-source de notre framework d'orchestration de **gestion de crise** : **Dispatch** ! [construit avec **FastAPI**]_"
Kevin Glisson, Marc Vilanova, Forest Monsen - Netflix(ref)
---
-"_I’m over the moon excited about **FastAPI**. It’s so fun!_"
+"_Je suis très enthousiaste à propos de **FastAPI**. C'est un bonheur !_"
-
---
-"_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._"
+"_Honnêtement, ce que vous avez construit a l'air super solide et élégant. A bien des égards, c'est comme ça que je voulais que **Hug** soit - c'est vraiment inspirant de voir quelqu'un construire ça._"
-
---
-"_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 [...]_"
+"_Si vous cherchez à apprendre un **framework moderne** pour créer des APIs REST, regardez **FastAPI** [...] C'est rapide, facile à utiliser et à apprendre [...]_"
+
+"_Nous sommes passés à **FastAPI** pour nos **APIs** [...] Je pense que vous l'aimerez [...]_"
+
+
+
+---
-"_We've switched over to **FastAPI** for our **APIs** [...] I think you'll like it [...]_"
+"_Si quelqu'un cherche à construire une API Python de production, je recommande vivement **FastAPI**. Il est **bien conçu**, **simple à utiliser** et **très évolutif**. Il est devenu un **composant clé** dans notre stratégie de développement API first et il est à l'origine de nombreux automatismes et services tels que notre ingénieur virtuel TAC._"
-
---
-## **Typer**, the FastAPI of CLIs
+## **Typer**, le FastAPI des CLI
-If you are building a CLI app to be used in the terminal instead of a web API, check out **Typer**.
+Si vous souhaitez construire une application CLI utilisable dans un terminal au lieu d'une API web, regardez **Typer**.
-**Typer** is FastAPI's little sibling. And it's intended to be the **FastAPI of CLIs**. ⌨️ 🚀
+**Typer** est le petit frère de FastAPI. Et il est destiné à être le **FastAPI des CLI**. ⌨️ 🚀
-## Requirements
+## Prérequis
Python 3.7+
-FastAPI stands on the shoulders of giants:
+FastAPI repose sur les épaules de géants :
-* Starlette for the web parts.
-* Pydantic for the data parts.
+* Starlette pour les parties web.
+* Pydantic pour les parties données.
## Installation
@@ -130,7 +134,7 @@ $ pip install fastapi
-You will also need an ASGI server, for production such as Uvicorn or Hypercorn.
+Vous aurez également besoin d'un serveur ASGI pour la production tel que Uvicorn ou Hypercorn.
-## Example
+## Exemple
-### Create it
+### Créez
-* Create a file `main.py` with:
+* Créez un fichier `main.py` avec :
```Python
from typing import Union
@@ -167,11 +171,11 @@ def read_item(item_id: int, q: Union[str, None] = None):
```
-Or use async def...
+Ou utilisez async def ...
-If your code uses `async` / `await`, use `async def`:
+Si votre code utilise `async` / `await`, utilisez `async def` :
-```Python hl_lines="9 14"
+```Python hl_lines="9 14"
from typing import Union
from fastapi import FastAPI
@@ -189,15 +193,15 @@ async def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
```
-**Note**:
+**Note**
-If you don't know, check the _"In a hurry?"_ section about `async` and `await` in the docs.
+Si vous n'êtes pas familier avec cette notion, consultez la section _"Vous êtes pressés ?"_ à propos de `async` et `await` dans la documentation.
-### Run it
+### Lancez
-Run the server with:
+Lancez le serveur avec :
-About the command uvicorn main:app --reload...
+À propos de la commande uvicorn main:app --reload ...
-The command `uvicorn main:app` refers to:
+La commande `uvicorn main:app` fait référence à :
-* `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` : le fichier `main.py` (le "module" Python).
+* `app` : l'objet créé à l'intérieur de `main.py` avec la ligne `app = FastAPI()`.
+* `--reload` : fait redémarrer le serveur après des changements de code. À n'utiliser que pour le développement.
-### Check it
+### Vérifiez
-Open your browser at http://127.0.0.1:8000/items/5?q=somequery.
+Ouvrez votre navigateur à l'adresse http://127.0.0.1:8000/items/5?q=somequery.
-You will see the JSON response as:
+Vous obtenez alors cette réponse JSON :
```JSON
{"item_id": 5, "q": "somequery"}
```
-You already created an API that:
+Vous venez de créer une API qui :
-* 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`.
+* Reçoit les requêtes HTTP pour les _chemins_ `/` et `/items/{item_id}`.
+* Les deux _chemins_ acceptent des opérations `GET` (également connu sous le nom de _méthodes_ HTTP).
+* Le _chemin_ `/items/{item_id}` a un _paramètre_ `item_id` qui doit être un `int`.
+* Le _chemin_ `/items/{item_id}` a un _paramètre de requête_ optionnel `q` de type `str`.
-### Interactive API docs
+### Documentation API interactive
-Now go to http://127.0.0.1:8000/docs.
+Maintenant, rendez-vous sur http://127.0.0.1:8000/docs.
-You will see the automatic interactive API documentation (provided by Swagger UI):
+Vous verrez la documentation interactive automatique de l'API (fournie par Swagger UI) :

-### Alternative API docs
+### Documentation API alternative
-And now, go to http://127.0.0.1:8000/redoc.
+Et maintenant, rendez-vous sur http://127.0.0.1:8000/redoc.
-You will see the alternative automatic documentation (provided by ReDoc):
+Vous verrez la documentation interactive automatique de l'API (fournie par ReDoc) :

-## Example upgrade
+## Exemple plus poussé
-Now modify the file `main.py` to receive a body from a `PUT` request.
+Maintenant, modifiez le fichier `main.py` pour recevoir le corps d'une requête `PUT`.
-Declare the body using standard Python types, thanks to Pydantic.
+Déclarez ce corps en utilisant les types Python standards, grâce à Pydantic.
-```Python hl_lines="4 9 10 11 12 25 26 27"
+```Python hl_lines="4 9-12 25-27"
from typing import Union
from fastapi import FastAPI
@@ -293,174 +297,173 @@ 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).
+Le serveur se recharge normalement automatiquement (car vous avez pensé à `--reload` dans la commande `uvicorn` ci-dessus).
-### Interactive API docs upgrade
+### Plus loin avec la documentation API interactive
-Now go to http://127.0.0.1:8000/docs.
+Maintenant, rendez-vous sur http://127.0.0.1:8000/docs.
-* The interactive API documentation will be automatically updated, including the new body:
+* La documentation interactive de l'API sera automatiquement mise à jour, y compris le nouveau corps de la requête :

-* Click on the button "Try it out", it allows you to fill the parameters and directly interact with the API:
+* Cliquez sur le bouton "Try it out", il vous permet de renseigner les paramètres et d'interagir directement avec l'API :

-* 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:
+* Cliquez ensuite sur le bouton "Execute", l'interface utilisateur communiquera avec votre API, enverra les paramètres, obtiendra les résultats et les affichera à l'écran :

-### Alternative API docs upgrade
+### Plus loin avec la documentation API alternative
-And now, go to http://127.0.0.1:8000/redoc.
+Et maintenant, rendez-vous sur http://127.0.0.1:8000/redoc.
-* The alternative documentation will also reflect the new query parameter and body:
+* La documentation alternative reflétera également le nouveau paramètre de requête et le nouveau corps :

-### Recap
+### En résumé
-In summary, you declare **once** the types of parameters, body, etc. as function parameters.
+En résumé, vous déclarez **une fois** les types de paramètres, le corps de la requête, etc. en tant que paramètres de fonction.
-You do that with standard modern Python types.
+Vous faites cela avec les types Python standard modernes.
-You don't have to learn a new syntax, the methods or classes of a specific library, etc.
+Vous n'avez pas à apprendre une nouvelle syntaxe, les méthodes ou les classes d'une bibliothèque spécifique, etc.
-Just standard **Python 3.6+**.
+Juste du **Python 3.7+** standard.
-For example, for an `int`:
+Par exemple, pour un `int`:
```Python
item_id: int
```
-or for a more complex `Item` model:
+ou pour un modèle `Item` plus complexe :
```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:
+... et avec cette déclaration unique, vous obtenez :
+
+* Une assistance dans votre IDE, notamment :
+ * la complétion.
+ * la vérification des types.
+* La validation des données :
+ * des erreurs automatiques et claires lorsque les données ne sont pas valides.
+ * une validation même pour les objets JSON profondément imbriqués.
+* Une conversion des données d'entrée : venant du réseau et allant vers les données et types de Python, permettant de lire :
+ * le JSON.
+ * les paramètres du chemin.
+ * les paramètres de la requête.
+ * les cookies.
+ * les en-têtes.
+ * les formulaires.
+ * les fichiers.
+* La conversion des données de sortie : conversion des données et types Python en données réseau (au format JSON), permettant de convertir :
+ * les types Python (`str`, `int`, `float`, `bool`, `list`, etc).
+ * les objets `datetime`.
+ * les objets `UUID`.
+ * les modèles de base de données.
+ * ... et beaucoup plus.
+* La documentation API interactive automatique, avec 2 interfaces utilisateur au choix :
* 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.
+Pour revenir à l'exemple de code précédent, **FastAPI** permet de :
+
+* Valider que `item_id` existe dans le chemin des requêtes `GET` et `PUT`.
+* Valider que `item_id` est de type `int` pour les requêtes `GET` et `PUT`.
+ * Si ce n'est pas le cas, le client voit une erreur utile et claire.
+* Vérifier qu'il existe un paramètre de requête facultatif nommé `q` (comme dans `http://127.0.0.1:8000/items/foo?q=somequery`) pour les requêtes `GET`.
+ * Puisque le paramètre `q` est déclaré avec `= None`, il est facultatif.
+ * Sans le `None`, il serait nécessaire (comme l'est le corps de la requête dans le cas du `PUT`).
+* Pour les requêtes `PUT` vers `/items/{item_id}`, de lire le corps en JSON :
+ * Vérifier qu'il a un attribut obligatoire `name` qui devrait être un `str`.
+ * Vérifier qu'il a un attribut obligatoire `prix` qui doit être un `float`.
+ * Vérifier qu'il a un attribut facultatif `is_offer`, qui devrait être un `bool`, s'il est présent.
+ * Tout cela fonctionnerait également pour les objets JSON profondément imbriqués.
+* Convertir de et vers JSON automatiquement.
+* Documenter tout avec OpenAPI, qui peut être utilisé par :
+ * Les systèmes de documentation interactifs.
+ * Les systèmes de génération automatique de code client, pour de nombreuses langues.
+* Fournir directement 2 interfaces web de documentation interactive.
---
-We just scratched the surface, but you already get the idea of how it all works.
+Nous n'avons fait qu'effleurer la surface, mais vous avez déjà une idée de la façon dont tout cela fonctionne.
-Try changing the line with:
+Essayez de changer la ligne contenant :
```Python
return {"item_name": item.name, "item_id": item_id}
```
-...from:
+... de :
```Python
... "item_name": item.name ...
```
-...to:
+... vers :
```Python
... "item_price": item.price ...
```
-...and see how your editor will auto-complete the attributes and know their types:
+... et voyez comment votre éditeur complétera automatiquement les attributs et connaîtra leurs types :
-
+
-For a more complete example including more features, see the Tutorial - User Guide.
+Pour un exemple plus complet comprenant plus de fonctionnalités, voir le Tutoriel - Guide utilisateur.
-**Spoiler alert**: the tutorial - user guide includes:
+**Spoiler alert** : le tutoriel - guide utilisateur inclut :
-* 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).
-* Many extra features (thanks to Starlette) as:
+* Déclaration de **paramètres** provenant d'autres endroits différents comme : **en-têtes.**, **cookies**, **champs de formulaire** et **fichiers**.
+* L'utilisation de **contraintes de validation** comme `maximum_length` ou `regex`.
+* Un **systéme d'injection de dépendance ** très puissant et facile à utiliser .
+* Sécurité et authentification, y compris la prise en charge de **OAuth2** avec les **jetons JWT** et l'authentification **HTTP Basic**.
+* Des techniques plus avancées (mais tout aussi faciles) pour déclarer les **modèles JSON profondément imbriqués** (grâce à Pydantic).
+* Intégration de **GraphQL** avec Strawberry et d'autres bibliothèques.
+* D'obtenir de nombreuses fonctionnalités supplémentaires (grâce à Starlette) comme :
* **WebSockets**
- * **GraphQL**
- * extremely easy tests based on HTTPX and `pytest`
- * **CORS**
+ * de tester le code très facilement avec `requests` et `pytest`
+ * **CORS**
* **Cookie Sessions**
- * ...and more.
+ * ... et plus encore.
## 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). (*)
+Les benchmarks TechEmpower indépendants montrent que les applications **FastAPI** s'exécutant sous Uvicorn sont parmi les frameworks existants en Python les plus rapides , juste derrière Starlette et Uvicorn (utilisés en interne par FastAPI). (*)
-To understand more about it, see the section Benchmarks.
+Pour en savoir plus, consultez la section Benchmarks.
-## Optional Dependencies
+## Dépendances facultatives
-Used by Pydantic:
+Utilisées par Pydantic:
-* ujson - for faster JSON "parsing".
-* email_validator - for email validation.
+* ujson - pour un "décodage" JSON plus rapide.
+* email_validator - pour la validation des adresses email.
-Used by Starlette:
+Utilisées par Starlette :
-* HTTPX - Required if you want to use the `TestClient`.
-* jinja2 - Required if you want to use the default template configuration.
-* python-multipart - Required if you want to support form "parsing", with `request.form()`.
-* itsdangerous - Required for `SessionMiddleware` support.
-* pyyaml - Required for Starlette's `SchemaGenerator` support (you probably don't need it with FastAPI).
-* graphene - Required for `GraphQLApp` support.
-* ujson - Required if you want to use `UJSONResponse`.
+* requests - Obligatoire si vous souhaitez utiliser `TestClient`.
+* jinja2 - Obligatoire si vous souhaitez utiliser la configuration de template par defaut.
+* python-multipart - Obligatoire si vous souhaitez supporter le "décodage" de formulaire avec `request.form()`.
+* itsdangerous - Obligatoire pour la prise en charge de `SessionMiddleware`.
+* pyyaml - Obligatoire pour le support `SchemaGenerator` de Starlette (vous n'en avez probablement pas besoin avec FastAPI).
+* ujson - Obligatoire si vous souhaitez utiliser `UJSONResponse`.
-Used by FastAPI / Starlette:
+Utilisées par FastAPI / Starlette :
-* uvicorn - for the server that loads and serves your application.
-* orjson - Required if you want to use `ORJSONResponse`.
+* uvicorn - Pour le serveur qui charge et sert votre application.
+* orjson - Obligatoire si vous voulez utiliser `ORJSONResponse`.
-You can install all of these with `pip install fastapi[all]`.
+Vous pouvez tout installer avec `pip install fastapi[all]`.
-## License
+## Licence
-This project is licensed under the terms of the MIT license.
+Ce projet est soumis aux termes de la licence MIT.
diff --git a/docs/fr/docs/tutorial/debugging.md b/docs/fr/docs/tutorial/debugging.md
new file mode 100644
index 000000000..e58872d30
--- /dev/null
+++ b/docs/fr/docs/tutorial/debugging.md
@@ -0,0 +1,112 @@
+# Débogage
+
+Vous pouvez connecter le débogueur dans votre éditeur, par exemple avec Visual Studio Code ou PyCharm.
+
+## Faites appel à `uvicorn`
+
+Dans votre application FastAPI, importez et exécutez directement `uvicorn` :
+
+```Python hl_lines="1 15"
+{!../../../docs_src/debugging/tutorial001.py!}
+```
+
+### À propos de `__name__ == "__main__"`
+
+Le but principal de `__name__ == "__main__"` est d'avoir du code qui est exécuté lorsque votre fichier est appelé avec :
+
+
+
+```console
+$ python myapp.py
+```
+
+
+
+mais qui n'est pas appelé lorsqu'un autre fichier l'importe, comme dans :
+
+```Python
+from myapp import app
+```
+
+#### Pour davantage de détails
+
+Imaginons que votre fichier s'appelle `myapp.py`.
+
+Si vous l'exécutez avec :
+
+
+
+```console
+$ python myapp.py
+```
+
+
+
+alors la variable interne `__name__` de votre fichier, créée automatiquement par Python, aura pour valeur la chaîne de caractères `"__main__"`.
+
+Ainsi, la section :
+
+```Python
+ uvicorn.run(app, host="0.0.0.0", port=8000)
+```
+
+va s'exécuter.
+
+---
+
+Cela ne se produira pas si vous importez ce module (fichier).
+
+Par exemple, si vous avez un autre fichier `importer.py` qui contient :
+
+```Python
+from myapp import app
+
+# Code supplémentaire
+```
+
+dans ce cas, la variable automatique `__name__` à l'intérieur de `myapp.py` n'aura pas la valeur `"__main__"`.
+
+Ainsi, la ligne :
+
+```Python
+ uvicorn.run(app, host="0.0.0.0", port=8000)
+```
+
+ne sera pas exécutée.
+
+!!! info
+Pour plus d'informations, consultez la documentation officielle de Python.
+
+## Exécutez votre code avec votre débogueur
+
+Parce que vous exécutez le serveur Uvicorn directement depuis votre code, vous pouvez appeler votre programme Python (votre application FastAPI) directement depuis le débogueur.
+
+---
+
+Par exemple, dans Visual Studio Code, vous pouvez :
+
+- Cliquer sur l'onglet "Debug" de la barre d'activités de Visual Studio Code.
+- "Add configuration...".
+- Sélectionnez "Python".
+- Lancez le débogueur avec l'option "`Python: Current File (Integrated Terminal)`".
+
+Il démarrera alors le serveur avec votre code **FastAPI**, s'arrêtera à vos points d'arrêt, etc.
+
+Voici à quoi cela pourrait ressembler :
+
+
+
+---
+
+Si vous utilisez Pycharm, vous pouvez :
+
+- Ouvrir le menu "Run".
+- Sélectionnez l'option "Debug...".
+- Un menu contextuel s'affiche alors.
+- Sélectionnez le fichier à déboguer (dans ce cas, `main.py`).
+
+Il démarrera alors le serveur avec votre code **FastAPI**, s'arrêtera à vos points d'arrêt, etc.
+
+Voici à quoi cela pourrait ressembler :
+
+
diff --git a/docs/fr/mkdocs.yml b/docs/fr/mkdocs.yml
index 7dce4b127..854d14474 100644
--- a/docs/fr/mkdocs.yml
+++ b/docs/fr/mkdocs.yml
@@ -40,11 +40,14 @@ nav:
- Languages:
- en: /
- az: /az/
+ - cs: /cs/
- de: /de/
+ - em: /em/
- es: /es/
- fa: /fa/
- fr: /fr/
- he: /he/
+ - hy: /hy/
- id: /id/
- it: /it/
- ja: /ja/
@@ -55,6 +58,7 @@ nav:
- ru: /ru/
- sq: /sq/
- sv: /sv/
+ - ta: /ta/
- tr: /tr/
- uk: /uk/
- zh: /zh/
@@ -67,8 +71,12 @@ nav:
- tutorial/query-params.md
- tutorial/body.md
- tutorial/background-tasks.md
+ - tutorial/debugging.md
- Guide utilisateur avancé:
+ - advanced/index.md
+ - advanced/path-operation-advanced-configuration.md
- advanced/additional-status-codes.md
+ - advanced/response-directly.md
- advanced/additional-responses.md
- async.md
- Déploiement:
@@ -77,6 +85,7 @@ nav:
- deployment/https.md
- deployment/deta.md
- deployment/docker.md
+ - deployment/manually.md
- project-generation.md
- alternatives.md
- history-design-future.md
@@ -104,7 +113,7 @@ markdown_extensions:
extra:
analytics:
provider: google
- property: UA-133183413-1
+ property: G-YNEVN69SC3
social:
- icon: fontawesome/brands/github-alt
link: https://github.com/tiangolo/fastapi
@@ -125,8 +134,12 @@ extra:
name: en - English
- link: /az/
name: az
+ - link: /cs/
+ name: cs
- link: /de/
name: de
+ - link: /em/
+ name: 😉
- link: /es/
name: es - español
- link: /fa/
@@ -135,6 +148,8 @@ extra:
name: fr - français
- link: /he/
name: he
+ - link: /hy/
+ name: hy
- link: /id/
name: id
- link: /it/
@@ -155,6 +170,8 @@ extra:
name: sq - shqip
- link: /sv/
name: sv - svenska
+ - link: /ta/
+ name: ta - தமிழ்
- link: /tr/
name: tr - Türkçe
- link: /uk/
diff --git a/docs/he/mkdocs.yml b/docs/he/mkdocs.yml
index 3279099b5..acf7ea8fd 100644
--- a/docs/he/mkdocs.yml
+++ b/docs/he/mkdocs.yml
@@ -40,11 +40,14 @@ nav:
- Languages:
- en: /
- az: /az/
+ - cs: /cs/
- de: /de/
+ - em: /em/
- es: /es/
- fa: /fa/
- fr: /fr/
- he: /he/
+ - hy: /hy/
- id: /id/
- it: /it/
- ja: /ja/
@@ -55,6 +58,7 @@ nav:
- ru: /ru/
- sq: /sq/
- sv: /sv/
+ - ta: /ta/
- tr: /tr/
- uk: /uk/
- zh: /zh/
@@ -80,7 +84,7 @@ markdown_extensions:
extra:
analytics:
provider: google
- property: UA-133183413-1
+ property: G-YNEVN69SC3
social:
- icon: fontawesome/brands/github-alt
link: https://github.com/tiangolo/fastapi
@@ -101,8 +105,12 @@ extra:
name: en - English
- link: /az/
name: az
+ - link: /cs/
+ name: cs
- link: /de/
name: de
+ - link: /em/
+ name: 😉
- link: /es/
name: es - español
- link: /fa/
@@ -111,6 +119,8 @@ extra:
name: fr - français
- link: /he/
name: he
+ - link: /hy/
+ name: hy
- link: /id/
name: id
- link: /it/
@@ -131,6 +141,8 @@ extra:
name: sq - shqip
- link: /sv/
name: sv - svenska
+ - link: /ta/
+ name: ta - தமிழ்
- link: /tr/
name: tr - Türkçe
- link: /uk/
diff --git a/docs/hy/docs/index.md b/docs/hy/docs/index.md
new file mode 100644
index 000000000..cc82b33cf
--- /dev/null
+++ b/docs/hy/docs/index.md
@@ -0,0 +1,467 @@
+
+{!../../../docs/missing-translation.md!}
+
+
+
+
+
+
+ FastAPI framework, high performance, easy to learn, fast to code, ready for production
+
+
+---
+
+**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.7+ 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.7+
+
+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):
+
+
+
+### Alternative API docs
+
+And now, go to http://127.0.0.1:8000/redoc.
+
+You will see the alternative automatic documentation (provided by ReDoc):
+
+
+
+## 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:
+
+
+
+* Click on the button "Try it out", it allows you to fill the parameters and directly interact with the API:
+
+
+
+* 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:
+
+
+
+### 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:
+
+
+
+### 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.7+**.
+
+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:
+
+
+
+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 HTTPX 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:
+
+* httpx - Required if you want to use the `TestClient`.
+* jinja2 - Required if you want to use the default template configuration.
+* python-multipart - Required if you want to support form "parsing", with `request.form()`.
+* itsdangerous - Required for `SessionMiddleware` support.
+* pyyaml - Required for Starlette's `SchemaGenerator` support (you probably don't need it with FastAPI).
+* ujson - Required if you want to use `UJSONResponse`.
+
+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/hy/mkdocs.yml b/docs/hy/mkdocs.yml
new file mode 100644
index 000000000..5d251ff69
--- /dev/null
+++ b/docs/hy/mkdocs.yml
@@ -0,0 +1,157 @@
+site_name: FastAPI
+site_description: FastAPI framework, high performance, easy to learn, fast to code, ready for production
+site_url: https://fastapi.tiangolo.com/hy/
+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: hy
+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/
+ - cs: /cs/
+ - de: /de/
+ - em: /em/
+ - es: /es/
+ - fa: /fa/
+ - fr: /fr/
+ - he: /he/
+ - hy: /hy/
+ - id: /id/
+ - it: /it/
+ - ja: /ja/
+ - ko: /ko/
+ - nl: /nl/
+ - pl: /pl/
+ - pt: /pt/
+ - ru: /ru/
+ - sq: /sq/
+ - sv: /sv/
+ - ta: /ta/
+ - 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: G-YNEVN69SC3
+ 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: /cs/
+ name: cs
+ - link: /de/
+ name: de
+ - link: /em/
+ name: 😉
+ - link: /es/
+ name: es - español
+ - link: /fa/
+ name: fa
+ - link: /fr/
+ name: fr - français
+ - link: /he/
+ name: he
+ - link: /hy/
+ name: hy
+ - 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: /ta/
+ name: ta - தமிழ்
+ - 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/hy/overrides/.gitignore b/docs/hy/overrides/.gitignore
new file mode 100644
index 000000000..e69de29bb
diff --git a/docs/id/mkdocs.yml b/docs/id/mkdocs.yml
index abb31252f..55461328f 100644
--- a/docs/id/mkdocs.yml
+++ b/docs/id/mkdocs.yml
@@ -40,11 +40,14 @@ nav:
- Languages:
- en: /
- az: /az/
+ - cs: /cs/
- de: /de/
+ - em: /em/
- es: /es/
- fa: /fa/
- fr: /fr/
- he: /he/
+ - hy: /hy/
- id: /id/
- it: /it/
- ja: /ja/
@@ -55,6 +58,7 @@ nav:
- ru: /ru/
- sq: /sq/
- sv: /sv/
+ - ta: /ta/
- tr: /tr/
- uk: /uk/
- zh: /zh/
@@ -80,7 +84,7 @@ markdown_extensions:
extra:
analytics:
provider: google
- property: UA-133183413-1
+ property: G-YNEVN69SC3
social:
- icon: fontawesome/brands/github-alt
link: https://github.com/tiangolo/fastapi
@@ -101,8 +105,12 @@ extra:
name: en - English
- link: /az/
name: az
+ - link: /cs/
+ name: cs
- link: /de/
name: de
+ - link: /em/
+ name: 😉
- link: /es/
name: es - español
- link: /fa/
@@ -111,6 +119,8 @@ extra:
name: fr - français
- link: /he/
name: he
+ - link: /hy/
+ name: hy
- link: /id/
name: id
- link: /it/
@@ -131,6 +141,8 @@ extra:
name: sq - shqip
- link: /sv/
name: sv - svenska
+ - link: /ta/
+ name: ta - தமிழ்
- link: /tr/
name: tr - Türkçe
- link: /uk/
diff --git a/docs/it/mkdocs.yml b/docs/it/mkdocs.yml
index 532b5bc52..251d86681 100644
--- a/docs/it/mkdocs.yml
+++ b/docs/it/mkdocs.yml
@@ -40,11 +40,14 @@ nav:
- Languages:
- en: /
- az: /az/
+ - cs: /cs/
- de: /de/
+ - em: /em/
- es: /es/
- fa: /fa/
- fr: /fr/
- he: /he/
+ - hy: /hy/
- id: /id/
- it: /it/
- ja: /ja/
@@ -55,6 +58,7 @@ nav:
- ru: /ru/
- sq: /sq/
- sv: /sv/
+ - ta: /ta/
- tr: /tr/
- uk: /uk/
- zh: /zh/
@@ -80,7 +84,7 @@ markdown_extensions:
extra:
analytics:
provider: google
- property: UA-133183413-1
+ property: G-YNEVN69SC3
social:
- icon: fontawesome/brands/github-alt
link: https://github.com/tiangolo/fastapi
@@ -101,8 +105,12 @@ extra:
name: en - English
- link: /az/
name: az
+ - link: /cs/
+ name: cs
- link: /de/
name: de
+ - link: /em/
+ name: 😉
- link: /es/
name: es - español
- link: /fa/
@@ -111,6 +119,8 @@ extra:
name: fr - français
- link: /he/
name: he
+ - link: /hy/
+ name: hy
- link: /id/
name: id
- link: /it/
@@ -131,6 +141,8 @@ extra:
name: sq - shqip
- link: /sv/
name: sv - svenska
+ - link: /ta/
+ name: ta - தமிழ்
- link: /tr/
name: tr - Türkçe
- link: /uk/
diff --git a/docs/ja/docs/tutorial/testing.md b/docs/ja/docs/tutorial/testing.md
index 56f5cabac..037e9628f 100644
--- a/docs/ja/docs/tutorial/testing.md
+++ b/docs/ja/docs/tutorial/testing.md
@@ -74,16 +74,16 @@
これらの *path operation* には `X-Token` ヘッダーが必要です。
-=== "Python 3.6 and above"
+=== "Python 3.10+"
```Python
- {!> ../../../docs_src/app_testing/app_b/main.py!}
+ {!> ../../../docs_src/app_testing/app_b_py310/main.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
```Python
- {!> ../../../docs_src/app_testing/app_b_py310/main.py!}
+ {!> ../../../docs_src/app_testing/app_b/main.py!}
```
### 拡張版テストファイル
diff --git a/docs/ja/mkdocs.yml b/docs/ja/mkdocs.yml
index 5bbcce605..98a18cf4f 100644
--- a/docs/ja/mkdocs.yml
+++ b/docs/ja/mkdocs.yml
@@ -40,11 +40,14 @@ nav:
- Languages:
- en: /
- az: /az/
+ - cs: /cs/
- de: /de/
+ - em: /em/
- es: /es/
- fa: /fa/
- fr: /fr/
- he: /he/
+ - hy: /hy/
- id: /id/
- it: /it/
- ja: /ja/
@@ -55,6 +58,7 @@ nav:
- ru: /ru/
- sq: /sq/
- sv: /sv/
+ - ta: /ta/
- tr: /tr/
- uk: /uk/
- zh: /zh/
@@ -124,7 +128,7 @@ markdown_extensions:
extra:
analytics:
provider: google
- property: UA-133183413-1
+ property: G-YNEVN69SC3
social:
- icon: fontawesome/brands/github-alt
link: https://github.com/tiangolo/fastapi
@@ -145,8 +149,12 @@ extra:
name: en - English
- link: /az/
name: az
+ - link: /cs/
+ name: cs
- link: /de/
name: de
+ - link: /em/
+ name: 😉
- link: /es/
name: es - español
- link: /fa/
@@ -155,6 +163,8 @@ extra:
name: fr - français
- link: /he/
name: he
+ - link: /hy/
+ name: hy
- link: /id/
name: id
- link: /it/
@@ -175,6 +185,8 @@ extra:
name: sq - shqip
- link: /sv/
name: sv - svenska
+ - link: /ta/
+ name: ta - தமிழ்
- link: /tr/
name: tr - Türkçe
- link: /uk/
diff --git a/docs/ko/docs/tutorial/cors.md b/docs/ko/docs/tutorial/cors.md
new file mode 100644
index 000000000..39e9ea83f
--- /dev/null
+++ b/docs/ko/docs/tutorial/cors.md
@@ -0,0 +1,84 @@
+# 교차 출처 리소스 공유
+
+CORS 또는 "교차-출처 리소스 공유"란, 브라우저에서 동작하는 프론트엔드가 자바스크립트로 코드로 백엔드와 통신하고, 백엔드는 해당 프론트엔드와 다른 "출처"에 존재하는 상황을 의미합니다.
+
+## 출처
+
+출처란 프로토콜(`http` , `https`), 도메인(`myapp.com`, `localhost`, `localhost.tiangolo.com` ), 그리고 포트(`80`, `443`, `8080` )의 조합을 의미합니다.
+
+따라서, 아래는 모두 상이한 출처입니다:
+
+* `http://localhost`
+* `https://localhost`
+* `http://localhost:8080`
+
+모두 `localhost` 에 있지만, 서로 다른 프로토콜과 포트를 사용하고 있으므로 다른 "출처"입니다.
+
+## 단계
+
+브라우저 내 `http://localhost:8080`에서 동작하는 프론트엔드가 있고, 자바스크립트는 `http://localhost`를 통해 백엔드와 통신한다고 가정해봅시다(포트를 명시하지 않는 경우, 브라우저는 `80` 을 기본 포트로 간주합니다).
+
+그러면 브라우저는 백엔드에 HTTP `OPTIONS` 요청을 보내고, 백엔드에서 이 다른 출처(`http://localhost:8080`)와의 통신을 허가하는 적절한 헤더를 보내면, 브라우저는 프론트엔드의 자바스크립트가 백엔드에 요청을 보낼 수 있도록 합니다.
+
+이를 위해, 백엔드는 "허용된 출처(allowed origins)" 목록을 가지고 있어야만 합니다.
+
+이 경우, 프론트엔드가 제대로 동작하기 위해 `http://localhost:8080`을 목록에 포함해야 합니다.
+
+## 와일드카드
+
+모든 출처를 허용하기 위해 목록을 `"*"` ("와일드카드")로 선언하는 것도 가능합니다.
+
+하지만 이것은 특정한 유형의 통신만을 허용하며, 쿠키 및 액세스 토큰과 사용되는 인증 헤더(Authoriztion header) 등이 포함된 경우와 같이 자격 증명(credentials)이 포함된 통신은 허용되지 않습니다.
+
+따라서 모든 작업을 의도한대로 실행하기 위해, 허용되는 출처를 명시적으로 지정하는 것이 좋습니다.
+
+## `CORSMiddleware` 사용
+
+`CORSMiddleware` 을 사용하여 **FastAPI** 응용 프로그램의 교차 출처 리소스 공유 환경을 설정할 수 있습니다.
+
+* `CORSMiddleware` 임포트.
+* 허용되는 출처(문자열 형식)의 리스트 생성.
+* FastAPI 응용 프로그램에 "미들웨어(middleware)"로 추가.
+
+백엔드에서 다음의 사항을 허용할지에 대해 설정할 수도 있습니다:
+
+* 자격증명 (인증 헤더, 쿠키 등).
+* 특정한 HTTP 메소드(`POST`, `PUT`) 또는 와일드카드 `"*"` 를 사용한 모든 HTTP 메소드.
+* 특정한 HTTP 헤더 또는 와일드카드 `"*"` 를 사용한 모든 HTTP 헤더.
+
+```Python hl_lines="2 6-11 13-19"
+{!../../../docs_src/cors/tutorial001.py!}
+```
+
+`CORSMiddleware` 에서 사용하는 기본 매개변수는 제한적이므로, 브라우저가 교차-도메인 상황에서 특정한 출처, 메소드, 헤더 등을 사용할 수 있도록 하려면 이들을 명시적으로 허용해야 합니다.
+
+다음의 인자들이 지원됩니다:
+
+* `allow_origins` - 교차-출처 요청을 보낼 수 있는 출처의 리스트입니다. 예) `['https://example.org', 'https://www.example.org']`. 모든 출처를 허용하기 위해 `['*']` 를 사용할 수 있습니다.
+* `allow_origin_regex` - 교차-출처 요청을 보낼 수 있는 출처를 정규표현식 문자열로 나타냅니다. `'https://.*\.example\.org'`.
+* `allow_methods` - 교차-출처 요청을 허용하는 HTTP 메소드의 리스트입니다. 기본값은 `['GET']` 입니다. `['*']` 을 사용하여 모든 표준 메소드들을 허용할 수 있습니다.
+* `allow_headers` - 교차-출처를 지원하는 HTTP 요청 헤더의 리스트입니다. 기본값은 `[]` 입니다. 모든 헤더들을 허용하기 위해 `['*']` 를 사용할 수 있습니다. `Accept`, `Accept-Language`, `Content-Language` 그리고 `Content-Type` 헤더는 CORS 요청시 언제나 허용됩니다.
+* `allow_credentials` - 교차-출처 요청시 쿠키 지원 여부를 설정합니다. 기본값은 `False` 입니다. 또한 해당 항목을 허용할 경우 `allow_origins` 는 `['*']` 로 설정할 수 없으며, 출처를 반드시 특정해야 합니다.
+* `expose_headers` - 브라우저에 접근할 수 있어야 하는 모든 응답 헤더를 가리킵니다. 기본값은 `[]` 입니다.
+* `max_age` - 브라우저가 CORS 응답을 캐시에 저장하는 최대 시간을 초 단위로 설정합니다. 기본값은 `600` 입니다.
+
+미들웨어는 두가지 특정한 종류의 HTTP 요청에 응답합니다...
+
+### CORS 사전 요청
+
+`Origin` 및 `Access-Control-Request-Method` 헤더와 함께 전송하는 모든 `OPTIONS` 요청입니다.
+
+이 경우 미들웨어는 들어오는 요청을 가로채 적절한 CORS 헤더와, 정보 제공을 위한 `200` 또는 `400` 응답으로 응답합니다.
+
+### 단순한 요청
+
+`Origin` 헤더를 가진 모든 요청. 이 경우 미들웨어는 요청을 정상적으로 전달하지만, 적절한 CORS 헤더를 응답에 포함시킵니다.
+
+## 더 많은 정보
+
+CORS에 대한 더 많은 정보를 알고싶다면, Mozilla CORS 문서를 참고하기 바랍니다.
+
+!!! note "기술적 세부 사항"
+ `from starlette.middleware.cors import CORSMiddleware` 역시 사용할 수 있습니다.
+
+ **FastAPI**는 개발자인 당신의 편의를 위해 `fastapi.middleware` 에서 몇가지의 미들웨어를 제공합니다. 하지만 대부분의 미들웨어가 Stralette으로부터 직접 제공됩니다.
diff --git a/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md
new file mode 100644
index 000000000..bbf3a8283
--- /dev/null
+++ b/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md
@@ -0,0 +1,244 @@
+# 의존성으로서의 클래스
+
+**의존성 주입** 시스템에 대해 자세히 살펴보기 전에 이전 예제를 업그레이드 해보겠습니다.
+
+## 이전 예제의 `딕셔너리`
+
+이전 예제에서, 우리는 의존성(의존 가능한) 함수에서 `딕셔너리`객체를 반환하고 있었습니다:
+
+=== "파이썬 3.6 이상"
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/dependencies/tutorial001.py!}
+ ```
+
+=== "파이썬 3.10 이상"
+
+ ```Python hl_lines="7"
+ {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
+ ```
+
+우리는 *경로 작동 함수*의 매개변수 `commons`에서 `딕셔너리` 객체를 얻습니다.
+
+그리고 우리는 에디터들이 `딕셔너리` 객체의 키나 밸류의 자료형을 알 수 없기 때문에 자동 완성과 같은 기능을 제공해 줄 수 없다는 것을 알고 있습니다.
+
+더 나은 방법이 있을 것 같습니다...
+
+## 의존성으로 사용 가능한 것
+
+지금까지 함수로 선언된 의존성을 봐왔습니다.
+
+아마도 더 일반적이기는 하겠지만 의존성을 선언하는 유일한 방법은 아닙니다.
+
+핵심 요소는 의존성이 "호출 가능"해야 한다는 것입니다
+
+파이썬에서의 "**호출 가능**"은 파이썬이 함수처럼 "호출"할 수 있는 모든 것입니다.
+
+따라서, 만약 당신이 `something`(함수가 아닐 수도 있음) 객체를 가지고 있고,
+
+```Python
+something()
+```
+
+또는
+
+```Python
+something(some_argument, some_keyword_argument="foo")
+```
+
+상기와 같은 방식으로 "호출(실행)" 할 수 있다면 "호출 가능"이 됩니다.
+
+## 의존성으로서의 클래스
+
+파이썬 클래스의 인스턴스를 생성하기 위해 사용하는 것과 동일한 문법을 사용한다는 걸 알 수 있습니다.
+
+예를 들어:
+
+```Python
+class Cat:
+ def __init__(self, name: str):
+ self.name = name
+
+
+fluffy = Cat(name="Mr Fluffy")
+```
+
+이 경우에 `fluffy`는 클래스 `Cat`의 인스턴스입니다. 그리고 우리는 `fluffy`를 만들기 위해서 `Cat`을 "호출"했습니다.
+
+따라서, 파이썬 클래스는 **호출 가능**합니다.
+
+그래서 **FastAPI**에서는 파이썬 클래스를 의존성으로 사용할 수 있습니다.
+
+FastAPI가 실질적으로 확인하는 것은 "호출 가능성"(함수, 클래스 또는 다른 모든 것)과 정의된 매개변수들입니다.
+
+"호출 가능"한 것을 의존성으로서 **FastAPI**에 전달하면, 그 "호출 가능"한 것의 매개변수들을 분석한 후 이를 *경로 동작 함수*를 위한 매개변수와 동일한 방식으로 처리합니다. 하위-의존성 또한 같은 방식으로 처리합니다.
+
+매개변수가 없는 "호출 가능"한 것 역시 매개변수가 없는 *경로 동작 함수*와 동일한 방식으로 적용됩니다.
+
+그래서, 우리는 위 예제에서의 `common_paramenters` 의존성을 클래스 `CommonQueryParams`로 바꿀 수 있습니다.
+
+=== "파이썬 3.6 이상"
+
+ ```Python hl_lines="11-15"
+ {!> ../../../docs_src/dependencies/tutorial002.py!}
+ ```
+
+=== "파이썬 3.10 이상"
+
+ ```Python hl_lines="9-13"
+ {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
+ ```
+
+클래스의 인스턴스를 생성하는 데 사용되는 `__init__` 메서드에 주목하기 바랍니다:
+
+=== "파이썬 3.6 이상"
+
+ ```Python hl_lines="12"
+ {!> ../../../docs_src/dependencies/tutorial002.py!}
+ ```
+
+=== "파이썬 3.10 이상"
+
+ ```Python hl_lines="10"
+ {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
+ ```
+
+...이전 `common_parameters`와 동일한 매개변수를 가집니다:
+
+=== "파이썬 3.6 이상"
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/dependencies/tutorial001.py!}
+ ```
+
+=== "파이썬 3.10 이상"
+
+ ```Python hl_lines="6"
+ {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
+ ```
+
+이 매개변수들은 **FastAPI**가 의존성을 "해결"하기 위해 사용할 것입니다
+
+함수와 클래스 두 가지 방식 모두, 아래 요소를 갖습니다:
+
+* `문자열`이면서 선택사항인 쿼리 매개변수 `q`.
+* 기본값이 `0`이면서 `정수형`인 쿼리 매개변수 `skip`
+* 기본값이 `100`이면서 `정수형`인 쿼리 매개변수 `limit`
+
+두 가지 방식 모두, 데이터는 변환, 검증되고 OpenAPI 스키마에 문서화됩니다.
+
+## 사용해봅시다!
+
+이제 아래의 클래스를 이용해서 의존성을 정의할 수 있습니다.
+
+=== "파이썬 3.6 이상"
+
+ ```Python hl_lines="19"
+ {!> ../../../docs_src/dependencies/tutorial002.py!}
+ ```
+
+=== "파이썬 3.10 이상"
+
+ ```Python hl_lines="17"
+ {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
+ ```
+
+**FastAPI**는 `CommonQueryParams` 클래스를 호출합니다. 이것은 해당 클래스의 "인스턴스"를 생성하고 그 인스턴스는 함수의 매개변수 `commons`로 전달됩니다.
+
+## 타입 힌팅 vs `Depends`
+
+위 코드에서 `CommonQueryParams`를 두 번 작성한 방식에 주목하십시오:
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+마지막 `CommonQueryParams` 변수를 보면:
+
+```Python
+... = Depends(CommonQueryParams)
+```
+
+... **FastAPI**가 실제로 어떤 것이 의존성인지 알기 위해서 사용하는 방법입니다.
+FastAPI는 선언된 매개변수들을 추출할 것이고 실제로 이 변수들을 호출할 것입니다.
+
+---
+
+이 경우에, 첫번째 `CommonQueryParams` 변수를 보면:
+
+```Python
+commons: CommonQueryParams ...
+```
+
+... **FastAPI**는 `CommonQueryParams` 변수에 어떠한 특별한 의미도 부여하지 않습니다. FastAPI는 이 변수를 데이터 변환, 검증 등에 활용하지 않습니다. (활용하려면 `= Depends(CommonQueryParams)`를 사용해야 합니다.)
+
+사실 아래와 같이 작성해도 무관합니다:
+
+```Python
+commons = Depends(CommonQueryParams)
+```
+
+..전체적인 코드는 아래와 같습니다:
+
+=== "파이썬 3.6 이상"
+
+ ```Python hl_lines="19"
+ {!> ../../../docs_src/dependencies/tutorial003.py!}
+ ```
+
+=== "파이썬 3.10 이상"
+
+ ```Python hl_lines="17"
+ {!> ../../../docs_src/dependencies/tutorial003_py310.py!}
+ ```
+
+그러나 자료형을 선언하면 에디터가 매개변수 `commons`로 전달될 것이 무엇인지 알게 되고, 이를 통해 코드 완성, 자료형 확인 등에 도움이 될 수 있으므로 권장됩니다.
+
+
+
+## 코드 단축
+
+그러나 여기 `CommonQueryParams`를 두 번이나 작성하는, 코드 반복이 있다는 것을 알 수 있습니다:
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+**FastAPI**는 *특히* 의존성이 **FastAPI**가 클래스 자체의 인스턴스를 생성하기 위해 "호출"하는 클래스인 경우, 조금 더 쉬운 방법을 제공합니다.
+
+이러한 특정한 경우에는 아래처럼 사용할 수 있습니다:
+
+이렇게 쓰는 것 대신:
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+...이렇게 쓸 수 있습니다.:
+
+```Python
+commons: CommonQueryParams = Depends()
+```
+
+의존성을 매개변수의 타입으로 선언하는 경우 `Depends(CommonQueryParams)`처럼 클래스 이름 전체를 *다시* 작성하는 대신, 매개변수를 넣지 않은 `Depends()`의 형태로 사용할 수 있습니다.
+
+아래에 같은 예제가 있습니다:
+
+=== "파이썬 3.6 이상"
+
+ ```Python hl_lines="19"
+ {!> ../../../docs_src/dependencies/tutorial004.py!}
+ ```
+
+=== "파이썬 3.10 이상"
+
+ ```Python hl_lines="17"
+ {!> ../../../docs_src/dependencies/tutorial004_py310.py!}
+ ```
+
+...이렇게 코드를 단축하여도 **FastAPI**는 무엇을 해야하는지 알고 있습니다.
+
+!!! tip "팁"
+ 만약 이것이 도움이 되기보다 더 헷갈리게 만든다면, 잊어버리십시오. 이것이 반드시 필요한 것은 아닙니다.
+
+ 이것은 단지 손쉬운 방법일 뿐입니다. 왜냐하면 **FastAPI**는 코드 반복을 최소화할 수 있는 방법을 고민하기 때문입니다.
diff --git a/docs/ko/mkdocs.yml b/docs/ko/mkdocs.yml
index 50931e134..138ab678b 100644
--- a/docs/ko/mkdocs.yml
+++ b/docs/ko/mkdocs.yml
@@ -40,11 +40,14 @@ nav:
- Languages:
- en: /
- az: /az/
+ - cs: /cs/
- de: /de/
+ - em: /em/
- es: /es/
- fa: /fa/
- fr: /fr/
- he: /he/
+ - hy: /hy/
- id: /id/
- it: /it/
- ja: /ja/
@@ -55,6 +58,7 @@ nav:
- ru: /ru/
- sq: /sq/
- sv: /sv/
+ - ta: /ta/
- tr: /tr/
- uk: /uk/
- zh: /zh/
@@ -69,6 +73,9 @@ nav:
- tutorial/request-files.md
- tutorial/request-forms-and-files.md
- tutorial/encoder.md
+ - tutorial/cors.md
+ - 의존성:
+ - tutorial/dependencies/classes-as-dependencies.md
markdown_extensions:
- toc:
permalink: true
@@ -91,7 +98,7 @@ markdown_extensions:
extra:
analytics:
provider: google
- property: UA-133183413-1
+ property: G-YNEVN69SC3
social:
- icon: fontawesome/brands/github-alt
link: https://github.com/tiangolo/fastapi
@@ -112,8 +119,12 @@ extra:
name: en - English
- link: /az/
name: az
+ - link: /cs/
+ name: cs
- link: /de/
name: de
+ - link: /em/
+ name: 😉
- link: /es/
name: es - español
- link: /fa/
@@ -122,6 +133,8 @@ extra:
name: fr - français
- link: /he/
name: he
+ - link: /hy/
+ name: hy
- link: /id/
name: id
- link: /it/
@@ -142,6 +155,8 @@ extra:
name: sq - shqip
- link: /sv/
name: sv - svenska
+ - link: /ta/
+ name: ta - தமிழ்
- link: /tr/
name: tr - Türkçe
- link: /uk/
diff --git a/docs/nl/mkdocs.yml b/docs/nl/mkdocs.yml
index 6d46939f9..55c971aa4 100644
--- a/docs/nl/mkdocs.yml
+++ b/docs/nl/mkdocs.yml
@@ -40,11 +40,14 @@ nav:
- Languages:
- en: /
- az: /az/
+ - cs: /cs/
- de: /de/
+ - em: /em/
- es: /es/
- fa: /fa/
- fr: /fr/
- he: /he/
+ - hy: /hy/
- id: /id/
- it: /it/
- ja: /ja/
@@ -55,6 +58,7 @@ nav:
- ru: /ru/
- sq: /sq/
- sv: /sv/
+ - ta: /ta/
- tr: /tr/
- uk: /uk/
- zh: /zh/
@@ -80,7 +84,7 @@ markdown_extensions:
extra:
analytics:
provider: google
- property: UA-133183413-1
+ property: G-YNEVN69SC3
social:
- icon: fontawesome/brands/github-alt
link: https://github.com/tiangolo/fastapi
@@ -101,8 +105,12 @@ extra:
name: en - English
- link: /az/
name: az
+ - link: /cs/
+ name: cs
- link: /de/
name: de
+ - link: /em/
+ name: 😉
- link: /es/
name: es - español
- link: /fa/
@@ -111,6 +119,8 @@ extra:
name: fr - français
- link: /he/
name: he
+ - link: /hy/
+ name: hy
- link: /id/
name: id
- link: /it/
@@ -131,6 +141,8 @@ extra:
name: sq - shqip
- link: /sv/
name: sv - svenska
+ - link: /ta/
+ name: ta - தமிழ்
- link: /tr/
name: tr - Türkçe
- link: /uk/
diff --git a/docs/pl/mkdocs.yml b/docs/pl/mkdocs.yml
index 1cd129420..af68f1b74 100644
--- a/docs/pl/mkdocs.yml
+++ b/docs/pl/mkdocs.yml
@@ -40,11 +40,14 @@ nav:
- Languages:
- en: /
- az: /az/
+ - cs: /cs/
- de: /de/
+ - em: /em/
- es: /es/
- fa: /fa/
- fr: /fr/
- he: /he/
+ - hy: /hy/
- id: /id/
- it: /it/
- ja: /ja/
@@ -55,6 +58,7 @@ nav:
- ru: /ru/
- sq: /sq/
- sv: /sv/
+ - ta: /ta/
- tr: /tr/
- uk: /uk/
- zh: /zh/
@@ -83,7 +87,7 @@ markdown_extensions:
extra:
analytics:
provider: google
- property: UA-133183413-1
+ property: G-YNEVN69SC3
social:
- icon: fontawesome/brands/github-alt
link: https://github.com/tiangolo/fastapi
@@ -104,8 +108,12 @@ extra:
name: en - English
- link: /az/
name: az
+ - link: /cs/
+ name: cs
- link: /de/
name: de
+ - link: /em/
+ name: 😉
- link: /es/
name: es - español
- link: /fa/
@@ -114,6 +122,8 @@ extra:
name: fr - français
- link: /he/
name: he
+ - link: /hy/
+ name: hy
- link: /id/
name: id
- link: /it/
@@ -134,6 +144,8 @@ extra:
name: sq - shqip
- link: /sv/
name: sv - svenska
+ - link: /ta/
+ name: ta - தமிழ்
- link: /tr/
name: tr - Türkçe
- link: /uk/
diff --git a/docs/pt/docs/index.md b/docs/pt/docs/index.md
index afc101ede..76668b4da 100644
--- a/docs/pt/docs/index.md
+++ b/docs/pt/docs/index.md
@@ -292,7 +292,7 @@ Agora vá para ../../../docs_src/body_multiple_params/tutorial001.py!}
+ ```Python hl_lines="17-19"
+ {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!}
```
-=== "Python 3.10 e superiores"
+=== "Python 3.6+"
- ```Python hl_lines="17-19"
- {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!}
+ ```Python hl_lines="19-21"
+ {!> ../../../docs_src/body_multiple_params/tutorial001.py!}
```
!!! nota
@@ -38,16 +38,16 @@ No exemplo anterior, as *operações de rota* esperariam um JSON no corpo conten
Mas você pode também declarar múltiplos parâmetros de corpo, por exemplo, `item` e `user`:
-=== "Python 3.6 e superiores"
+=== "Python 3.10+"
- ```Python hl_lines="22"
- {!> ../../../docs_src/body_multiple_params/tutorial002.py!}
+ ```Python hl_lines="20"
+ {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!}
```
-=== "Python 3.10 e superiores"
+=== "Python 3.6+"
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!}
+ ```Python hl_lines="22"
+ {!> ../../../docs_src/body_multiple_params/tutorial002.py!}
```
Neste caso, o **FastAPI** perceberá que existe mais de um parâmetro de corpo na função (dois parâmetros que são modelos Pydantic).
@@ -87,13 +87,13 @@ Se você declará-lo como é, porque é um valor singular, o **FastAPI** assumir
Mas você pode instruir o **FastAPI** para tratá-lo como outra chave do corpo usando `Body`:
-=== "Python 3.6 e superiores"
+=== "Python 3.6+"
```Python hl_lines="22"
{!> ../../../docs_src/body_multiple_params/tutorial003.py!}
```
-=== "Python 3.10 e superiores"
+=== "Python 3.10+"
```Python hl_lines="20"
{!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!}
@@ -137,16 +137,16 @@ q: str | None = None
Por exemplo:
-=== "Python 3.6 e superiores"
+=== "Python 3.10+"
- ```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004.py!}
+ ```Python hl_lines="26"
+ {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!}
```
-=== "Python 3.10 e superiores"
+=== "Python 3.6+"
- ```Python hl_lines="26"
- {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!}
+ ```Python hl_lines="27"
+ {!> ../../../docs_src/body_multiple_params/tutorial004.py!}
```
!!! info "Informação"
@@ -166,16 +166,16 @@ item: Item = Body(embed=True)
como em:
-=== "Python 3.6 e superiores"
+=== "Python 3.10+"
- ```Python hl_lines="17"
- {!> ../../../docs_src/body_multiple_params/tutorial005.py!}
+ ```Python hl_lines="15"
+ {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!}
```
-=== "Python 3.10 e superiores"
+=== "Python 3.6+"
- ```Python hl_lines="15"
- {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!}
+ ```Python hl_lines="17"
+ {!> ../../../docs_src/body_multiple_params/tutorial005.py!}
```
Neste caso o **FastAPI** esperará um corpo como:
diff --git a/docs/pt/docs/tutorial/body-nested-models.md b/docs/pt/docs/tutorial/body-nested-models.md
new file mode 100644
index 000000000..8ab77173e
--- /dev/null
+++ b/docs/pt/docs/tutorial/body-nested-models.md
@@ -0,0 +1,248 @@
+# Corpo - Modelos aninhados
+
+Com o **FastAPI**, você pode definir, validar, documentar e usar modelos profundamente aninhados de forma arbitrária (graças ao Pydantic).
+
+## Campos do tipo Lista
+
+Você pode definir um atributo como um subtipo. Por exemplo, uma `list` do Python:
+
+```Python hl_lines="14"
+{!../../../docs_src/body_nested_models/tutorial001.py!}
+```
+
+Isso fará com que tags seja uma lista de itens mesmo sem declarar o tipo dos elementos desta lista.
+
+## Campos do tipo Lista com um parâmetro de tipo
+
+Mas o Python tem uma maneira específica de declarar listas com tipos internos ou "parâmetros de tipo":
+
+### Importe `List` do typing
+
+Primeiramente, importe `List` do módulo `typing` que já vem por padrão no Python:
+
+```Python hl_lines="1"
+{!../../../docs_src/body_nested_models/tutorial002.py!}
+```
+
+### Declare a `List` com um parâmetro de tipo
+
+Para declarar tipos que têm parâmetros de tipo(tipos internos), como `list`, `dict`, `tuple`:
+
+* Importe os do modulo `typing`
+* Passe o(s) tipo(s) interno(s) como "parâmetros de tipo" usando colchetes: `[` e `]`
+
+```Python
+from typing import List
+
+my_list: List[str]
+```
+
+Essa é a sintaxe padrão do Python para declarações de tipo.
+
+Use a mesma sintaxe padrão para atributos de modelo com tipos internos.
+
+Portanto, em nosso exemplo, podemos fazer com que `tags` sejam especificamente uma "lista de strings":
+
+
+```Python hl_lines="14"
+{!../../../docs_src/body_nested_models/tutorial002.py!}
+```
+
+## Tipo "set"
+
+
+Mas então, quando nós pensamos mais, percebemos que as tags não devem se repetir, elas provavelmente devem ser strings únicas.
+
+E que o Python tem um tipo de dados especial para conjuntos de itens únicos, o `set`.
+
+Então podemos importar `Set` e declarar `tags` como um `set` de `str`s:
+
+
+```Python hl_lines="1 14"
+{!../../../docs_src/body_nested_models/tutorial003.py!}
+```
+
+Com isso, mesmo que você receba uma requisição contendo dados duplicados, ela será convertida em um conjunto de itens exclusivos.
+
+E sempre que você enviar esses dados como resposta, mesmo se a fonte tiver duplicatas, eles serão gerados como um conjunto de itens exclusivos.
+
+E também teremos anotações/documentação em conformidade.
+
+## Modelos aninhados
+
+Cada atributo de um modelo Pydantic tem um tipo.
+
+Mas esse tipo pode ser outro modelo Pydantic.
+
+Portanto, você pode declarar "objects" JSON profundamente aninhados com nomes, tipos e validações de atributos específicos.
+
+Tudo isso, aninhado arbitrariamente.
+
+### Defina um sub-modelo
+
+Por exemplo, nós podemos definir um modelo `Image`:
+
+```Python hl_lines="9-11"
+{!../../../docs_src/body_nested_models/tutorial004.py!}
+```
+
+### Use o sub-modelo como um tipo
+
+E então podemos usa-lo como o tipo de um atributo:
+
+```Python hl_lines="20"
+{!../../../docs_src/body_nested_models/tutorial004.py!}
+```
+
+Isso significa que o **FastAPI** vai esperar um corpo similar à:
+
+```JSON
+{
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2,
+ "tags": ["rock", "metal", "bar"],
+ "image": {
+ "url": "http://example.com/baz.jpg",
+ "name": "The Foo live"
+ }
+}
+```
+
+Novamente, apenas fazendo essa declaração, com o **FastAPI**, você ganha:
+
+* Suporte do editor de texto (compleção, etc), inclusive para modelos aninhados
+* Conversão de dados
+* Validação de dados
+* Documentação automatica
+
+## Tipos especiais e validação
+
+Além dos tipos singulares normais como `str`, `int`, `float`, etc. Você também pode usar tipos singulares mais complexos que herdam de `str`.
+
+Para ver todas as opções possíveis, cheque a documentação para ostipos exoticos do Pydantic. Você verá alguns exemplos no próximo capitulo.
+
+Por exemplo, no modelo `Image` nós temos um campo `url`, nós podemos declara-lo como um `HttpUrl` do Pydantic invés de como uma `str`:
+
+```Python hl_lines="4 10"
+{!../../../docs_src/body_nested_models/tutorial005.py!}
+```
+
+A string será verificada para se tornar uma URL válida e documentada no esquema JSON/1OpenAPI como tal.
+
+## Atributos como listas de submodelos
+
+Você também pode usar modelos Pydantic como subtipos de `list`, `set`, etc:
+
+```Python hl_lines="20"
+{!../../../docs_src/body_nested_models/tutorial006.py!}
+```
+
+Isso vai esperar(converter, validar, documentar, etc) um corpo JSON tal qual:
+
+```JSON hl_lines="11"
+{
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2,
+ "tags": [
+ "rock",
+ "metal",
+ "bar"
+ ],
+ "images": [
+ {
+ "url": "http://example.com/baz.jpg",
+ "name": "The Foo live"
+ },
+ {
+ "url": "http://example.com/dave.jpg",
+ "name": "The Baz"
+ }
+ ]
+}
+```
+
+!!! Informação
+ Note como o campo `images` agora tem uma lista de objetos de image.
+
+## Modelos profundamente aninhados
+
+Você pode definir modelos profundamente aninhados de forma arbitrária:
+
+```Python hl_lines="9 14 20 23 27"
+{!../../../docs_src/body_nested_models/tutorial007.py!}
+```
+
+!!! Informação
+ Note como `Offer` tem uma lista de `Item`s, que por sua vez possui opcionalmente uma lista `Image`s
+
+## Corpos de listas puras
+
+Se o valor de primeiro nível do corpo JSON que você espera for um `array` do JSON (uma` lista` do Python), você pode declarar o tipo no parâmetro da função, da mesma forma que nos modelos do Pydantic:
+
+
+```Python
+images: List[Image]
+```
+
+como em:
+
+```Python hl_lines="15"
+{!../../../docs_src/body_nested_models/tutorial008.py!}
+```
+
+## Suporte de editor em todo canto
+
+E você obtém suporte do editor em todos os lugares.
+
+Mesmo para itens dentro de listas:
+
+
+
+Você não conseguiria este tipo de suporte de editor se estivesse trabalhando diretamente com `dict` em vez de modelos Pydantic.
+
+Mas você também não precisa se preocupar com eles, os dicts de entrada são convertidos automaticamente e sua saída é convertida automaticamente para JSON também.
+
+## Corpos de `dict`s arbitrários
+
+Você também pode declarar um corpo como um `dict` com chaves de algum tipo e valores de outro tipo.
+
+Sem ter que saber de antemão quais são os nomes de campos/atributos válidos (como seria o caso dos modelos Pydantic).
+
+Isso seria útil se você deseja receber chaves que ainda não conhece.
+
+---
+
+Outro caso útil é quando você deseja ter chaves de outro tipo, por exemplo, `int`.
+
+É isso que vamos ver aqui.
+
+Neste caso, você aceitaria qualquer `dict`, desde que tenha chaves` int` com valores `float`:
+
+```Python hl_lines="9"
+{!../../../docs_src/body_nested_models/tutorial009.py!}
+```
+
+!!! Dica
+ Leve em condideração que o JSON só suporta `str` como chaves.
+
+ Mas o Pydantic tem conversão automática de dados.
+
+ Isso significa que, embora os clientes da API só possam enviar strings como chaves, desde que essas strings contenham inteiros puros, o Pydantic irá convertê-los e validá-los.
+
+ E o `dict` que você recebe como `weights` terá, na verdade, chaves `int` e valores` float`.
+
+## Recapitulação
+
+Com **FastAPI** você tem a flexibilidade máxima fornecida pelos modelos Pydantic, enquanto seu código é mantido simples, curto e elegante.
+
+Mas com todos os benefícios:
+
+* Suporte do editor (compleção em todo canto!)
+* Conversão de dados (leia-se parsing/serialização)
+* Validação de dados
+* Documentação dos esquemas
+* Documentação automática
diff --git a/docs/pt/docs/tutorial/encoder.md b/docs/pt/docs/tutorial/encoder.md
new file mode 100644
index 000000000..bb4483fdc
--- /dev/null
+++ b/docs/pt/docs/tutorial/encoder.md
@@ -0,0 +1,42 @@
+# Codificador Compatível com JSON
+
+Existem alguns casos em que você pode precisar converter um tipo de dados (como um modelo Pydantic) para algo compatível com JSON (como um `dict`, `list`, etc).
+
+Por exemplo, se você precisar armazená-lo em um banco de dados.
+
+Para isso, **FastAPI** fornece uma função `jsonable_encoder()`.
+
+## Usando a função `jsonable_encoder`
+
+Vamos imaginar que você tenha um banco de dados `fake_db` que recebe apenas dados compatíveis com JSON.
+
+Por exemplo, ele não recebe objetos `datetime`, pois estes objetos não são compatíveis com JSON.
+
+Então, um objeto `datetime` teria que ser convertido em um `str` contendo os dados no formato ISO.
+
+Da mesma forma, este banco de dados não receberia um modelo Pydantic (um objeto com atributos), apenas um `dict`.
+
+Você pode usar a função `jsonable_encoder` para resolver isso.
+
+A função recebe um objeto, como um modelo Pydantic e retorna uma versão compatível com JSON:
+
+=== "Python 3.10+"
+
+ ```Python hl_lines="4 21"
+ {!> ../../../docs_src/encoder/tutorial001_py310.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="5 22"
+ {!> ../../../docs_src/encoder/tutorial001.py!}
+ ```
+
+Neste exemplo, ele converteria o modelo Pydantic em um `dict`, e o `datetime` em um `str`.
+
+O resultado de chamar a função é algo que pode ser codificado com o padrão do Python `json.dumps()`.
+
+A função não retorna um grande `str` contendo os dados no formato JSON (como uma string). Mas sim, retorna uma estrutura de dados padrão do Python (por exemplo, um `dict`) com valores e subvalores compatíveis com JSON.
+
+!!! nota
+ `jsonable_encoder` é realmente usado pelo **FastAPI** internamente para converter dados. Mas também é útil em muitos outros cenários.
diff --git a/docs/pt/docs/tutorial/extra-models.md b/docs/pt/docs/tutorial/extra-models.md
new file mode 100644
index 000000000..dd5407eb2
--- /dev/null
+++ b/docs/pt/docs/tutorial/extra-models.md
@@ -0,0 +1,252 @@
+# Modelos Adicionais
+
+Continuando com o exemplo anterior, será comum ter mais de um modelo relacionado.
+
+Isso é especialmente o caso para modelos de usuários, porque:
+
+* O **modelo de entrada** precisa ser capaz de ter uma senha.
+* O **modelo de saída** não deve ter uma senha.
+* O **modelo de banco de dados** provavelmente precisaria ter uma senha criptografada.
+
+!!! danger
+ Nunca armazene senhas em texto simples dos usuários. Sempre armazene uma "hash segura" que você pode verificar depois.
+
+ Se não souber, você aprenderá o que é uma "senha hash" nos [capítulos de segurança](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}.
+
+## Múltiplos modelos
+
+Aqui está uma ideia geral de como os modelos poderiam parecer com seus campos de senha e os lugares onde são usados:
+
+=== "Python 3.6 and above"
+
+ ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41"
+ {!> ../../../docs_src/extra_models/tutorial001.py!}
+ ```
+
+=== "Python 3.10 and above"
+
+ ```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39"
+ {!> ../../../docs_src/extra_models/tutorial001_py310.py!}
+ ```
+
+### Sobre `**user_in.dict()`
+
+#### O `.dict()` do Pydantic
+
+`user_in` é um modelo Pydantic da classe `UserIn`.
+
+Os modelos Pydantic possuem um método `.dict()` que retorna um `dict` com os dados do modelo.
+
+Então, se criarmos um objeto Pydantic `user_in` como:
+
+```Python
+user_in = UserIn(username="john", password="secret", email="john.doe@example.com")
+```
+
+e depois chamarmos:
+
+```Python
+user_dict = user_in.dict()
+```
+
+agora temos um `dict` com os dados na variável `user_dict` (é um `dict` em vez de um objeto de modelo Pydantic).
+
+E se chamarmos:
+
+```Python
+print(user_dict)
+```
+
+teríamos um `dict` Python com:
+
+```Python
+{
+ 'username': 'john',
+ 'password': 'secret',
+ 'email': 'john.doe@example.com',
+ 'full_name': None,
+}
+```
+
+#### Desembrulhando um `dict`
+
+Se tomarmos um `dict` como `user_dict` e passarmos para uma função (ou classe) com `**user_dict`, o Python irá "desembrulhá-lo". Ele passará as chaves e valores do `user_dict` diretamente como argumentos chave-valor.
+
+Então, continuando com o `user_dict` acima, escrevendo:
+
+```Python
+UserInDB(**user_dict)
+```
+
+Resultaria em algo equivalente a:
+
+```Python
+UserInDB(
+ username="john",
+ password="secret",
+ email="john.doe@example.com",
+ full_name=None,
+)
+```
+
+Ou mais exatamente, usando `user_dict` diretamente, com qualquer conteúdo que ele possa ter no futuro:
+
+```Python
+UserInDB(
+ username = user_dict["username"],
+ password = user_dict["password"],
+ email = user_dict["email"],
+ full_name = user_dict["full_name"],
+)
+```
+
+#### Um modelo Pydantic a partir do conteúdo de outro
+
+Como no exemplo acima, obtivemos o `user_dict` a partir do `user_in.dict()`, este código:
+
+```Python
+user_dict = user_in.dict()
+UserInDB(**user_dict)
+```
+
+seria equivalente a:
+
+```Python
+UserInDB(**user_in.dict())
+```
+
+...porque `user_in.dict()` é um `dict`, e depois fazemos o Python "desembrulhá-lo" passando-o para UserInDB precedido por `**`.
+
+Então, obtemos um modelo Pydantic a partir dos dados em outro modelo Pydantic.
+
+#### Desembrulhando um `dict` e palavras-chave extras
+
+E, então, adicionando o argumento de palavra-chave extra `hashed_password=hashed_password`, como em:
+
+```Python
+UserInDB(**user_in.dict(), hashed_password=hashed_password)
+```
+
+...acaba sendo como:
+
+```Python
+UserInDB(
+ username = user_dict["username"],
+ password = user_dict["password"],
+ email = user_dict["email"],
+ full_name = user_dict["full_name"],
+ hashed_password = hashed_password,
+)
+```
+
+!!! warning
+ As funções adicionais de suporte são apenas para demonstração de um fluxo possível dos dados, mas é claro que elas não fornecem segurança real.
+
+## Reduzir duplicação
+
+Reduzir a duplicação de código é uma das ideias principais no **FastAPI**.
+
+A duplicação de código aumenta as chances de bugs, problemas de segurança, problemas de desincronização de código (quando você atualiza em um lugar, mas não em outros), etc.
+
+E esses modelos estão compartilhando muitos dos dados e duplicando nomes e tipos de atributos.
+
+Nós poderíamos fazer melhor.
+
+Podemos declarar um modelo `UserBase` que serve como base para nossos outros modelos. E então podemos fazer subclasses desse modelo que herdam seus atributos (declarações de tipo, validação, etc.).
+
+Toda conversão de dados, validação, documentação, etc. ainda funcionará normalmente.
+
+Dessa forma, podemos declarar apenas as diferenças entre os modelos (com `password` em texto claro, com `hashed_password` e sem senha):
+
+=== "Python 3.6 and above"
+
+ ```Python hl_lines="9 15-16 19-20 23-24"
+ {!> ../../../docs_src/extra_models/tutorial002.py!}
+ ```
+
+=== "Python 3.10 and above"
+
+ ```Python hl_lines="7 13-14 17-18 21-22"
+ {!> ../../../docs_src/extra_models/tutorial002_py310.py!}
+ ```
+
+## `Union` ou `anyOf`
+
+Você pode declarar uma resposta como o `Union` de dois tipos, o que significa que a resposta seria qualquer um dos dois.
+
+Isso será definido no OpenAPI com `anyOf`.
+
+Para fazer isso, use a dica de tipo padrão do Python `typing.Union`:
+
+!!! note
+ Ao definir um `Union`, inclua o tipo mais específico primeiro, seguido pelo tipo menos específico. No exemplo abaixo, o tipo mais específico `PlaneItem` vem antes de `CarItem` em `Union[PlaneItem, CarItem]`.
+
+=== "Python 3.6 and above"
+
+ ```Python hl_lines="1 14-15 18-20 33"
+ {!> ../../../docs_src/extra_models/tutorial003.py!}
+ ```
+
+=== "Python 3.10 and above"
+
+ ```Python hl_lines="1 14-15 18-20 33"
+ {!> ../../../docs_src/extra_models/tutorial003_py310.py!}
+ ```
+
+### `Union` no Python 3.10
+
+Neste exemplo, passamos `Union[PlaneItem, CarItem]` como o valor do argumento `response_model`.
+
+Dado que estamos passando-o como um **valor para um argumento** em vez de colocá-lo em uma **anotação de tipo**, precisamos usar `Union` mesmo no Python 3.10.
+
+Se estivesse em uma anotação de tipo, poderíamos ter usado a barra vertical, como:
+
+```Python
+some_variable: PlaneItem | CarItem
+```
+
+Mas se colocarmos isso em `response_model=PlaneItem | CarItem` teríamos um erro, pois o Python tentaria executar uma **operação inválida** entre `PlaneItem` e `CarItem` em vez de interpretar isso como uma anotação de tipo.
+
+## Lista de modelos
+
+Da mesma forma, você pode declarar respostas de listas de objetos.
+
+Para isso, use o padrão Python `typing.List` (ou simplesmente `list` no Python 3.9 e superior):
+
+=== "Python 3.6 and above"
+
+ ```Python hl_lines="1 20"
+ {!> ../../../docs_src/extra_models/tutorial004.py!}
+ ```
+
+=== "Python 3.9 and above"
+
+ ```Python hl_lines="18"
+ {!> ../../../docs_src/extra_models/tutorial004_py39.py!}
+ ```
+
+## Resposta com `dict` arbitrário
+
+Você também pode declarar uma resposta usando um simples `dict` arbitrário, declarando apenas o tipo das chaves e valores, sem usar um modelo Pydantic.
+
+Isso é útil se você não souber os nomes de campo / atributo válidos (que seriam necessários para um modelo Pydantic) antecipadamente.
+
+Neste caso, você pode usar `typing.Dict` (ou simplesmente dict no Python 3.9 e superior):
+
+=== "Python 3.6 and above"
+
+ ```Python hl_lines="1 8"
+ {!> ../../../docs_src/extra_models/tutorial005.py!}
+ ```
+
+=== "Python 3.9 and above"
+
+ ```Python hl_lines="6"
+ {!> ../../../docs_src/extra_models/tutorial005_py39.py!}
+ ```
+
+## Em resumo
+
+Use vários modelos Pydantic e herde livremente para cada caso.
+
+Não é necessário ter um único modelo de dados por entidade se essa entidade precisar ter diferentes "estados". No caso da "entidade" de usuário com um estado que inclui `password`, `password_hash` e sem senha.
diff --git a/docs/pt/docs/tutorial/header-params.md b/docs/pt/docs/tutorial/header-params.md
index 94ee784cd..bc8843327 100644
--- a/docs/pt/docs/tutorial/header-params.md
+++ b/docs/pt/docs/tutorial/header-params.md
@@ -6,16 +6,16 @@ Você pode definir parâmetros de Cabeçalho da mesma maneira que define paramê
Primeiro importe `Header`:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="3"
- {!> ../../../docs_src/header_params/tutorial001.py!}
+ ```Python hl_lines="1"
+ {!> ../../../docs_src/header_params/tutorial001_py310.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="1"
- {!> ../../../docs_src/header_params/tutorial001_py310.py!}
+ ```Python hl_lines="3"
+ {!> ../../../docs_src/header_params/tutorial001.py!}
```
## Declare parâmetros de `Header`
@@ -24,16 +24,16 @@ Então declare os paramêtros de cabeçalho usando a mesma estrutura que em `Pat
O primeiro valor é o valor padrão, você pode passar todas as validações adicionais ou parâmetros de anotação:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial001.py!}
+ ```Python hl_lines="7"
+ {!> ../../../docs_src/header_params/tutorial001_py310.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="7"
- {!> ../../../docs_src/header_params/tutorial001_py310.py!}
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/header_params/tutorial001.py!}
```
!!! note "Detalhes Técnicos"
@@ -60,16 +60,16 @@ Portanto, você pode usar `user_agent` como faria normalmente no código Python,
Se por algum motivo você precisar desabilitar a conversão automática de sublinhados para hífens, defina o parâmetro `convert_underscores` de `Header` para `False`:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="10"
- {!> ../../../docs_src/header_params/tutorial002.py!}
+ ```Python hl_lines="8"
+ {!> ../../../docs_src/header_params/tutorial002_py310.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="8"
- {!> ../../../docs_src/header_params/tutorial002_py310.py!}
+ ```Python hl_lines="10"
+ {!> ../../../docs_src/header_params/tutorial002.py!}
```
!!! warning "Aviso"
@@ -85,22 +85,22 @@ Você receberá todos os valores do cabeçalho duplicado como uma `list` Python.
Por exemplo, para declarar um cabeçalho de `X-Token` que pode aparecer mais de uma vez, você pode escrever:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial003.py!}
+ ```Python hl_lines="7"
+ {!> ../../../docs_src/header_params/tutorial003_py310.py!}
```
-=== "Python 3.9 and above"
+=== "Python 3.9+"
```Python hl_lines="9"
{!> ../../../docs_src/header_params/tutorial003_py39.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="7"
- {!> ../../../docs_src/header_params/tutorial003_py310.py!}
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/header_params/tutorial003.py!}
```
Se você se comunicar com essa *operação de caminho* enviando dois cabeçalhos HTTP como:
diff --git a/docs/pt/docs/tutorial/path-operation-configuration.md b/docs/pt/docs/tutorial/path-operation-configuration.md
new file mode 100644
index 000000000..e0a23f665
--- /dev/null
+++ b/docs/pt/docs/tutorial/path-operation-configuration.md
@@ -0,0 +1,180 @@
+# Configuração da Operação de Rota
+
+Existem vários parâmetros que você pode passar para o seu *decorador de operação de rota* para configurá-lo.
+
+!!! warning "Aviso"
+ Observe que esses parâmetros são passados diretamente para o *decorador de operação de rota*, não para a sua *função de operação de rota*.
+
+## Código de Status da Resposta
+
+Você pode definir o `status_code` (HTTP) para ser usado na resposta da sua *operação de rota*.
+
+Você pode passar diretamente o código `int`, como `404`.
+
+Mas se você não se lembrar o que cada código numérico significa, pode usar as constantes de atalho em `status`:
+
+=== "Python 3.6 and above"
+
+ ```Python hl_lines="3 17"
+ {!> ../../../docs_src/path_operation_configuration/tutorial001.py!}
+ ```
+
+=== "Python 3.9 and above"
+
+ ```Python hl_lines="3 17"
+ {!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!}
+ ```
+
+=== "Python 3.10 and above"
+
+ ```Python hl_lines="1 15"
+ {!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!}
+ ```
+
+Esse código de status será usado na resposta e será adicionado ao esquema OpenAPI.
+
+!!! note "Detalhes Técnicos"
+ Você também poderia usar `from starlette import status`.
+
+ **FastAPI** fornece o mesmo `starlette.status` como `fastapi.status` apenas como uma conveniência para você, o desenvolvedor. Mas vem diretamente do Starlette.
+
+## Tags
+
+Você pode adicionar tags para sua *operação de rota*, passe o parâmetro `tags` com uma `list` de `str` (comumente apenas um `str`):
+
+=== "Python 3.6 and above"
+
+ ```Python hl_lines="17 22 27"
+ {!> ../../../docs_src/path_operation_configuration/tutorial002.py!}
+ ```
+
+=== "Python 3.9 and above"
+
+ ```Python hl_lines="17 22 27"
+ {!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!}
+ ```
+
+=== "Python 3.10 and above"
+
+ ```Python hl_lines="15 20 25"
+ {!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!}
+ ```
+
+Eles serão adicionados ao esquema OpenAPI e usados pelas interfaces de documentação automática:
+
+
+
+### Tags com Enums
+
+Se você tem uma grande aplicação, você pode acabar acumulando **várias tags**, e você gostaria de ter certeza de que você sempre usa a **mesma tag** para *operações de rota* relacionadas.
+
+Nestes casos, pode fazer sentido armazenar as tags em um `Enum`.
+
+**FastAPI** suporta isso da mesma maneira que com strings simples:
+
+```Python hl_lines="1 8-10 13 18"
+{!../../../docs_src/path_operation_configuration/tutorial002b.py!}
+```
+
+## Resumo e descrição
+
+Você pode adicionar um `summary` e uma `description`:
+
+=== "Python 3.6 and above"
+
+ ```Python hl_lines="20-21"
+ {!> ../../../docs_src/path_operation_configuration/tutorial003.py!}
+ ```
+
+=== "Python 3.9 and above"
+
+ ```Python hl_lines="20-21"
+ {!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!}
+ ```
+
+=== "Python 3.10 and above"
+
+ ```Python hl_lines="18-19"
+ {!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!}
+ ```
+
+## Descrição do docstring
+
+Como as descrições tendem a ser longas e cobrir várias linhas, você pode declarar a descrição da *operação de rota* na docstring da função e o **FastAPI** irá lê-la de lá.
+
+Você pode escrever Markdown na docstring, ele será interpretado e exibido corretamente (levando em conta a indentação da docstring).
+
+=== "Python 3.6 and above"
+
+ ```Python hl_lines="19-27"
+ {!> ../../../docs_src/path_operation_configuration/tutorial004.py!}
+ ```
+
+=== "Python 3.9 and above"
+
+ ```Python hl_lines="19-27"
+ {!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!}
+ ```
+
+=== "Python 3.10 and above"
+
+ ```Python hl_lines="17-25"
+ {!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!}
+ ```
+
+Ela será usada nas documentações interativas:
+
+
+
+
+## Descrição da resposta
+
+Você pode especificar a descrição da resposta com o parâmetro `response_description`:
+
+=== "Python 3.6 and above"
+
+ ```Python hl_lines="21"
+ {!> ../../../docs_src/path_operation_configuration/tutorial005.py!}
+ ```
+
+=== "Python 3.9 and above"
+
+ ```Python hl_lines="21"
+ {!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!}
+ ```
+
+=== "Python 3.10 and above"
+
+ ```Python hl_lines="19"
+ {!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!}
+ ```
+
+!!! info "Informação"
+ Note que `response_description` se refere especificamente à resposta, a `description` se refere à *operação de rota* em geral.
+
+!!! check
+ OpenAPI especifica que cada *operação de rota* requer uma descrição de resposta.
+
+ Então, se você não fornecer uma, o **FastAPI** irá gerar automaticamente uma de "Resposta bem-sucedida".
+
+
+
+## Depreciar uma *operação de rota*
+
+Se você precisar marcar uma *operação de rota* como descontinuada, mas sem removê-la, passe o parâmetro `deprecated`:
+
+```Python hl_lines="16"
+{!../../../docs_src/path_operation_configuration/tutorial006.py!}
+```
+
+Ela será claramente marcada como descontinuada nas documentações interativas:
+
+
+
+Verifique como *operações de rota* descontinuadas e não descontinuadas se parecem:
+
+
+
+## Resumindo
+
+Você pode configurar e adicionar metadados para suas *operações de rota* facilmente passando parâmetros para os *decoradores de operação de rota*.
diff --git a/docs/pt/docs/tutorial/path-params-numeric-validations.md b/docs/pt/docs/tutorial/path-params-numeric-validations.md
index f478fd190..ec9b74b30 100644
--- a/docs/pt/docs/tutorial/path-params-numeric-validations.md
+++ b/docs/pt/docs/tutorial/path-params-numeric-validations.md
@@ -6,16 +6,16 @@ Do mesmo modo que você pode declarar mais validações e metadados para parâme
Primeiro, importe `Path` de `fastapi`:
-=== "Python 3.6 e superiores"
+=== "Python 3.10+"
- ```Python hl_lines="3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
+ ```Python hl_lines="1"
+ {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
```
-=== "Python 3.10 e superiores"
+=== "Python 3.6+"
- ```Python hl_lines="1"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
+ ```Python hl_lines="3"
+ {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
```
## Declare metadados
@@ -24,16 +24,16 @@ Você pode declarar todos os parâmetros da mesma maneira que na `Query`.
Por exemplo para declarar um valor de metadado `title` para o parâmetro de rota `item_id` você pode digitar:
-=== "Python 3.6 e superiores"
+=== "Python 3.10+"
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
+ ```Python hl_lines="8"
+ {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
```
-=== "Python 3.10 e superiores"
+=== "Python 3.6+"
- ```Python hl_lines="8"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
+ ```Python hl_lines="10"
+ {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
```
!!! note "Nota"
diff --git a/docs/pt/docs/tutorial/query-params.md b/docs/pt/docs/tutorial/query-params.md
index 189724396..3ada4fd21 100644
--- a/docs/pt/docs/tutorial/query-params.md
+++ b/docs/pt/docs/tutorial/query-params.md
@@ -63,16 +63,16 @@ Os valores dos parâmetros na sua função serão:
Da mesma forma, você pode declarar parâmetros de consulta opcionais, definindo o valor padrão para `None`:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params/tutorial002.py!}
+ ```Python hl_lines="7"
+ {!> ../../../docs_src/query_params/tutorial002_py310.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params/tutorial002_py310.py!}
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/query_params/tutorial002.py!}
```
Nesse caso, o parâmetro da função `q` será opcional, e `None` será o padrão.
@@ -85,16 +85,16 @@ Nesse caso, o parâmetro da função `q` será opcional, e `None` será o padrã
Você também pode declarar tipos `bool`, e eles serão convertidos:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params/tutorial003.py!}
+ ```Python hl_lines="7"
+ {!> ../../../docs_src/query_params/tutorial003_py310.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params/tutorial003_py310.py!}
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/query_params/tutorial003.py!}
```
Nesse caso, se você for para:
@@ -137,16 +137,16 @@ E você não precisa declarar eles em nenhuma ordem específica.
Eles serão detectados pelo nome:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="8 10"
- {!> ../../../docs_src/query_params/tutorial004.py!}
+ ```Python hl_lines="6 8"
+ {!> ../../../docs_src/query_params/tutorial004_py310.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="6 8"
- {!> ../../../docs_src/query_params/tutorial004_py310.py!}
+ ```Python hl_lines="8 10"
+ {!> ../../../docs_src/query_params/tutorial004.py!}
```
## Parâmetros de consulta obrigatórios
@@ -203,17 +203,18 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
E claro, você pode definir alguns parâmetros como obrigatórios, alguns possuindo um valor padrão, e outros sendo totalmente opcionais:
-=== "Python 3.6 and above"
+=== "Python 3.10+"
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params/tutorial006.py!}
+ ```Python hl_lines="8"
+ {!> ../../../docs_src/query_params/tutorial006_py310.py!}
```
-=== "Python 3.10 and above"
+=== "Python 3.6+"
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params/tutorial006_py310.py!}
+ ```Python hl_lines="10"
+ {!> ../../../docs_src/query_params/tutorial006.py!}
```
+
Nesse caso, existem 3 parâmetros de consulta:
* `needy`, um `str` obrigatório.
diff --git a/docs/pt/docs/tutorial/static-files.md b/docs/pt/docs/tutorial/static-files.md
new file mode 100644
index 000000000..009158fc6
--- /dev/null
+++ b/docs/pt/docs/tutorial/static-files.md
@@ -0,0 +1,39 @@
+# Arquivos Estáticos
+
+Você pode servir arquivos estáticos automaticamente de um diretório usando `StaticFiles`.
+
+## Use `StaticFiles`
+
+* Importe `StaticFiles`.
+* "Monte" uma instância de `StaticFiles()` em um caminho específico.
+
+```Python hl_lines="2 6"
+{!../../../docs_src/static_files/tutorial001.py!}
+```
+
+!!! note "Detalhes técnicos"
+ Você também pode usar `from starlette.staticfiles import StaticFiles`.
+
+ O **FastAPI** fornece o mesmo que `starlette.staticfiles` como `fastapi.staticfiles` apenas como uma conveniência para você, o desenvolvedor. Mas na verdade vem diretamente da Starlette.
+
+### O que é "Montagem"
+
+"Montagem" significa adicionar um aplicativo completamente "independente" em uma rota específica, que então cuida de todas as subrotas.
+
+Isso é diferente de usar um `APIRouter`, pois um aplicativo montado é completamente independente. A OpenAPI e a documentação do seu aplicativo principal não incluirão nada do aplicativo montado, etc.
+
+Você pode ler mais sobre isso no **Guia Avançado do Usuário**.
+
+## Detalhes
+
+O primeiro `"/static"` refere-se à subrota em que este "subaplicativo" será "montado". Portanto, qualquer caminho que comece com `"/static"` será tratado por ele.
+
+O `directory="static"` refere-se ao nome do diretório que contém seus arquivos estáticos.
+
+O `name="static"` dá a ela um nome que pode ser usado internamente pelo FastAPI.
+
+Todos esses parâmetros podem ser diferentes de "`static`", ajuste-os de acordo com as necessidades e detalhes específicos de sua própria aplicação.
+
+## Mais informações
+
+Para mais detalhes e opções, verifique Starlette's docs about Static Files.
diff --git a/docs/pt/mkdocs.yml b/docs/pt/mkdocs.yml
index 0858de062..9c3007e03 100644
--- a/docs/pt/mkdocs.yml
+++ b/docs/pt/mkdocs.yml
@@ -40,11 +40,14 @@ nav:
- Languages:
- en: /
- az: /az/
+ - cs: /cs/
- de: /de/
+ - em: /em/
- es: /es/
- fa: /fa/
- fr: /fr/
- he: /he/
+ - hy: /hy/
- id: /id/
- it: /it/
- ja: /ja/
@@ -55,6 +58,7 @@ nav:
- ru: /ru/
- sq: /sq/
- sv: /sv/
+ - ta: /ta/
- tr: /tr/
- uk: /uk/
- zh: /zh/
@@ -68,18 +72,23 @@ nav:
- tutorial/body.md
- tutorial/body-multiple-params.md
- tutorial/body-fields.md
+ - tutorial/body-nested-models.md
- tutorial/extra-data-types.md
+ - tutorial/extra-models.md
- tutorial/query-params-str-validations.md
- tutorial/path-params-numeric-validations.md
+ - tutorial/path-operation-configuration.md
- tutorial/cookie-params.md
- tutorial/header-params.md
- tutorial/response-status-code.md
- tutorial/request-forms.md
- tutorial/request-forms-and-files.md
- tutorial/handling-errors.md
+ - tutorial/encoder.md
- Segurança:
- tutorial/security/index.md
- tutorial/background-tasks.md
+ - tutorial/static-files.md
- Guia de Usuário Avançado:
- advanced/index.md
- Implantação:
@@ -115,7 +124,7 @@ markdown_extensions:
extra:
analytics:
provider: google
- property: UA-133183413-1
+ property: G-YNEVN69SC3
social:
- icon: fontawesome/brands/github-alt
link: https://github.com/tiangolo/fastapi
@@ -136,8 +145,12 @@ extra:
name: en - English
- link: /az/
name: az
+ - link: /cs/
+ name: cs
- link: /de/
name: de
+ - link: /em/
+ name: 😉
- link: /es/
name: es - español
- link: /fa/
@@ -146,6 +159,8 @@ extra:
name: fr - français
- link: /he/
name: he
+ - link: /hy/
+ name: hy
- link: /id/
name: id
- link: /it/
@@ -166,6 +181,8 @@ extra:
name: sq - shqip
- link: /sv/
name: sv - svenska
+ - link: /ta/
+ name: ta - தமிழ்
- link: /tr/
name: tr - Türkçe
- link: /uk/
diff --git a/docs/ru/docs/alternatives.md b/docs/ru/docs/alternatives.md
new file mode 100644
index 000000000..9e3c497d1
--- /dev/null
+++ b/docs/ru/docs/alternatives.md
@@ -0,0 +1,460 @@
+# Альтернативы, источники вдохновения и сравнения
+
+Что вдохновило на создание **FastAPI**, сравнение его с альтернативами и чему он научился у них.
+
+## Введение
+
+**FastAPI** не существовал бы, если б не было более ранних работ других людей.
+
+Они создали большое количество инструментов, которые вдохновили меня на создание **FastAPI**.
+
+Я всячески избегал создания нового фреймворка в течение нескольких лет.
+Сначала я пытался собрать все нужные функции, которые ныне есть в **FastAPI**, используя множество различных фреймворков, плагинов и инструментов.
+
+Но в какой-то момент не осталось другого выбора, кроме как создать что-то, что предоставляло бы все эти функции сразу.
+Взять самые лучшие идеи из предыдущих инструментов и, используя новые возможности Python (которых не было до версии 3.6, то есть подсказки типов), объединить их.
+
+## Предшествующие инструменты
+
+### Django
+
+Это самый популярный Python-фреймворк, и он пользуется доверием.
+Он используется для создания проектов типа Instagram.
+
+Django довольно тесно связан с реляционными базами данных (такими как MySQL или PostgreSQL), потому использовать NoSQL базы данных (например, Couchbase, MongoDB, Cassandra и т.п.) в качестве основного хранилища данных - непросто.
+
+Он был создан для генерации HTML-страниц на сервере, а не для создания API, используемых современными веб-интерфейсами (React, Vue.js, Angular и т.п.) или другими системами (например, IoT) взаимодействующими с сервером.
+
+### Django REST Framework
+
+Фреймворк Django REST был создан, как гибкий инструментарий для создания веб-API на основе Django.
+
+DRF использовался многими компаниями, включая Mozilla, Red Hat и Eventbrite.
+
+Это был один из первых примеров **автоматического документирования API** и это была одна из первых идей, вдохновивших на создание **FastAPI**.
+
+!!! note "Заметка"
+ Django REST Framework был создан Tom Christie.
+ Он же создал Starlette и Uvicorn, на которых основан **FastAPI**.
+
+!!! check "Идея для **FastAPI**"
+ Должно быть автоматическое создание документации API с пользовательским веб-интерфейсом.
+
+### Flask
+
+Flask - это "микрофреймворк", в нём нет интеграции с базами данных и многих других вещей, которые предустановлены в Django.
+
+Его простота и гибкость дают широкие возможности, такие как использование баз данных NoSQL в качестве основной системы хранения данных.
+
+Он очень прост, его изучение интуитивно понятно, хотя в некоторых местах документация довольно техническая.
+
+Flask часто используется и для приложений, которым не нужна база данных, настройки прав доступа для пользователей и прочие из множества функций, предварительно встроенных в Django.
+Хотя многие из этих функций могут быть добавлены с помощью плагинов.
+
+Такое разделение на части и то, что это "микрофреймворк", который можно расширить, добавляя необходимые возможности, было ключевой особенностью, которую я хотел сохранить.
+
+Простота Flask, показалась мне подходящей для создания API.
+Но ещё нужно было найти "Django REST Framework" для Flask.
+
+!!! check "Идеи для **FastAPI**"
+ Это будет микрофреймворк. К нему легко будет добавить необходимые инструменты и части.
+
+ Должна быть простая и лёгкая в использовании система маршрутизации запросов.
+
+
+### Requests
+
+На самом деле **FastAPI** не является альтернативой **Requests**.
+Их область применения очень разная.
+
+В принципе, можно использовать Requests *внутри* приложения FastAPI.
+
+Но всё же я использовал в FastAPI некоторые идеи из Requests.
+
+**Requests** - это библиотека для взаимодействия с API в качестве клиента,
+в то время как **FastAPI** - это библиотека для *создания* API (то есть сервера).
+
+Они, так или иначе, диаметрально противоположны и дополняют друг друга.
+
+Requests имеет очень простой и понятный дизайн, очень прост в использовании и имеет разумные значения по умолчанию.
+И в то же время он очень мощный и настраиваемый.
+
+Вот почему на официальном сайте написано:
+
+> Requests - один из самых загружаемых пакетов Python всех времен
+
+
+Использовать его очень просто. Например, чтобы выполнить запрос `GET`, Вы бы написали:
+
+```Python
+response = requests.get("http://example.com/some/url")
+```
+
+Противоположная *операция пути* в FastAPI может выглядеть следующим образом:
+
+```Python hl_lines="1"
+@app.get("/some/url")
+def read_url():
+ return {"message": "Hello World"}
+```
+
+Глядите, как похоже `requests.get(...)` и `@app.get(...)`.
+
+!!! check "Идеи для **FastAPI**"
+ * Должен быть простой и понятный API.
+ * Нужно использовать названия HTTP-методов (операций) для упрощения понимания происходящего.
+ * Должны быть разумные настройки по умолчанию и широкие возможности их кастомизации.
+
+
+### Swagger / OpenAPI
+
+Главной функцией, которую я хотел унаследовать от Django REST Framework, была автоматическая документация API.
+
+Но потом я обнаружил, что существует стандарт документирования API, использующий JSON (или YAML, расширение JSON) под названием Swagger.
+
+И к нему уже был создан пользовательский веб-интерфейс.
+Таким образом, возможность генерировать документацию Swagger для API позволила бы использовать этот интерфейс.
+
+В какой-то момент Swagger был передан Linux Foundation и переименован в OpenAPI.
+
+Вот почему, когда говорят о версии 2.0, обычно говорят "Swagger", а для версии 3+ "OpenAPI".
+
+!!! check "Идеи для **FastAPI**"
+ Использовать открытые стандарты для спецификаций API вместо самодельных схем.
+
+ Совместимость с основанными на стандартах пользовательскими интерфейсами:
+
+ * Swagger UI
+ * ReDoc
+
+ Они были выбраны за популярность и стабильность.
+ Но сделав беглый поиск, Вы можете найти десятки альтернативных пользовательских интерфейсов для OpenAPI, которые Вы можете использовать с **FastAPI**.
+
+### REST фреймворки для Flask
+
+Существует несколько REST фреймворков для Flask, но потратив время и усилия на их изучение, я обнаружил, что многие из них не обновляются или заброшены и имеют нерешённые проблемы из-за которых они непригодны к использованию.
+
+### Marshmallow
+
+Одной из основных функций, необходимых системам API, является "сериализация" данных, то есть преобразование данных из кода (Python) во что-то, что может быть отправлено по сети.
+Например, превращение объекта содержащего данные из базы данных в объект JSON, конвертация объекта `datetime` в строку и т.п.
+
+Еще одна важная функция, необходимая API — проверка данных, позволяющая убедиться, что данные действительны и соответствуют заданным параметрам.
+Как пример, можно указать, что ожидаются данные типа `int`, а не какая-то произвольная строка.
+Это особенно полезно для входящих данных.
+
+Без системы проверки данных Вам пришлось бы прописывать все проверки вручную.
+
+Именно для обеспечения этих функций и была создана Marshmallow.
+Это отличная библиотека и я много раз пользовался ею раньше.
+
+Но она была создана до того, как появились подсказки типов Python.
+Итак, чтобы определить каждую схему,
+Вам нужно использовать определенные утилиты и классы, предоставляемые Marshmallow.
+
+!!! check "Идея для **FastAPI**"
+ Использовать код программы для автоматического создания "схем", определяющих типы данных и их проверку.
+
+### Webargs
+
+Другая немаловажная функция API - парсинг данных из входящих запросов.
+
+Webargs - это инструмент, который был создан для этого и поддерживает несколько фреймворков, включая Flask.
+
+Для проверки данных он использует Marshmallow и создан теми же авторами.
+
+Это превосходный инструмент и я тоже часто пользовался им до **FastAPI**.
+
+!!! info "Информация"
+ Webargs бы создан разработчиками Marshmallow.
+
+!!! check "Идея для **FastAPI**"
+ Должна быть автоматическая проверка входных данных.
+
+### APISpec
+
+Marshmallow и Webargs осуществляют проверку, анализ и сериализацию данных как плагины.
+
+Но документации API всё ещё не было. Тогда был создан APISpec.
+
+Это плагин для множества фреймворков, в том числе и для Starlette.
+
+Он работает так - Вы записываете определение схем, используя формат YAML, внутри докстринга каждой функции, обрабатывающей маршрут.
+
+Используя эти докстринги, он генерирует схему OpenAPI.
+
+Так это работает для Flask, Starlette, Responder и т.п.
+
+Но теперь у нас возникает новая проблема - наличие постороннего микро-синтаксиса внутри кода Python (большие YAML).
+
+Редактор кода не особо может помочь в такой парадигме.
+А изменив какие-то параметры или схемы для Marshmallow можно забыть отредактировать докстринг с YAML и сгенерированная схема становится недействительной.
+
+!!! info "Информация"
+ APISpec тоже был создан авторами Marshmallow.
+
+!!! check "Идея для **FastAPI**"
+ Необходима поддержка открытого стандарта для API - OpenAPI.
+
+### Flask-apispec
+
+Это плагин для Flask, который связан с Webargs, Marshmallow и APISpec.
+
+Он получает информацию от Webargs и Marshmallow, а затем использует APISpec для автоматического создания схемы OpenAPI.
+
+Это отличный, но крайне недооценённый инструмент.
+Он должен быть более популярен, чем многие плагины для Flask.
+Возможно, это связано с тем, что его документация слишком скудна и абстрактна.
+
+Он избавил от необходимости писать чужеродный синтаксис YAML внутри докстрингов.
+
+Такое сочетание Flask, Flask-apispec, Marshmallow и Webargs было моим любимым стеком при построении бэкенда до появления **FastAPI**.
+
+Использование этого стека привело к созданию нескольких генераторов проектов. Я и некоторые другие команды до сих пор используем их:
+
+* https://github.com/tiangolo/full-stack
+* https://github.com/tiangolo/full-stack-flask-couchbase
+* https://github.com/tiangolo/full-stack-flask-couchdb
+
+Эти генераторы проектов также стали основой для [Генераторов проектов с **FastAPI**](project-generation.md){.internal-link target=_blank}.
+
+!!! info "Информация"
+ Как ни странно, но Flask-apispec тоже создан авторами Marshmallow.
+
+!!! check "Идея для **FastAPI**"
+ Схема OpenAPI должна создаваться автоматически и использовать тот же код, который осуществляет сериализацию и проверку данных.
+
+### NestJS (и Angular)
+
+Здесь даже не используется Python. NestJS - этот фреймворк написанный на JavaScript (TypeScript), основанный на NodeJS и вдохновлённый Angular.
+
+Он позволяет получить нечто похожее на то, что можно сделать с помощью Flask-apispec.
+
+В него встроена система внедрения зависимостей, ещё одна идея взятая от Angular.
+Однако требуется предварительная регистрация "внедрений" (как и во всех других известных мне системах внедрения зависимостей), что увеличивает количество и повторяемость кода.
+
+Так как параметры в нём описываются с помощью типов TypeScript (аналогично подсказкам типов в Python), поддержка редактора работает довольно хорошо.
+
+Но поскольку данные из TypeScript не сохраняются после компиляции в JavaScript, он не может полагаться на подсказки типов для определения проверки данных, сериализации и документации.
+Из-за этого и некоторых дизайнерских решений, для валидации, сериализации и автоматической генерации схем, приходится во многих местах добавлять декораторы.
+Таким образом, это становится довольно многословным.
+
+Кроме того, он не очень хорошо справляется с вложенными моделями.
+Если в запросе имеется объект JSON, внутренние поля которого, в свою очередь, являются вложенными объектами JSON, это не может быть должным образом задокументировано и проверено.
+
+!!! check "Идеи для **FastAPI** "
+ Нужно использовать подсказки типов, чтоб воспользоваться поддержкой редактора кода.
+
+ Нужна мощная система внедрения зависимостей. Необходим способ для уменьшения повторов кода.
+
+### Sanic
+
+Sanic был одним из первых чрезвычайно быстрых Python-фреймворков основанных на `asyncio`.
+Он был сделан очень похожим на Flask.
+
+!!! note "Технические детали"
+ В нём использован `uvloop` вместо стандартного цикла событий `asyncio`, что и сделало его таким быстрым.
+
+ Он явно вдохновил создателей Uvicorn и Starlette, которые в настоящее время быстрее Sanic в открытых бенчмарках.
+
+!!! check "Идеи для **FastAPI**"
+ Должна быть сумасшедшая производительность.
+
+ Для этого **FastAPI** основан на Starlette, самом быстром из доступных фреймворков (по замерам незаинтересованных лиц).
+
+### Falcon
+
+Falcon - ещё один высокопроизводительный Python-фреймворк.
+В нём минимум функций и он создан, чтоб быть основой для других фреймворков, например, Hug.
+
+Функции в нём получают два параметра - "запрос к серверу" и "ответ сервера".
+Затем Вы "читаете" часть запроса и "пишите" часть ответа.
+Из-за такой конструкции невозможно объявить параметры запроса и тела сообщения со стандартными подсказками типов Python в качестве параметров функции.
+
+Таким образом, и валидацию данных, и их сериализацию, и документацию нужно прописывать вручную.
+Либо эти функции должны быть встроены во фреймворк, сконструированный поверх Falcon, как в Hug.
+Такая же особенность присутствует и в других фреймворках, вдохновлённых идеей Falcon, использовать только один объект запроса и один объект ответа.
+
+!!! check "Идея для **FastAPI**"
+ Найдите способы добиться отличной производительности.
+
+ Объявлять параметры `ответа сервера` в функциях, как в Hug.
+
+ Хотя в FastAPI это необязательно и используется в основном для установки заголовков, куки и альтернативных кодов состояния.
+
+### Molten
+
+Molten мне попался на начальной стадии написания **FastAPI**. В нём были похожие идеи:
+
+* Использование подсказок типов.
+* Валидация и документация исходя из этих подсказок.
+* Система внедрения зависимостей.
+
+В нём не используются сторонние библиотеки (такие, как Pydantic) для валидации, сериализации и документации.
+Поэтому переиспользовать эти определения типов непросто.
+
+Также требуется более подробная конфигурация и используется стандарт WSGI, который не предназначен для использования с высокопроизводительными инструментами, такими как Uvicorn, Starlette и Sanic, в отличие от ASGI.
+
+Его система внедрения зависимостей требует предварительной регистрации, и зависимости определяются, как объявления типов.
+Из-за этого невозможно объявить более одного "компонента" (зависимости), который предоставляет определенный тип.
+
+Маршруты объявляются в единственном месте с использованием функций, объявленных в других местах (вместо использования декораторов, в которые могут быть обёрнуты функции, обрабатывающие конкретные ресурсы).
+Это больше похоже на Django, чем на Flask и Starlette.
+Он разделяет в коде вещи, которые довольно тесно связаны.
+
+!!! check "Идея для **FastAPI**"
+ Определить дополнительные проверки типов данных, используя значения атрибутов модели "по умолчанию".
+ Это улучшает помощь редактора и раньше это не было доступно в Pydantic.
+
+ Фактически это подтолкнуло на обновление Pydantic для поддержки одинакового стиля проверок (теперь этот функционал уже доступен в Pydantic).
+
+### Hug
+
+Hug был одним из первых фреймворков, реализовавших объявление параметров API с использованием подсказок типов Python.
+Эта отличная идея была использована и другими инструментами.
+
+При объявлении параметров вместо стандартных типов Python использовались собственные типы, но всё же это был огромный шаг вперед.
+
+Это также был один из первых фреймворков, генерировавших полную API-схему в формате JSON.
+
+Данная схема не придерживалась стандартов вроде OpenAPI и JSON Schema.
+Поэтому было бы непросто совместить её с другими инструментами, такими как Swagger UI.
+Но опять же, это была очень инновационная идея.
+
+Ещё у него есть интересная и необычная функция: используя один и тот же фреймворк можно создавать и API, и CLI.
+
+Поскольку он основан на WSGI, старом стандарте для синхронных веб-фреймворков, он не может работать с веб-сокетами и другими модными штуками, но всё равно обладает высокой производительностью.
+
+!!! info "Информация"
+ Hug создан Timothy Crosley, автором `isort`, отличного инструмента для автоматической сортировки импортов в Python-файлах.
+
+!!! check "Идеи для **FastAPI**"
+ Hug повлиял на создание некоторых частей APIStar и был одним из инструментов, которые я счел наиболее многообещающими, наряду с APIStar.
+
+ Hug натолкнул на мысли использовать в **FastAPI** подсказки типов Python для автоматического создания схемы, определяющей API и его параметры.
+
+ Hug вдохновил **FastAPI** объявить параметр `ответа` в функциях для установки заголовков и куки.
+
+### APIStar (<= 0.5)
+
+Непосредственно перед тем, как принять решение о создании **FastAPI**, я обнаружил **APIStar**.
+В нем было почти все, что я искал и у него был отличный дизайн.
+
+Это была одна из первых реализаций фреймворка, использующего подсказки типов для объявления параметров и запросов, которые я когда-либо видел (до NestJS и Molten).
+Я нашёл его примерно в то же время, что и Hug, но APIStar использовал стандарт OpenAPI.
+
+В нём были автоматические проверка и сериализация данных и генерация схемы OpenAPI основанные на подсказках типов в нескольких местах.
+
+При определении схемы тела сообщения не использовались подсказки типов, как в Pydantic, это больше похоже на Marshmallow, поэтому помощь редактора была недостаточно хорошей, но всё же APIStar был лучшим доступным вариантом.
+
+На тот момент у него были лучшие показатели производительности (проигрывающие только Starlette).
+
+Изначально у него не было автоматической документации API для веб-интерфейса, но я знал, что могу добавить к нему Swagger UI.
+
+В APIStar была система внедрения зависимостей, которая тоже требовала предварительную регистрацию компонентов, как и ранее описанные инструменты.
+Но, тем не менее, это была отличная штука.
+
+Я не смог использовать его в полноценном проекте, так как были проблемы со встраиванием функций безопасности в схему OpenAPI, из-за которых невозможно было встроить все функции, применяемые в генераторах проектов на основе Flask-apispec.
+Я добавил в свой список задач создание пул-реквеста, добавляющего эту функциональность.
+
+В дальнейшем фокус проекта сместился.
+
+Это больше не был API-фреймворк, так как автор сосредоточился на Starlette.
+
+Ныне APIStar - это набор инструментов для проверки спецификаций OpenAPI.
+
+!!! info "Информация"
+ APIStar был создан Tom Christie. Тот самый парень, который создал:
+
+ * Django REST Framework
+ * Starlette (на котором основан **FastAPI**)
+ * Uvicorn (используемый в Starlette и **FastAPI**)
+
+!!! check "Идеи для **FastAPI**"
+ Воплощение.
+
+ Мне казалось блестящей идеей объявлять множество функций (проверка данных, сериализация, документация) с помощью одних и тех же типов Python, которые при этом обеспечивают ещё и помощь редактора кода.
+
+ После долгих поисков среди похожих друг на друга фреймворков и сравнения их различий, APIStar стал самым лучшим выбором.
+
+ Но APIStar перестал быть фреймворком для создания веб-сервера, зато появился Starlette, новая и лучшая основа для построения подобных систем.
+ Это была последняя капля, сподвигнувшая на создание **FastAPI**.
+
+ Я считаю **FastAPI** "духовным преемником" APIStar, улучившим его возможности благодаря урокам, извлечённым из всех упомянутых выше инструментов.
+
+## Что используется в **FastAPI**
+
+### Pydantic
+
+Pydantic - это библиотека для валидации данных, сериализации и документирования (используя JSON Schema), основываясь на подсказках типов Python, что делает его чрезвычайно интуитивным.
+
+Его можно сравнить с Marshmallow, хотя в бенчмарках Pydantic быстрее, чем Marshmallow.
+И он основан на тех же подсказках типов, которые отлично поддерживаются редакторами кода.
+
+!!! check "**FastAPI** использует Pydantic"
+ Для проверки данных, сериализации данных и автоматической документации моделей (на основе JSON Schema).
+
+ Затем **FastAPI** берёт эти схемы JSON и помещает их в схему OpenAPI, не касаясь других вещей, которые он делает.
+
+### Starlette
+
+Starlette - это легковесный ASGI фреймворк/набор инструментов, который идеален для построения высокопроизводительных асинхронных сервисов.
+
+Starlette очень простой и интуитивный.
+Он разработан таким образом, чтобы быть легко расширяемым и иметь модульные компоненты.
+
+В нём есть:
+
+* Впечатляющая производительность.
+* Поддержка веб-сокетов.
+* Фоновые задачи.
+* Обработка событий при старте и финише приложения.
+* Тестовый клиент на основе HTTPX.
+* Поддержка CORS, сжатие GZip, статические файлы, потоковая передача данных.
+* Поддержка сессий и куки.
+* 100% покрытие тестами.
+* 100% аннотированный код.
+* Несколько жёстких зависимостей.
+
+В настоящее время Starlette показывает самую высокую скорость среди Python-фреймворков в тестовых замерах.
+Быстрее только Uvicorn, который является сервером, а не фреймворком.
+
+Starlette обеспечивает весь функционал микрофреймворка, но не предоставляет автоматическую валидацию данных, сериализацию и документацию.
+
+**FastAPI** добавляет эти функции используя подсказки типов Python и Pydantic.
+Ещё **FastAPI** добавляет систему внедрения зависимостей, утилиты безопасности, генерацию схемы OpenAPI и т.д.
+
+!!! note "Технические детали"
+ ASGI - это новый "стандарт" разработанный участниками команды Django.
+ Он пока что не является "стандартом в Python" (то есть принятым PEP), но процесс принятия запущен.
+
+ Тем не менее он уже используется в качестве "стандарта" несколькими инструментами.
+ Это значительно улучшает совместимость, поскольку Вы можете переключиться с Uvicorn на любой другой ASGI-сервер (например, Daphne или Hypercorn) или Вы можете добавить ASGI-совместимые инструменты, такие как `python-socketio`.
+
+!!! check "**FastAPI** использует Starlette"
+ В качестве ядра веб-сервиса для обработки запросов, добавив некоторые функции сверху.
+
+ Класс `FastAPI` наследуется напрямую от класса `Starlette`.
+
+ Таким образом, всё что Вы могли делать со Starlette, Вы можете делать с **FastAPI**, по сути это прокачанный Starlette.
+
+### Uvicorn
+
+Uvicorn - это молниеносный ASGI-сервер, построенный на uvloop и httptools.
+
+Uvicorn является сервером, а не фреймворком.
+Например, он не предоставляет инструментов для маршрутизации запросов по ресурсам.
+Для этого нужна надстройка, такая как Starlette (или **FastAPI**).
+
+Он рекомендуется в качестве сервера для Starlette и **FastAPI**.
+
+!!! check "**FastAPI** рекомендует его"
+ Как основной сервер для запуска приложения **FastAPI**.
+
+ Вы можете объединить его с Gunicorn, чтобы иметь асинхронный многопроцессный сервер.
+
+ Узнать больше деталей можно в разделе [Развёртывание](deployment/index.md){.internal-link target=_blank}.
+
+## Тестовые замеры и скорость
+
+Чтобы понять, сравнить и увидеть разницу между Uvicorn, Starlette и FastAPI, ознакомьтесь с разделом [Тестовые замеры](benchmarks.md){.internal-link target=_blank}.
diff --git a/docs/ru/docs/benchmarks.md b/docs/ru/docs/benchmarks.md
new file mode 100644
index 000000000..259dca8e6
--- /dev/null
+++ b/docs/ru/docs/benchmarks.md
@@ -0,0 +1,37 @@
+# Замеры производительности
+
+Независимые тесты производительности приложений от TechEmpower показывают, что **FastAPI** под управлением Uvicorn один из самых быстрых Python-фреймворков и уступает только Starlette и Uvicorn (которые используются в FastAPI). (*)
+
+Но при просмотре и сравнении замеров производительности следует иметь в виду нижеописанное.
+
+## Замеры производительности и скорости
+
+В подобных тестах часто можно увидеть, что инструменты разного типа сравнивают друг с другом, как аналогичные.
+
+В частности, сравнивают вместе Uvicorn, Starlette и FastAPI (среди многих других инструментов).
+
+Чем проще проблема, которую решает инструмент, тем выше его производительность. И большинство тестов не проверяют дополнительные функции, предоставляемые инструментом.
+
+Иерархия инструментов имеет следующий вид:
+
+* **Uvicorn**: ASGI-сервер
+ * **Starlette** (использует Uvicorn): веб-микрофреймворк
+ * **FastAPI** (использует Starlette): API-микрофреймворк с дополнительными функциями для создания API, с валидацией данных и т.д.
+
+* **Uvicorn**:
+ * Будет иметь наилучшую производительность, так как не имеет большого количества дополнительного кода, кроме самого сервера.
+ * Вы не будете писать приложение на Uvicorn напрямую. Это означало бы, что Ваш код должен включать как минимум весь
+ код, предоставляемый Starlette (или **FastAPI**). И если Вы так сделаете, то в конечном итоге Ваше приложение будет иметь те же накладные расходы, что и при использовании фреймворка, минимизирующего код Вашего приложения и Ваши ошибки.
+ * Uvicorn подлежит сравнению с Daphne, Hypercorn, uWSGI и другими веб-серверами.
+
+* **Starlette**:
+ * Будет уступать Uvicorn по производительности. Фактически Starlette управляется Uvicorn и из-за выполнения большего количества кода он не может быть быстрее, чем Uvicorn.
+ * Зато он предоставляет Вам инструменты для создания простых веб-приложений с обработкой маршрутов URL и т.д.
+ * Starlette следует сравнивать с Sanic, Flask, Django и другими веб-фреймворками (или микрофреймворками).
+
+* **FastAPI**:
+ * Так же как Starlette использует Uvicorn и не может быть быстрее него, **FastAPI** использует Starlette, то есть он не может быть быстрее Starlette.
+ * FastAPI предоставляет больше возможностей поверх Starlette, которые наверняка Вам понадобятся при создании API, такие как проверка данных и сериализация. В довесок Вы ещё и получаете автоматическую документацию (автоматическая документация даже не увеличивает накладные расходы при работе приложения, так как она создается при запуске).
+ * Если Вы не используете FastAPI, а используете Starlette напрямую (или другой инструмент вроде Sanic, Flask, Responder и т.д.), Вам пришлось бы самостоятельно реализовать валидацию и сериализацию данных. То есть, в итоге, Ваше приложение имело бы такие же накладные расходы, как если бы оно было создано с использованием FastAPI. И во многих случаях валидация и сериализация данных представляют собой самый большой объём кода, написанного в приложениях.
+ * Таким образом, используя FastAPI Вы потратите меньше времени на разработку, уменьшите количество ошибок, строк кода и, вероятно, получите ту же производительность (или лучше), как и если бы не использовали его (поскольку Вам пришлось бы реализовать все его возможности в своем коде).
+ * FastAPI должно сравнивать с фреймворками веб-приложений (или наборами инструментов), которые обеспечивают валидацию и сериализацию данных, а также предоставляют автоматическую документацию, такими как Flask-apispec, NestJS, Molten и им подобные.
diff --git a/docs/ru/docs/contributing.md b/docs/ru/docs/contributing.md
new file mode 100644
index 000000000..f61ef1cb6
--- /dev/null
+++ b/docs/ru/docs/contributing.md
@@ -0,0 +1,469 @@
+# Участие в разработке фреймворка
+
+Возможно, для начала Вам стоит ознакомиться с основными способами [помочь FastAPI или получить помощь](help-fastapi.md){.internal-link target=_blank}.
+
+## Разработка
+
+Если Вы уже склонировали репозиторий и знаете, что Вам нужно более глубокое погружение в код фреймворка, то здесь представлены некоторые инструкции по настройке виртуального окружения.
+
+### Виртуальное окружение с помощью `venv`
+
+Находясь в нужной директории, Вы можете создать виртуальное окружение при помощи Python модуля `venv`.
+
+
+
+```console
+$ python -m venv env
+```
+
+
+
+Эта команда создаст директорию `./env/` с бинарными (двоичными) файлами Python, а затем Вы сможете скачивать и устанавливать необходимые библиотеки в изолированное виртуальное окружение.
+
+### Активация виртуального окружения
+
+Активируйте виртуально окружение командой:
+
+=== "Linux, macOS"
+
+
+
+Если в терминале появится ответ, что бинарник `pip` расположен по пути `.../env/bin/pip`, значит всё в порядке. 🎉
+
+Во избежание ошибок в дальнейших шагах, удостоверьтесь, что в Вашем виртуальном окружении установлена последняя версия `pip`:
+
+
+
+!!! tip "Подсказка"
+ Каждый раз, перед установкой новой библиотеки в виртуальное окружение при помощи `pip`, не забудьте активировать это виртуальное окружение.
+
+ Это гарантирует, что если Вы используете библиотеку, установленную этим пакетом, то Вы используете библиотеку из Вашего локального окружения, а не любую другую, которая может быть установлена глобально.
+
+### pip
+
+После активации виртуального окружения, как было указано ранее, введите следующую команду:
+
+
+
+Это установит все необходимые зависимости в локальное окружение для Вашего локального FastAPI.
+
+#### Использование локального FastAPI
+
+Если Вы создаёте Python файл, который импортирует и использует FastAPI,а затем запускаете его интерпретатором Python из Вашего локального окружения, то он будет использовать код из локального FastAPI.
+
+И, так как при вводе вышеупомянутой команды был указан флаг `-e`, если Вы измените код локального FastAPI, то при следующем запуске этого файла, он будет использовать свежую версию локального FastAPI, который Вы только что изменили.
+
+Таким образом, Вам не нужно "переустанавливать" Вашу локальную версию, чтобы протестировать каждое изменение.
+
+### Форматировние
+
+Скачанный репозиторий содержит скрипт, который может отформатировать и подчистить Ваш код:
+
+
+
+```console
+$ bash scripts/format.sh
+```
+
+
+
+Заодно он упорядочит Ваши импорты.
+
+Чтобы он сортировал их правильно, необходимо, чтобы FastAPI был установлен локально в Вашей среде, с помощью команды из раздела выше, использующей флаг `-e`.
+
+## Документация
+
+Прежде всего, убедитесь, что Вы настроили своё окружение, как описано выше, для установки всех зависимостей.
+
+Документация использует MkDocs.
+
+Также существуют дополнительные инструменты/скрипты для работы с переводами в `./scripts/docs.py`.
+
+!!! tip "Подсказка"
+
+ Нет необходимости заглядывать в `./scripts/docs.py`, просто используйте это в командной строке.
+
+Вся документация имеет формат Markdown и расположена в директории `./docs/en/`.
+
+Многие руководства содержат блоки кода.
+
+В большинстве случаев эти блоки кода представляют собой вполне законченные приложения, которые можно запускать как есть.
+
+На самом деле, эти блоки кода не написаны внутри Markdown, это Python файлы в директории `./docs_src/`.
+
+И эти Python файлы включаются/вводятся в документацию при создании сайта.
+
+### Тестирование документации
+
+
+Фактически, большинство тестов запускаются с примерами исходных файлов в документации.
+
+Это помогает убедиться, что:
+
+* Документация находится в актуальном состоянии.
+* Примеры из документации могут быть запущены как есть.
+* Большинство функций описаны в документации и покрыты тестами.
+
+Существует скрипт, который во время локальной разработки создаёт сайт и проверяет наличие любых изменений, перезагружая его в реальном времени:
+
+
+
+Он запустит сайт документации по адресу: `http://127.0.0.1:8008`.
+
+
+Таким образом, Вы сможете редактировать файлы с документацией или кодом и наблюдать изменения вживую.
+
+#### Typer CLI (опционально)
+
+
+Приведенная ранее инструкция показала Вам, как запускать скрипт `./scripts/docs.py` непосредственно через интерпретатор `python` .
+
+Но также можно использовать Typer CLI, что позволит Вам воспользоваться автозаполнением команд в Вашем терминале.
+
+Если Вы установили Typer CLI, то для включения функции автозаполнения, введите эту команду:
+
+
+
+```console
+$ typer --install-completion
+
+zsh completion installed in /home/user/.bashrc.
+Completion will take effect once you restart the terminal.
+```
+
+
+
+### Приложения и документация одновременно
+
+Если Вы запускаете приложение, например так:
+
+
+
+```console
+$ uvicorn tutorial001:app --reload
+
+INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
+```
+
+
+
+По умолчанию Uvicorn будет использовать порт `8000` и не будет конфликтовать с сайтом документации, использующим порт `8008`.
+
+### Переводы на другие языки
+
+Помощь с переводами ценится КРАЙНЕ ВЫСОКО! И переводы не могут быть сделаны без помощи сообщества. 🌎 🚀
+
+Ниже приведены шаги, как помочь с переводами.
+
+#### Подсказки и инструкции
+
+* Проверьте существующие пул-реквесты для Вашего языка. Добавьте отзывы с просьбой внести изменения, если они необходимы, или одобрите их.
+
+!!! tip "Подсказка"
+ Вы можете добавлять комментарии с предложениями по изменению в существующие пул-реквесты.
+
+ Ознакомьтесь с документацией о добавлении отзыва к пул-реквесту, чтобы утвердить его или запросить изменения.
+
+* Проверьте проблемы и вопросы, чтобы узнать, есть ли кто-то, координирующий переводы для Вашего языка.
+
+* Добавляйте один пул-реквест для каждой отдельной переведённой страницы. Это значительно облегчит другим его просмотр.
+
+Для языков, которые я не знаю, прежде чем добавить перевод в основную ветку, я подожду пока несколько других участников сообщества проверят его.
+
+* Вы также можете проверить, есть ли переводы для Вашего языка и добавить к ним отзыв, который поможет мне убедиться в правильности перевода. Тогда я смогу объединить его с основной веткой.
+
+* Используйте те же самые примеры кода Python. Переводите только текст документации. Вам не нужно ничего менять, чтобы эти примеры работали.
+
+* Используйте те же самые изображения, имена файлов и ссылки. Вы не должны менять ничего для сохранения работоспособности.
+
+* Чтобы узнать 2-буквенный код языка, на который Вы хотите сделать перевод, Вы можете воспользоваться таблицей Список кодов языков ISO 639-1.
+
+#### Существующий язык
+
+Допустим, Вы хотите перевести страницу на язык, на котором уже есть какие-то переводы, например, на испанский.
+
+Кодом испанского языка является `es`. А значит директория для переводов на испанский язык: `docs/es/`.
+
+!!! tip "Подсказка"
+ Главный ("официальный") язык - английский, директория для него `docs/en/`.
+
+Вы можете запустить сервер документации на испанском:
+
+
+
+```console
+// Используйте команду "live" и передайте код языка в качестве аргумента командной строки
+$ python ./scripts/docs.py live es
+
+[INFO] Serving on http://127.0.0.1:8008
+[INFO] Start watching changes
+[INFO] Start detecting changes
+```
+
+
+
+Теперь Вы можете перейти по адресу: http://127.0.0.1:8008 и наблюдать вносимые Вами изменения вживую.
+
+
+Если Вы посмотрите на сайт документации FastAPI, то увидите, что все страницы есть на каждом языке. Но некоторые страницы не переведены и имеют уведомление об отсутствующем переводе.
+
+Но когда Вы запускаете сайт локально, Вы видите только те страницы, которые уже переведены.
+
+
+Предположим, что Вы хотите добавить перевод страницы [Основные свойства](features.md){.internal-link target=_blank}.
+
+* Скопируйте файл:
+
+```
+docs/en/docs/features.md
+```
+
+* Вставьте его точно в то же место, но в директорию языка, на который Вы хотите сделать перевод, например:
+
+```
+docs/es/docs/features.md
+```
+
+!!! tip "Подсказка"
+ Заметьте, что в пути файла мы изменили только код языка с `en` на `es`.
+
+* Теперь откройте файл конфигурации MkDocs для английского языка, расположенный тут:
+
+```
+docs/en/mkdocs.yml
+```
+
+* Найдите в файле конфигурации место, где расположена строка `docs/features.md`. Похожее на это:
+
+```YAML hl_lines="8"
+site_name: FastAPI
+# More stuff
+nav:
+- FastAPI: index.md
+- Languages:
+ - en: /
+ - es: /es/
+- features.md
+```
+
+* Откройте файл конфигурации MkDocs для языка, на который Вы переводите, например:
+
+```
+docs/es/mkdocs.yml
+```
+
+* Добавьте строку `docs/features.md` точно в то же место, как и в случае для английского, как-то так:
+
+```YAML hl_lines="8"
+site_name: FastAPI
+# More stuff
+nav:
+- FastAPI: index.md
+- Languages:
+ - en: /
+ - es: /es/
+- features.md
+```
+
+Убедитесь, что при наличии других записей, новая запись с Вашим переводом находится точно в том же порядке, что и в английской версии.
+
+Если Вы зайдёте в свой браузер, то увидите, что в документации стал отображаться Ваш новый раздел.🎉
+
+Теперь Вы можете переводить эту страницу и смотреть, как она выглядит при сохранении файла.
+
+#### Новый язык
+
+Допустим, Вы хотите добавить перевод для языка, на который пока что не переведена ни одна страница.
+
+Скажем, Вы решили сделать перевод для креольского языка, но его еще нет в документации.
+
+Перейдите в таблицу кодов языков по ссылке указанной выше, где найдёте, что кодом креольского языка является `ht`.
+
+Затем запустите скрипт, генерирующий директорию для переводов на новые языки:
+
+
+
+```console
+// Используйте команду new-lang и передайте код языка в качестве аргумента командной строки
+$ python ./scripts/docs.py new-lang ht
+
+Successfully initialized: docs/ht
+Updating ht
+Updating en
+```
+
+
+
+После чего Вы можете проверить в своем редакторе кода, что появился новый каталог `docs/ht/`.
+
+!!! tip "Подсказка"
+ Создайте первый пул-реквест, который будет содержать только пустую директорию для нового языка, прежде чем добавлять переводы.
+
+ Таким образом, другие участники могут переводить другие страницы, пока Вы работаете над одной. 🚀
+
+Начните перевод с главной страницы `docs/ht/index.md`.
+
+В дальнейшем можно действовать, как указано в предыдущих инструкциях для "существующего языка".
+
+##### Новый язык не поддерживается
+
+Если при запуске скрипта `./scripts/docs.py live` Вы получаете сообщение об ошибке, что язык не поддерживается, что-то вроде:
+
+```
+ raise TemplateNotFound(template)
+jinja2.exceptions.TemplateNotFound: partials/language/xx.html
+```
+
+Сие означает, что тема не поддерживает этот язык (в данном случае с поддельным 2-буквенным кодом `xx`).
+
+Но не стоит переживать. Вы можете установить языком темы английский, а затем перевести текст документации.
+
+Если возникла такая необходимость, отредактируйте `mkdocs.yml` для Вашего нового языка. Это будет выглядеть как-то так:
+
+```YAML hl_lines="5"
+site_name: FastAPI
+# More stuff
+theme:
+ # More stuff
+ language: xx
+```
+
+Измените `xx` (код Вашего языка) на `en` и перезапустите сервер.
+
+#### Предпросмотр результата
+
+Когда Вы запускаете скрипт `./scripts/docs.py` с командой `live`, то будут показаны файлы и переводы для указанного языка.
+
+Но когда Вы закончите, то можете посмотреть, как это будет выглядеть по-настоящему.
+
+Для этого сначала создайте всю документацию:
+
+
+
+```console
+// Используйте команду "build-all", это займёт немного времени
+$ python ./scripts/docs.py build-all
+
+Updating es
+Updating en
+Building docs for: en
+Building docs for: es
+Successfully built docs for: es
+Copying en index.md to README.md
+```
+
+
+
+Скрипт сгенерирует `./docs_build/` для каждого языка. Он добавит все файлы с отсутствующими переводами с пометкой о том, что "у этого файла еще нет перевода". Но Вам не нужно ничего делать с этим каталогом.
+
+Затем он создаст независимые сайты MkDocs для каждого языка, объединит их и сгенерирует конечный результат на `./site/`.
+
+После чего Вы сможете запустить сервер со всеми языками командой `serve`:
+
+
+
+```console
+// Используйте команду "serve" после того, как отработает команда "build-all"
+$ python ./scripts/docs.py serve
+
+Warning: this is a very simple server. For development, use mkdocs serve instead.
+This is here only to preview a site with translations already built.
+Make sure you run the build-all command first.
+Serving at: http://127.0.0.1:8008
+```
+
+
+
+## Тесты
+
+Также в репозитории есть скрипт, который Вы можете запустить локально, чтобы протестировать весь код и сгенерировать отчеты о покрытии тестами в HTML:
+
+
+
+Эта команда создаст директорию `./htmlcov/`, в которой будет файл `./htmlcov/index.html`. Открыв его в Вашем браузере, Вы можете в интерактивном режиме изучить, все ли части кода охвачены тестами.
diff --git a/docs/ru/docs/fastapi-people.md b/docs/ru/docs/fastapi-people.md
new file mode 100644
index 000000000..64ae66a03
--- /dev/null
+++ b/docs/ru/docs/fastapi-people.md
@@ -0,0 +1,180 @@
+
+# Люди, поддерживающие FastAPI
+
+У FastAPI замечательное сообщество, которое доброжелательно к людям с любым уровнем знаний.
+
+## Создатель и хранитель
+
+Ку! 👋
+
+Это я:
+
+{% if people %}
+
+{% endif %}
+
+Я создал и продолжаю поддерживать **FastAPI**. Узнать обо мне больше можно тут [Помочь FastAPI - Получить помощь - Связаться с автором](help-fastapi.md#connect-with-the-author){.internal-link target=_blank}.
+
+... но на этой странице я хочу показать вам наше сообщество.
+
+---
+
+**FastAPI** получает огромную поддержку от своего сообщества. И я хочу отметить вклад его участников.
+
+Это люди, которые:
+
+* [Помогают другим с их проблемами (вопросами) на GitHub](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank}.
+* [Создают пул-реквесты](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}.
+* Делают ревью пул-реквестов, [что особенно важно для переводов на другие языки](contributing.md#translations){.internal-link target=_blank}.
+
+Поаплодируем им! 👏 🙇
+
+## Самые активные участники за прошедший месяц
+
+Эти участники [оказали наибольшую помощь другим с решением их проблем (вопросов) на GitHub](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank} в течение последнего месяца. ☕
+
+{% if people %}
+
+{% endif %}
+
+## Эксперты
+
+Здесь представлены **Эксперты FastAPI**. 🤓
+
+Эти участники [оказали наибольшую помощь другим с решением их проблем (вопросов) на GitHub](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank} за *всё время*.
+
+Оказывая помощь многим другим, они подтвердили свой уровень знаний. ✨
+
+{% if people %}
+
+{% endif %}
+
+## Рейтинг участников, внёсших вклад в код
+
+Здесь представлен **Рейтинг участников, внёсших вклад в код**. 👷
+
+Эти люди [сделали наибольшее количество пул-реквестов](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}, *включённых в основной код*.
+
+Они сделали наибольший вклад в исходный код, документацию, переводы и т.п. 📦
+
+{% if people %}
+
+{% endif %}
+
+На самом деле таких людей довольно много (более сотни), вы можете увидеть всех на этой странице FastAPI GitHub Contributors page. 👷
+
+## Рейтинг ревьюеров
+
+Здесь представлен **Рейтинг ревьюеров**. 🕵️
+
+### Проверки переводов на другие языки
+
+Я знаю не очень много языков (и не очень хорошо 😅).
+Итак, ревьюеры - это люди, которые могут [**подтвердить предложенный вами перевод** документации](contributing.md#translations){.internal-link target=_blank}. Без них не было бы документации на многих языках.
+
+---
+
+В **Рейтинге ревьюеров** 🕵️ представлены те, кто проверил наибольшее количество пул-реквестов других участников, обеспечивая качество кода, документации и, особенно, **переводов на другие языки**.
+
+{% if people %}
+
+
+{% endfor %}
+{% endif %}
+
+## О данных - технические детали
+
+Основная цель этой страницы - подчеркнуть усилия сообщества по оказанию помощи другим.
+
+Особенно это касается усилий, которые обычно менее заметны и во многих случаях более трудоемки, таких как помощь другим в решении проблем и проверка пул-реквестов с переводами.
+
+Данные рейтинги подсчитываются каждый месяц, ознакомиться с тем, как это работает можно тут.
+
+Кроме того, я также подчеркиваю вклад спонсоров.
+
+И я оставляю за собой право обновлять алгоритмы подсчёта, виды рейтингов, пороговые значения и т.д. (так, на всякий случай 🤷).
diff --git a/docs/ru/docs/help-fastapi.md b/docs/ru/docs/help-fastapi.md
new file mode 100644
index 000000000..a69e37bd8
--- /dev/null
+++ b/docs/ru/docs/help-fastapi.md
@@ -0,0 +1,257 @@
+# Помочь FastAPI - Получить помощь
+
+Нравится ли Вам **FastAPI**?
+
+Хотели бы Вы помочь FastAPI, его пользователям и автору?
+
+Может быть у Вас возникли трудности с **FastAPI** и Вам нужна помощь?
+
+Есть несколько очень простых способов оказания помощи (иногда достаточно всего лишь одного или двух кликов).
+
+И также есть несколько способов получить помощь.
+
+## Подписаться на новостную рассылку
+
+Вы можете подписаться на редкую [новостную рассылку **FastAPI и его друзья**](/newsletter/){.internal-link target=_blank} и быть в курсе о:
+
+* Новостях о FastAPI и его друзьях 🚀
+* Руководствах 📝
+* Возможностях ✨
+* Исправлениях 🚨
+* Подсказках и хитростях ✅
+
+## Подписаться на FastAPI в Twitter
+
+Подписаться на @fastapi в **Twitter** для получения наисвежайших новостей о **FastAPI**. 🐦
+
+## Добавить **FastAPI** звезду на GitHub
+
+Вы можете добавить FastAPI "звезду" на GitHub (кликнуть на кнопку звезды в верхнем правом углу экрана): https://github.com/tiangolo/fastapi. ⭐️
+
+Чем больше звёзд, тем легче другим пользователям найти нас и увидеть, что проект уже стал полезным для многих.
+
+## Отслеживать свежие выпуски в репозитории на GitHub
+
+Вы можете "отслеживать" FastAPI на GitHub (кликните по кнопке "watch" наверху справа): https://github.com/tiangolo/fastapi. 👀
+
+Там же Вы можете указать в настройках - "Releases only".
+
+С такой настройкой Вы будете получать уведомления на вашу электронную почту каждый раз, когда появится новый релиз (новая версия) **FastAPI** с исправлениями ошибок и новыми возможностями.
+
+## Связаться с автором
+
+Можно связаться со мной (Себястьян Рамирез / `tiangolo`), автором FastAPI.
+
+Вы можете:
+
+* Подписаться на меня на **GitHub**.
+ * Посмотреть другие мои проекты с открытым кодом, которые могут быть полезны Вам.
+ * Подписавшись на меня Вы сможете получать уведомления, что я создал новый проект с открытым кодом,.
+* Подписаться на меня в **Twitter** или в Mastodon.
+ * Поделиться со мной, как Вы используете FastAPI (я обожаю читать про это).
+ * Получать уведомления, когда я делаю объявления и представляю новые инструменты.
+ * Вы также можете подписаться на @fastapi в Twitter (это отдельный аккаунт).
+* Подписаться на меня в **Linkedin**.
+ * Получать уведомления, когда я делаю объявления и представляю новые инструменты (правда чаще всего я использую Twitter 🤷♂).
+* Читать, что я пишу (или подписаться на меня) в **Dev.to** или в **Medium**.
+ * Читать другие идеи, статьи и читать об инструментах созданных мной.
+ * Подпишитесь на меня, чтобы прочитать, когда я опубликую что-нибудь новое.
+
+## Оставить сообщение в Twitter о **FastAPI**
+
+Оставьте сообщение в Twitter о **FastAPI** и позвольте мне и другим узнать - почему он Вам нравится. 🎉
+
+Я люблю узнавать о том, как **FastAPI** используется, что Вам понравилось в нём, в каких проектах/компаниях Вы используете его и т.п.
+
+## Оставить голос за FastAPI
+
+* Голосуйте за **FastAPI** в Slant.
+* Голосуйте за **FastAPI** в AlternativeTo.
+* Расскажите, как Вы используете **FastAPI** на StackShare.
+
+## Помочь другим с их проблемами на GitHub
+
+Вы можете посмотреть, какие проблемы испытывают другие люди и попытаться помочь им. Чаще всего это вопросы, на которые, весьма вероятно, Вы уже знаете ответ. 🤓
+
+Если Вы будете много помогать людям с решением их проблем, Вы можете стать официальным [Экспертом FastAPI](fastapi-people.md#experts){.internal-link target=_blank}. 🎉
+
+Только помните, самое важное при этом - доброта. Столкнувшись с проблемой, люди расстраиваются и часто задают вопросы не лучшим образом, но постарайтесь быть максимально доброжелательным. 🤗
+
+Идея сообщества **FastAPI** в том, чтобы быть добродушным и гостеприимными. Не допускайте издевательств или неуважительного поведения по отношению к другим. Мы должны заботиться друг о друге.
+
+---
+
+Как помочь другим с их проблемами:
+
+### Понять вопрос
+
+* Удостоверьтесь, что поняли **цель** и обстоятельства случая вопрошающего.
+
+* Затем проверьте, что вопрос (в подавляющем большинстве - это вопросы) Вам **ясен**.
+
+* Во многих случаях вопрос касается решения, которое пользователь придумал сам, но может быть и решение **получше**. Если Вы поймёте проблему и обстоятельства случая, то сможете предложить **альтернативное решение**.
+
+* Ежели вопрос Вам непонятен, запросите больше **деталей**.
+
+### Воспроизвести проблему
+
+В большинстве случаев есть что-то связанное с **исходным кодом** вопрошающего.
+
+И во многих случаях будет предоставлен только фрагмент этого кода, которого недостаточно для **воспроизведения проблемы**.
+
+* Попросите предоставить минимальный воспроизводимый пример, который можно **скопировать** и запустить локально дабы увидеть такую же ошибку, или поведение, или лучше понять обстоятельства случая.
+
+* Если на Вас нахлынуло великодушие, то можете попытаться **создать похожий пример** самостоятельно, основываясь только на описании проблемы. Но имейте в виду, что это может занять много времени и, возможно, стоит сначала позадавать вопросы для прояснения проблемы.
+
+### Предложить решение
+
+* После того как Вы поняли вопрос, Вы можете дать **ответ**.
+
+* Следует понять **основную проблему и обстоятельства случая**, потому что может быть решение лучше, чем то, которое пытались реализовать.
+
+### Попросить закрыть проблему
+
+Если Вам ответили, высоки шансы, что Вам удалось решить проблему, поздравляю, **Вы - герой**! 🦸
+
+* В таком случае, если вопрос решён, попросите **закрыть проблему**.
+
+## Отслеживать репозиторий на GitHub
+
+Вы можете "отслеживать" FastAPI на GitHub (кликните по кнопке "watch" наверху справа): https://github.com/tiangolo/fastapi. 👀
+
+Если Вы выберете "Watching" вместо "Releases only", то будете получать уведомления когда кто-либо попросит о помощи с решением его проблемы.
+
+Тогда Вы можете попробовать решить эту проблему.
+
+## Запросить помощь с решением проблемы
+
+Вы можете создать новый запрос с просьбой о помощи в репозитории на GitHub, например:
+
+* Задать **вопрос** или попросить помощи в решении **проблемы**.
+* Предложить новое **улучшение**.
+
+**Заметка**: Если Вы создаёте подобные запросы, то я попрошу Вас также оказывать аналогичную помощь другим. 😉
+
+## Проверять пул-реквесты
+
+Вы можете помочь мне проверять пул-реквесты других участников.
+
+И повторюсь, постарайтесь быть доброжелательным. 🤗
+
+---
+
+О том, что нужно иметь в виду при проверке пул-реквестов:
+
+### Понять проблему
+
+* Во-первых, убедитесь, что **поняли проблему**, которую пул-реквест пытается решить. Для этого может потребоваться продолжительное обсуждение.
+
+* Также есть вероятность, что пул-реквест не актуален, так как проблему можно решить **другим путём**. В таком случае Вы можете указать на этот факт.
+
+### Не переживайте о стиле
+
+* Не стоит слишком беспокоиться о таких вещах, как стиль сообщений в коммитах или количество коммитов. При слиянии пул-реквеста с основной веткой, я буду сжимать и настраивать всё вручную.
+
+* Также не беспокойтесь о правилах стиля, для проверки сего есть автоматизированные инструменты.
+
+И если всё же потребуется какой-то другой стиль, я попрошу Вас об этом напрямую или добавлю сам коммиты с необходимыми изменениями.
+
+### Проверить код
+
+* Проверьте и прочитайте код, посмотрите, какой он имеет смысл, **запустите его локально** и посмотрите, действительно ли он решает поставленную задачу.
+
+* Затем, используя **комментарий**, сообщите, что Вы сделали проверку, тогда я буду знать, что Вы действительно проверили код.
+
+!!! Информация
+ К сожалению, я не могу так просто доверять пул-реквестам, у которых уже есть несколько одобрений.
+
+ Бывали случаи, что пул-реквесты имели 3, 5 или больше одобрений, вероятно из-за привлекательного описания, но когда я проверял эти пул-реквесты, они оказывались сломаны, содержали ошибки или вовсе не решали проблему, которую, как они утверждали, должны были решить. 😅
+
+ Потому это действительно важно - проверять и запускать код, и комментарием уведомлять меня, что Вы проделали эти действия. 🤓
+
+* Если Вы считаете, что пул-реквест можно упростить, то можете попросить об этом, но не нужно быть слишком придирчивым, может быть много субъективных точек зрения (и у меня тоже будет своя 🙈), поэтому будет лучше, если Вы сосредоточитесь на фундаментальных вещах.
+
+### Тестировать
+
+* Помогите мне проверить, что у пул-реквеста есть **тесты**.
+
+* Проверьте, что тесты **падали** до пул-реквеста. 🚨
+
+* Затем проверьте, что тесты **не валятся** после пул-реквеста. ✅
+
+* Многие пул-реквесты не имеют тестов, Вы можете **напомнить** о необходимости добавления тестов или даже **предложить** какие-либо свои тесты. Это одна из тех вещей, которые отнимают много времени и Вы можете помочь с этим.
+
+* Затем добавьте комментарий, что Вы испробовали в ходе проверки. Таким образом я буду знать, как Вы произвели проверку. 🤓
+
+## Создать пул-реквест
+
+Вы можете [сделать вклад](contributing.md){.internal-link target=_blank} в код фреймворка используя пул-реквесты, например:
+
+* Исправить опечатку, которую Вы нашли в документации.
+* Поделиться статьёй, видео или подкастом о FastAPI, которые Вы создали или нашли изменив этот файл.
+ * Убедитесь, что Вы добавили свою ссылку в начало соответствующего раздела.
+* Помочь с [переводом документации](contributing.md#translations){.internal-link target=_blank} на Ваш язык.
+ * Вы также можете проверять переводы сделанные другими.
+* Предложить новые разделы документации.
+* Исправить существующуе проблемы/баги.
+ * Убедитесь, что добавили тесты.
+* Добавить новую возможность.
+ * Убедитесь, что добавили тесты.
+ * Убедитесь, что добавили документацию, если она необходима.
+
+## Помочь поддерживать FastAPI
+
+Помогите мне поддерживать **FastAPI**! 🤓
+
+Предстоит ещё много работы и, по большей части, **ВЫ** можете её сделать.
+
+Основные задачи, которые Вы можете выполнить прямо сейчас:
+
+* [Помочь другим с их проблемами на GitHub](#help-others-with-issues-in-github){.internal-link target=_blank} (смотрите вышестоящую секцию).
+* [Проверить пул-реквесты](#review-pull-requests){.internal-link target=_blank} (смотрите вышестоящую секцию).
+
+Эти две задачи **отнимают больше всего времени**. Это основная работа по поддержке FastAPI.
+
+Если Вы можете помочь мне с этим, **Вы помогаете поддерживать FastAPI** и следить за тем, чтобы он продолжал **развиваться быстрее и лучше**. 🚀
+
+## Подключиться к чату
+
+Подключайтесь к 👥 чату в Discord 👥 и общайтесь с другими участниками сообщества FastAPI.
+
+!!! Подсказка
+ Вопросы по проблемам с фреймворком лучше задавать в GitHub issues, так больше шансов, что Вы получите помощь от [Экспертов FastAPI](fastapi-people.md#experts){.internal-link target=_blank}.
+
+ Используйте этот чат только для бесед на отвлечённые темы.
+
+Существует также чат в Gitter, но поскольку в нем нет каналов и расширенных функций, общение в нём сложнее, потому рекомендуемой системой является Discord.
+
+### Не использовать чаты для вопросов
+
+Имейте в виду, что чаты позволяют больше "свободного общения", потому там легко задавать вопросы, которые слишком общие и на которые труднее ответить, так что Вы можете не получить нужные Вам ответы.
+
+В разделе "проблемы" на GitHub, есть шаблон, который поможет Вам написать вопрос правильно, чтобы Вам было легче получить хороший ответ или даже решить проблему самостоятельно, прежде чем Вы зададите вопрос. В GitHub я могу быть уверен, что всегда отвечаю на всё, даже если это займет какое-то время. И я не могу сделать то же самое в чатах. 😅
+
+Кроме того, общение в чатах не так легкодоступно для поиска, как в GitHub, потому вопросы и ответы могут потеряться среди другого общения. И только проблемы решаемые на GitHub учитываются в получении лычки [Эксперт FastAPI](fastapi-people.md#experts){.internal-link target=_blank}, так что весьма вероятно, что Вы получите больше внимания на GitHub.
+
+С другой стороны, в чатах тысячи пользователей, а значит есть большие шансы в любое время найти там кого-то, с кем можно поговорить. 😄
+
+## Спонсировать автора
+
+Вы также можете оказать мне финансовую поддержку посредством спонсорства через GitHub.
+
+Там можно просто купить мне кофе ☕️ в знак благодарности. 😄
+
+А ещё Вы можете стать Серебряным или Золотым спонсором для FastAPI. 🏅🎉
+
+## Спонсировать инструменты, на которых зиждется мощь FastAPI
+
+Как Вы могли заметить в документации, FastAPI опирается на плечи титанов: Starlette и Pydantic.
+
+Им тоже можно оказать спонсорскую поддержку:
+
+* Samuel Colvin (Pydantic)
+* Encode (Starlette, Uvicorn)
+
+---
+
+Благодарствую! 🚀
diff --git a/docs/ru/docs/history-design-future.md b/docs/ru/docs/history-design-future.md
new file mode 100644
index 000000000..2a5e428b1
--- /dev/null
+++ b/docs/ru/docs/history-design-future.md
@@ -0,0 +1,77 @@
+# История создания и дальнейшее развитие
+
+Однажды, один из пользователей **FastAPI** задал вопрос:
+
+> Какова история этого проекта? Создаётся впечатление, что он явился из ниоткуда и завоевал мир за несколько недель [...]
+
+Что ж, вот небольшая часть истории проекта.
+
+## Альтернативы
+
+В течение нескольких лет я, возглавляя различные команды разработчиков, создавал довольно сложные API для машинного обучения, распределённых систем, асинхронных задач, баз данных NoSQL и т.д.
+
+В рамках работы над этими проектами я исследовал, проверял и использовал многие фреймворки.
+
+Во многом история **FastAPI** - история его предшественников.
+
+Как написано в разделе [Альтернативы](alternatives.md){.internal-link target=_blank}:
+
+
+
+**FastAPI** не существовал бы, если б не было более ранних работ других людей.
+
+Они создали большое количество инструментов, которые и вдохновили меня на создание **FastAPI**.
+
+Я всячески избегал создания нового фреймворка в течение нескольких лет. Сначала я пытался собрать все нужные возможности, которые ныне есть в **FastAPI**, используя множество различных фреймворков, плагинов и инструментов.
+
+Но в какой-то момент не осталось другого выбора, кроме как создать что-то, что предоставляло бы все эти возможности сразу. Взять самые лучшие идеи из предыдущих инструментов и, используя введённые в Python подсказки типов (которых не было до версии 3.6), объединить их.
+
+
+
+## Исследования
+
+Благодаря опыту использования существующих альтернатив, мы с коллегами изучили их основные идеи и скомбинировали собранные знания наилучшим образом.
+
+Например, стало ясно, что необходимо брать за основу стандартные подсказки типов Python, а самым лучшим подходом является использование уже существующих стандартов.
+
+Итак, прежде чем приступить к написанию **FastAPI**, я потратил несколько месяцев на изучение OpenAPI, JSON Schema, OAuth2, и т.п. для понимания их взаимосвязей, совпадений и различий.
+
+## Дизайн
+
+Затем я потратил некоторое время на придумывание "API" разработчика, который я хотел иметь как пользователь (как разработчик, использующий FastAPI).
+
+Я проверил несколько идей на самых популярных редакторах кода среди Python-разработчиков: PyCharm, VS Code, Jedi.
+
+Данные по редакторам я взял из опроса Python-разработчиков, который охватываает около 80% пользователей.
+
+Это означает, что **FastAPI** был специально проверен на редакторах, используемых 80% Python-разработчиками. И поскольку большинство других редакторов, как правило, работают аналогичным образом, все его преимущества должны работать практически для всех редакторов.
+
+Таким образом, я смог найти наилучшие способы сократить дублирование кода, обеспечить повсеместное автодополнение, проверку типов и ошибок и т.д.
+
+И все это, чтобы все пользователи могли получать наилучший опыт разработки.
+
+## Зависимости
+
+Протестировав несколько вариантов, я решил, что в качестве основы буду использовать **Pydantic** и его преимущества.
+
+По моим предложениям был изменён код этого фреймворка, чтобы сделать его полностью совместимым с JSON Schema, поддержать различные способы определения ограничений и улучшить помощь редакторов (проверки типов, автозаполнение).
+
+В то же время, я принимал участие в разработке **Starlette**, ещё один из основных компонентов FastAPI.
+
+## Разработка
+
+К тому времени, когда я начал создавать **FastAPI**, большинство необходимых деталей уже существовало, дизайн был определён, зависимости и прочие инструменты были готовы, а знания о стандартах и спецификациях были четкими и свежими.
+
+## Будущее
+
+Сейчас уже ясно, что **FastAPI** со своими идеями стал полезен многим людям.
+
+При сравнении с альтернативами, выбор падает на него, поскольку он лучше подходит для множества вариантов использования.
+
+Многие разработчики и команды уже используют **FastAPI** в своих проектах (включая меня и мою команду).
+
+Но, тем не менее, грядёт добавление ещё многих улучшений и возможностей.
+
+У **FastAPI** великое будущее.
+
+И [ваш вклад в это](help-fastapi.md){.internal-link target=_blank} - очень ценнен.
diff --git a/docs/ru/docs/project-generation.md b/docs/ru/docs/project-generation.md
new file mode 100644
index 000000000..76253d6f2
--- /dev/null
+++ b/docs/ru/docs/project-generation.md
@@ -0,0 +1,84 @@
+# Генераторы проектов - Шаблоны
+
+Чтобы начать работу быстрее, Вы можете использовать "генераторы проектов", в которые включены множество начальных настроек для функций безопасности, баз данных и некоторые эндпоинты API.
+
+В генераторе проектов всегда будут предустановлены какие-то настройки, которые Вам следует обновить и подогнать под свои нужды, но это может быть хорошей отправной точкой для Вашего проекта.
+
+## Full Stack FastAPI PostgreSQL
+
+GitHub: https://github.com/tiangolo/full-stack-fastapi-postgresql
+
+### Full Stack FastAPI PostgreSQL - Особенности
+
+* Полностью интегрирован с **Docker** (основан на Docker).
+* Развёртывается в режиме Docker Swarm.
+* Интегрирован с **Docker Compose** и оптимизирован для локальной разработки.
+* **Готовый к реальной работе** веб-сервер Python использующий Uvicorn и Gunicorn.
+* Бэкенд построен на фреймворке **FastAPI**:
+ * **Быстрый**: Высокопроизводительный, на уровне **NodeJS** и **Go** (благодаря Starlette и Pydantic).
+ * **Интуитивно понятный**: Отличная поддержка редактора. Автодополнение кода везде. Меньше времени на отладку.
+ * **Простой**: Разработан так, чтоб быть простым в использовании и изучении. Меньше времени на чтение документации.
+ * **Лаконичный**: Минимизировано повторение кода. Каждый объявленный параметр определяет несколько функций.
+ * **Надёжный**: Получите готовый к работе код. С автоматической интерактивной документацией.
+ * **Стандартизированный**: Основан на открытых стандартах API (OpenAPI и JSON Schema) и полностью совместим с ними.
+ * **Множество других возможностей** включая автоматическую проверку и сериализацию данных, интерактивную документацию, аутентификацию с помощью OAuth2 JWT-токенов и т.д.
+* **Безопасное хранение паролей**, которые хэшируются по умолчанию.
+* Аутентификация посредством **JWT-токенов**.
+* Модели **SQLAlchemy** (независящие от расширений Flask, а значит могут быть непосредственно использованы процессами Celery).
+* Базовая модель пользователя (измените или удалите её по необходимости).
+* **Alembic** для организации миграций.
+* **CORS** (Совместное использование ресурсов из разных источников).
+* **Celery**, процессы которого могут выборочно импортировать и использовать модели и код из остальной части бэкенда.
+* Тесты, на основе **Pytest**, интегрированные в Docker, чтобы Вы могли полностью проверить Ваше API, независимо от базы данных. Так как тесты запускаются в Docker, для них может создаваться новое хранилище данных каждый раз (Вы можете, по своему желанию, использовать ElasticSearch, MongoDB, CouchDB или другую СУБД, только лишь для проверки - будет ли Ваше API работать с этим хранилищем).
+* Простая интеграция Python с **Jupyter Kernels** для разработки удалённо или в Docker с расширениями похожими на Atom Hydrogen или Visual Studio Code Jupyter.
+* Фронтенд построен на фреймворке **Vue**:
+ * Сгенерирован с помощью Vue CLI.
+ * Поддерживает **аутентификацию с помощью JWT-токенов**.
+ * Страница логина.
+ * Перенаправление на страницу главной панели мониторинга после логина.
+ * Главная страница мониторинга с возможностью создания и изменения пользователей.
+ * Пользователь может изменять свои данные.
+ * **Vuex**.
+ * **Vue-router**.
+ * **Vuetify** для конструирования красивых компонентов страниц.
+ * **TypeScript**.
+ * Сервер Docker основан на **Nginx** (настроен для удобной работы с Vue-router).
+ * Многоступенчатая сборка Docker, то есть Вам не нужно сохранять или коммитить скомпилированный код.
+ * Тесты фронтенда запускаются во время сборки (можно отключить).
+ * Сделан настолько модульно, насколько возможно, поэтому работает "из коробки", но Вы можете повторно сгенерировать фронтенд с помощью Vue CLI или создать то, что Вам нужно и повторно использовать то, что захотите.
+* **PGAdmin** для СУБД PostgreSQL, которые легко можно заменить на PHPMyAdmin и MySQL.
+* **Flower** для отслеживания работы Celery.
+* Балансировка нагрузки между фронтендом и бэкендом с помощью **Traefik**, а значит, Вы можете расположить их на одном домене, разделив url-пути, так как они обслуживаются разными контейнерами.
+* Интеграция с Traefik включает автоматическую генерацию сертификатов Let's Encrypt для поддержки протокола **HTTPS**.
+* GitLab **CI** (непрерывная интеграция), которая включает тестирование фронтенда и бэкенда.
+
+## Full Stack FastAPI Couchbase
+
+GitHub: https://github.com/tiangolo/full-stack-fastapi-couchbase
+
+⚠️ **ПРЕДУПРЕЖДЕНИЕ** ⚠️
+
+Если Вы начинаете новый проект, ознакомьтесь с представленными здесь альтернативами.
+
+Например, генератор проектов Full Stack FastAPI PostgreSQL может быть более подходящей альтернативой, так как он активно поддерживается и используется. И он включает в себя все новые возможности и улучшения.
+
+Но никто не запрещает Вам использовать генератор с СУБД Couchbase, возможно, он всё ещё работает нормально. Или у Вас уже есть проект, созданный с помощью этого генератора ранее, и Вы, вероятно, уже обновили его в соответствии со своими потребностями.
+
+Вы можете прочитать о нём больше в документации соответствующего репозитория.
+
+## Full Stack FastAPI MongoDB
+
+...может быть когда-нибудь появится, в зависимости от наличия у меня свободного времени и прочих факторов. 😅 🎉
+
+## Модели машинного обучения на основе spaCy и FastAPI
+
+GitHub: https://github.com/microsoft/cookiecutter-spacy-fastapi
+
+### Модели машинного обучения на основе spaCy и FastAPI - Особенности
+
+* Интеграция с моделями **spaCy** NER.
+* Встроенный формат запросов к **когнитивному поиску Azure**.
+* **Готовый к реальной работе** веб-сервер Python использующий Uvicorn и Gunicorn.
+* Встроенное развёртывание на основе **Azure DevOps** Kubernetes (AKS) CI/CD.
+* **Многоязычность**. Лёгкий выбор одного из встроенных в spaCy языков во время настройки проекта.
+* **Легко подключить** модели из других фреймворков (Pytorch, Tensorflow) не ограничиваясь spaCy.
diff --git a/docs/ru/docs/tutorial/background-tasks.md b/docs/ru/docs/tutorial/background-tasks.md
index e608f6c8f..81efda786 100644
--- a/docs/ru/docs/tutorial/background-tasks.md
+++ b/docs/ru/docs/tutorial/background-tasks.md
@@ -57,16 +57,16 @@
**FastAPI** знает, что нужно сделать в каждом случае и как переиспользовать тот же объект `BackgroundTasks`, так чтобы все фоновые задачи собрались и запустились вместе в фоне:
-=== "Python 3.6 и выше"
+=== "Python 3.10+"
- ```Python hl_lines="13 15 22 25"
- {!> ../../../docs_src/background_tasks/tutorial002.py!}
+ ```Python hl_lines="11 13 20 23"
+ {!> ../../../docs_src/background_tasks/tutorial002_py310.py!}
```
-=== "Python 3.10 и выше"
+=== "Python 3.6+"
- ```Python hl_lines="11 13 20 23"
- {!> ../../../docs_src/background_tasks/tutorial002_py310.py!}
+ ```Python hl_lines="13 15 22 25"
+ {!> ../../../docs_src/background_tasks/tutorial002.py!}
```
В этом примере сообщения будут записаны в `log.txt` *после* того, как ответ сервера был отправлен.
diff --git a/docs/ru/docs/tutorial/body-fields.md b/docs/ru/docs/tutorial/body-fields.md
new file mode 100644
index 000000000..674b8bde4
--- /dev/null
+++ b/docs/ru/docs/tutorial/body-fields.md
@@ -0,0 +1,69 @@
+# Body - Поля
+
+Таким же способом, как вы объявляете дополнительную валидацию и метаданные в параметрах *функции обработки пути* с помощью функций `Query`, `Path` и `Body`, вы можете объявлять валидацию и метаданные внутри Pydantic моделей, используя функцию `Field` из Pydantic.
+
+## Импорт `Field`
+
+Сначала вы должны импортировать его:
+
+=== "Python 3.10+"
+
+ ```Python hl_lines="2"
+ {!> ../../../docs_src/body_fields/tutorial001_py310.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="4"
+ {!> ../../../docs_src/body_fields/tutorial001.py!}
+ ```
+
+!!! warning "Внимание"
+ Обратите внимание, что функция `Field` импортируется непосредственно из `pydantic`, а не из `fastapi`, как все остальные функции (`Query`, `Path`, `Body` и т.д.).
+
+## Объявление атрибутов модели
+
+Вы можете использовать функцию `Field` с атрибутами модели:
+
+=== "Python 3.10+"
+
+ ```Python hl_lines="9-12"
+ {!> ../../../docs_src/body_fields/tutorial001_py310.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="11-14"
+ {!> ../../../docs_src/body_fields/tutorial001.py!}
+ ```
+
+Функция `Field` работает так же, как `Query`, `Path` и `Body`, у ее такие же параметры и т.д.
+
+!!! note "Технические детали"
+ На самом деле, `Query`, `Path` и другие функции, которые вы увидите в дальнейшем, создают объекты подклассов общего класса `Param`, который сам по себе является подклассом `FieldInfo` из Pydantic.
+
+ И `Field` (из Pydantic), и `Body`, оба возвращают объекты подкласса `FieldInfo`.
+
+ У класса `Body` есть и другие подклассы, с которыми вы ознакомитесь позже.
+
+ Помните, что когда вы импортируете `Query`, `Path` и другое из `fastapi`, это фактически функции, которые возвращают специальные классы.
+
+!!! tip "Подсказка"
+ Обратите внимание, что каждый атрибут модели с типом, значением по умолчанию и `Field` имеет ту же структуру, что и параметр *функции обработки пути* с `Field` вместо `Path`, `Query` и `Body`.
+
+## Добавление дополнительной информации
+
+Вы можете объявлять дополнительную информацию в `Field`, `Query`, `Body` и т.п. Она будет включена в сгенерированную JSON схему.
+
+Вы узнаете больше о добавлении дополнительной информации позже в документации, когда будете изучать, как задавать примеры принимаемых данных.
+
+
+!!! warning "Внимание"
+ Дополнительные ключи, переданные в функцию `Field`, также будут присутствовать в сгенерированной OpenAPI схеме вашего приложения.
+ Поскольку эти ключи не являются обязательной частью спецификации OpenAPI, некоторые инструменты OpenAPI, например, [валидатор OpenAPI](https://validator.swagger.io/), могут не работать с вашей сгенерированной схемой.
+
+## Резюме
+
+Вы можете использовать функцию `Field` из Pydantic, чтобы задавать дополнительную валидацию и метаданные для атрибутов модели.
+
+Вы также можете использовать дополнительные ключевые аргументы, чтобы добавить метаданные JSON схемы.
diff --git a/docs/ru/docs/tutorial/cookie-params.md b/docs/ru/docs/tutorial/cookie-params.md
new file mode 100644
index 000000000..a6f2caa26
--- /dev/null
+++ b/docs/ru/docs/tutorial/cookie-params.md
@@ -0,0 +1,49 @@
+# Параметры Cookie
+
+Вы можете задать параметры Cookie таким же способом, как `Query` и `Path` параметры.
+
+## Импорт `Cookie`
+
+Сначала импортируйте `Cookie`:
+
+=== "Python 3.10+"
+
+ ```Python hl_lines="1"
+ {!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="3"
+ {!> ../../../docs_src/cookie_params/tutorial001.py!}
+ ```
+
+## Объявление параметров `Cookie`
+
+Затем объявляйте параметры cookie, используя ту же структуру, что и с `Path` и `Query`.
+
+Первое значение - это значение по умолчанию, вы можете передать все дополнительные параметры проверки или аннотации:
+
+=== "Python 3.10+"
+
+ ```Python hl_lines="7"
+ {!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/cookie_params/tutorial001.py!}
+ ```
+
+!!! note "Технические детали"
+ `Cookie` - это класс, родственный `Path` и `Query`. Он также наследуется от общего класса `Param`.
+
+ Но помните, что когда вы импортируете `Query`, `Path`, `Cookie` и другое из `fastapi`, это фактически функции, которые возвращают специальные классы.
+
+!!! info "Дополнительная информация"
+ Для объявления cookies, вам нужно использовать `Cookie`, иначе параметры будут интерпретированы как параметры запроса.
+
+## Резюме
+
+Объявляйте cookies с помощью `Cookie`, используя тот же общий шаблон, что и `Query`, и `Path`.
diff --git a/docs/ru/docs/tutorial/extra-data-types.md b/docs/ru/docs/tutorial/extra-data-types.md
new file mode 100644
index 000000000..efcbcb38a
--- /dev/null
+++ b/docs/ru/docs/tutorial/extra-data-types.md
@@ -0,0 +1,82 @@
+# Дополнительные типы данных
+
+До сих пор вы использовали простые типы данных, такие как:
+
+* `int`
+* `float`
+* `str`
+* `bool`
+
+Но вы также можете использовать и более сложные типы.
+
+При этом у вас останутся те же возможности , что и до сих пор:
+
+* Отличная поддержка редактора.
+* Преобразование данных из входящих запросов.
+* Преобразование данных для ответа.
+* Валидация данных.
+* Автоматическая аннотация и документация.
+
+## Другие типы данных
+
+Ниже перечислены некоторые из дополнительных типов данных, которые вы можете использовать:
+
+* `UUID`:
+ * Стандартный "Универсальный уникальный идентификатор", используемый в качестве идентификатора во многих базах данных и системах.
+ * В запросах и ответах будет представлен как `str`.
+* `datetime.datetime`:
+ * Встроенный в Python `datetime.datetime`.
+ * В запросах и ответах будет представлен как `str` в формате ISO 8601, например: `2008-09-15T15:53:00+05:00`.
+* `datetime.date`:
+ * Встроенный в Python `datetime.date`.
+ * В запросах и ответах будет представлен как `str` в формате ISO 8601, например: `2008-09-15`.
+* `datetime.time`:
+ * Встроенный в Python `datetime.time`.
+ * В запросах и ответах будет представлен как `str` в формате ISO 8601, например: `14:23:55.003`.
+* `datetime.timedelta`:
+ * Встроенный в Python `datetime.timedelta`.
+ * В запросах и ответах будет представлен в виде общего количества секунд типа `float`.
+ * Pydantic также позволяет представить его как "Кодировку разницы во времени ISO 8601", см. документацию для получения дополнительной информации.
+* `frozenset`:
+ * В запросах и ответах обрабатывается так же, как и `set`:
+ * В запросах будет прочитан список, исключены дубликаты и преобразован в `set`.
+ * В ответах `set` будет преобразован в `list`.
+ * В сгенерированной схеме будет указано, что значения `set` уникальны (с помощью JSON-схемы `uniqueItems`).
+* `bytes`:
+ * Встроенный в Python `bytes`.
+ * В запросах и ответах будет рассматриваться как `str`.
+ * В сгенерированной схеме будет указано, что это `str` в формате `binary`.
+* `Decimal`:
+ * Встроенный в Python `Decimal`.
+ * В запросах и ответах обрабатывается так же, как и `float`.
+* Вы можете проверить все допустимые типы данных pydantic здесь: Типы данных Pydantic.
+
+## Пример
+
+Вот пример *операции пути* с параметрами, который демонстрирует некоторые из вышеперечисленных типов.
+
+=== "Python 3.6 и выше"
+
+ ```Python hl_lines="1 3 12-16"
+ {!> ../../../docs_src/extra_data_types/tutorial001.py!}
+ ```
+
+=== "Python 3.10 и выше"
+
+ ```Python hl_lines="1 2 11-15"
+ {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
+ ```
+
+Обратите внимание, что параметры внутри функции имеют свой естественный тип данных, и вы, например, можете выполнять обычные манипуляции с датами, такие как:
+
+=== "Python 3.6 и выше"
+
+ ```Python hl_lines="18-19"
+ {!> ../../../docs_src/extra_data_types/tutorial001.py!}
+ ```
+
+=== "Python 3.10 и выше"
+
+ ```Python hl_lines="17-18"
+ {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
+ ```
diff --git a/docs/ru/docs/tutorial/query-params-str-validations.md b/docs/ru/docs/tutorial/query-params-str-validations.md
new file mode 100644
index 000000000..68042db63
--- /dev/null
+++ b/docs/ru/docs/tutorial/query-params-str-validations.md
@@ -0,0 +1,919 @@
+# Query-параметры и валидация строк
+
+**FastAPI** позволяет определять дополнительную информацию и валидацию для ваших параметров.
+
+Давайте рассмотрим следующий пример:
+
+=== "Python 3.10+"
+
+ ```Python hl_lines="7"
+ {!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/query_params_str_validations/tutorial001.py!}
+ ```
+
+Query-параметр `q` имеет тип `Union[str, None]` (или `str | None` в Python 3.10). Это означает, что входной параметр будет типа `str`, но может быть и `None`. Ещё параметр имеет значение по умолчанию `None`, из-за чего FastAPI определит параметр как необязательный.
+
+!!! note "Технические детали"
+ FastAPI определит параметр `q` как необязательный, потому что его значение по умолчанию `= None`.
+
+ `Union` в `Union[str, None]` позволит редактору кода оказать вам лучшую поддержку и найти ошибки.
+
+## Расширенная валидация
+
+Добавим дополнительное условие валидации параметра `q` - **длина строки не более 50 символов** (условие проверяется всякий раз, когда параметр `q` не является `None`).
+
+### Импорт `Query` и `Annotated`
+
+Чтобы достичь этого, первым делом нам нужно импортировать:
+
+* `Query` из пакета `fastapi`:
+* `Annotated` из пакета `typing` (или из `typing_extensions` для Python ниже 3.9)
+
+=== "Python 3.10+"
+
+ В Python 3.9 или выше, `Annotated` является частью стандартной библиотеки, таким образом вы можете импортировать его из `typing`.
+
+ ```Python hl_lines="1 3"
+ {!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!}
+ ```
+
+=== "Python 3.6+"
+
+ В версиях Python ниже Python 3.9 `Annotation` импортируется из `typing_extensions`.
+
+ Эта библиотека будет установлена вместе с FastAPI.
+
+ ```Python hl_lines="3-4"
+ {!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!}
+ ```
+
+## `Annotated` как тип для query-параметра `q`
+
+Помните, как ранее я говорил об Annotated? Он может быть использован для добавления метаданных для ваших параметров в разделе [Введение в аннотации типов Python](../python-types.md#type-hints-with-metadata-annotations){.internal-link target=_blank}?
+
+Пришло время использовать их в FastAPI. 🚀
+
+У нас была аннотация следующего типа:
+
+=== "Python 3.10+"
+
+ ```Python
+ q: str | None = None
+ ```
+
+=== "Python 3.6+"
+
+ ```Python
+ q: Union[str, None] = None
+ ```
+
+Вот что мы получим, если обернём это в `Annotated`:
+
+=== "Python 3.10+"
+
+ ```Python
+ q: Annotated[str | None] = None
+ ```
+
+=== "Python 3.6+"
+
+ ```Python
+ q: Annotated[Union[str, None]] = None
+ ```
+
+Обе эти версии означают одно и тоже. `q` - это параметр, который может быть `str` или `None`, и по умолчанию он будет принимать `None`.
+
+Давайте повеселимся. 🎉
+
+## Добавим `Query` в `Annotated` для query-параметра `q`
+
+Теперь, когда у нас есть `Annotated`, где мы можем добавить больше метаданных, добавим `Query` со значением параметра `max_length` равным 50:
+
+=== "Python 3.10+"
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="10"
+ {!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!}
+ ```
+
+Обратите внимание, что значение по умолчанию всё ещё `None`, так что параметр остаётся необязательным.
+
+Однако теперь, имея `Query(max_length=50)` внутри `Annotated`, мы говорим FastAPI, что мы хотим извлечь это значение из параметров query-запроса (что произойдёт в любом случае 🤷), и что мы хотим иметь **дополнительные условия валидации** для этого значения (для чего мы и делаем это - чтобы получить дополнительную валидацию). 😎
+
+Теперь FastAPI:
+
+* **Валидирует** (проверяет), что полученные данные состоят максимум из 50 символов
+* Показывает **исчерпывающую ошибку** (будет описание местонахождения ошибки и её причины) для клиента в случаях, когда данные не валидны
+* **Задокументирует** параметр в схему OpenAPI *операции пути* (что будет отображено в **UI автоматической документации**)
+
+## Альтернативный (устаревший) способ задать `Query` как значение по умолчанию
+
+В предыдущих версиях FastAPI (ниже 0.95.0) необходимо было использовать `Query` как значение по умолчанию для query-параметра. Так было вместо размещения его в `Annotated`, так что велика вероятность, что вам встретится такой код. Сейчас объясню.
+
+!!! tip "Подсказка"
+ При написании нового кода и везде где это возможно, используйте `Annotated`, как было описано ранее. У этого способа есть несколько преимуществ (о них дальше) и никаких недостатков. 🍰
+
+Вот как вы могли бы использовать `Query()` в качестве значения по умолчанию параметра вашей функции, установив для параметра `max_length` значение 50:
+
+=== "Python 3.10+"
+
+ ```Python hl_lines="7"
+ {!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/query_params_str_validations/tutorial002.py!}
+ ```
+
+В таком случае (без использования `Annotated`), мы заменили значение по умолчанию с `None` на `Query()` в функции. Теперь нам нужно установить значение по умолчанию для query-параметра `Query(default=None)`, что необходимо для тех же целей, как когда ранее просто указывалось значение по умолчанию (по крайней мере, для FastAPI).
+
+Таким образом:
+
+```Python
+q: Union[str, None] = Query(default=None)
+```
+
+...делает параметр необязательным со значением по умолчанию `None`, также как это делает:
+
+```Python
+q: Union[str, None] = None
+```
+
+И для Python 3.10 и выше:
+
+```Python
+q: str | None = Query(default=None)
+```
+
+...делает параметр необязательным со значением по умолчанию `None`, также как это делает:
+
+```Python
+q: str | None = None
+```
+
+Но он явно объявляет его как query-параметр.
+
+!!! info "Дополнительная информация"
+ Запомните, важной частью объявления параметра как необязательного является:
+
+ ```Python
+ = None
+ ```
+
+ или:
+
+ ```Python
+ = Query(default=None)
+ ```
+
+ так как `None` указан в качестве значения по умолчанию, параметр будет **необязательным**.
+
+ `Union[str, None]` позволит редактору кода оказать вам лучшую поддержку. Но это не то, на что обращает внимание FastAPI для определения необязательности параметра.
+
+Теперь, мы можем указать больше параметров для `Query`. В данном случае, параметр `max_length` применяется к строкам:
+
+```Python
+q: Union[str, None] = Query(default=None, max_length=50)
+```
+
+Входные данные будут проверены. Если данные недействительны, тогда будет указано на ошибку в запросе (будет описание местонахождения ошибки и её причины). Кроме того, параметр задокументируется в схеме OpenAPI данной *операции пути*.
+
+### Использовать `Query` как значение по умолчанию или добавить в `Annotated`
+
+Когда `Query` используется внутри `Annotated`, вы не можете использовать параметр `default` у `Query`.
+
+Вместо этого, используйте обычное указание значения по умолчанию для параметра функции. Иначе, это будет несовместимо.
+
+Следующий пример не рабочий:
+
+```Python
+q: Annotated[str, Query(default="rick")] = "morty"
+```
+
+...потому что нельзя однозначно определить, что именно должно быть значением по умолчанию: `"rick"` или `"morty"`.
+
+Вам следует использовать (предпочтительно):
+
+```Python
+q: Annotated[str, Query()] = "rick"
+```
+
+...или как в старом коде, который вам может попасться:
+
+```Python
+q: str = Query(default="rick")
+```
+
+### Преимущества `Annotated`
+
+**Рекомендуется использовать `Annotated`** вместо значения по умолчанию в параметрах функции, потому что так **лучше** по нескольким причинам. 🤓
+
+Значение **по умолчанию** у **параметров функции** - это **действительно значение по умолчанию**, что более интуитивно понятно для пользователей Python. 😌
+
+Вы можете **вызвать** ту же функцию в **иных местах** без FastAPI, и она **сработает как ожидается**. Если это **обязательный** параметр (без значения по умолчанию), ваш **редактор кода** сообщит об ошибке. **Python** также укажет на ошибку, если вы вызовете функцию без передачи ей обязательного параметра.
+
+Если вы вместо `Annotated` используете **(устаревший) стиль значений по умолчанию**, тогда при вызове этой функции без FastAPI в **другом месте** вам необходимо **помнить** о передаче аргументов функции, чтобы она работала корректно. В противном случае, значения будут отличаться от тех, что вы ожидаете (например, `QueryInfo` или что-то подобное вместо `str`). И ни ваш редактор кода, ни Python не будут жаловаться на работу этой функции, только когда вычисления внутри дадут сбой.
+
+Так как `Annotated` может принимать более одной аннотации метаданных, то теперь вы можете использовать ту же функцию с другими инструментами, например Typer. 🚀
+
+## Больше валидации
+
+Вы также можете добавить параметр `min_length`:
+
+=== "Python 3.10+"
+
+ ```Python hl_lines="10"
+ {!> ../../../docs_src/query_params_str_validations/tutorial003_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="10"
+ {!> ../../../docs_src/query_params_str_validations/tutorial003_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="11"
+ {!> ../../../docs_src/query_params_str_validations/tutorial003_an.py!}
+ ```
+
+=== "Python 3.10+ без Annotated"
+
+ !!! tip "Подсказка"
+ Рекомендуется использовать версию с `Annotated` если возможно.
+
+ ```Python hl_lines="7"
+ {!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!}
+ ```
+
+=== "Python 3.6+ без Annotated"
+
+ !!! tip "Подсказка"
+ Рекомендуется использовать версию с `Annotated` если возможно.
+
+ ```Python hl_lines="10"
+ {!> ../../../docs_src/query_params_str_validations/tutorial003.py!}
+ ```
+
+## Регулярные выражения
+
+Вы можете определить регулярное выражение, которому должен соответствовать параметр:
+
+=== "Python 3.10+"
+
+ ```Python hl_lines="11"
+ {!> ../../../docs_src/query_params_str_validations/tutorial004_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="11"
+ {!> ../../../docs_src/query_params_str_validations/tutorial004_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="12"
+ {!> ../../../docs_src/query_params_str_validations/tutorial004_an.py!}
+ ```
+
+=== "Python 3.10+ без Annotated"
+
+ !!! tip "Подсказка"
+ Рекомендуется использовать версию с `Annotated` если возможно.
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!}
+ ```
+
+=== "Python 3.6+ без Annotated"
+
+ !!! tip "Подсказка"
+ Рекомендуется использовать версию с `Annotated` если возможно.
+
+ ```Python hl_lines="11"
+ {!> ../../../docs_src/query_params_str_validations/tutorial004.py!}
+ ```
+
+Данное регулярное выражение проверяет, что полученное значение параметра:
+
+* `^`: начало строки.
+* `fixedquery`: в точности содержит строку `fixedquery`.
+* `$`: конец строки, не имеет символов после `fixedquery`.
+
+Не переживайте, если **"регулярное выражение"** вызывает у вас трудности. Это достаточно сложная тема для многих людей. Вы можете сделать множество вещей без использования регулярных выражений.
+
+Но когда они вам понадобятся, и вы закончите их освоение, то не будет проблемой использовать их в **FastAPI**.
+
+## Значения по умолчанию
+
+Вы точно также можете указать любое значение `по умолчанию`, как ранее указывали `None`.
+
+Например, вы хотите для параметра запроса `q` указать, что он должен состоять минимум из 3 символов (`min_length=3`) и иметь значение по умолчанию `"fixedquery"`:
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/query_params_str_validations/tutorial005_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="8"
+ {!> ../../../docs_src/query_params_str_validations/tutorial005_an.py!}
+ ```
+
+=== "Python 3.6+ без Annotated"
+
+ !!! tip "Подсказка"
+ Рекомендуется использовать версию с `Annotated` если возможно.
+
+ ```Python hl_lines="7"
+ {!> ../../../docs_src/query_params_str_validations/tutorial005.py!}
+ ```
+
+!!! note "Технические детали"
+ Наличие значения по умолчанию делает параметр необязательным.
+
+## Обязательный параметр
+
+Когда вам не требуется дополнительная валидация или дополнительные метаданные для параметра запроса, вы можете сделать параметр `q` обязательным просто не указывая значения по умолчанию. Например:
+
+```Python
+q: str
+```
+
+вместо:
+
+```Python
+q: Union[str, None] = None
+```
+
+Но у нас query-параметр определён как `Query`. Например:
+
+=== "Annotated"
+
+ ```Python
+ q: Annotated[Union[str, None], Query(min_length=3)] = None
+ ```
+
+=== "без Annotated"
+
+ ```Python
+ q: Union[str, None] = Query(default=None, min_length=3)
+ ```
+
+В таком случае, чтобы сделать query-параметр `Query` обязательным, вы можете просто не указывать значение по умолчанию:
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/query_params_str_validations/tutorial006_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="8"
+ {!> ../../../docs_src/query_params_str_validations/tutorial006_an.py!}
+ ```
+
+=== "Python 3.6+ без Annotated"
+
+ !!! tip "Подсказка"
+ Рекомендуется использовать версию с `Annotated` если возможно.
+
+ ```Python hl_lines="7"
+ {!> ../../../docs_src/query_params_str_validations/tutorial006.py!}
+ ```
+
+ !!! tip "Подсказка"
+ Обратите внимание, что даже когда `Query()` используется как значение по умолчанию для параметра функции, мы не передаём `default=None` в `Query()`.
+
+ Лучше будет использовать версию с `Annotated`. 😉
+
+### Обязательный параметр с Ellipsis (`...`)
+
+Альтернативный способ указать обязательность параметра запроса - это указать параметр `default` через многоточие `...`:
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="8"
+ {!> ../../../docs_src/query_params_str_validations/tutorial006b_an.py!}
+ ```
+
+=== "Python 3.6+ без Annotated"
+
+ !!! tip "Подсказка"
+ Рекомендуется использовать версию с `Annotated` если возможно.
+
+ ```Python hl_lines="7"
+ {!> ../../../docs_src/query_params_str_validations/tutorial006b.py!}
+ ```
+
+!!! info "Дополнительная информация"
+ Если вы ранее не сталкивались с `...`: это специальное значение, часть языка Python и называется "Ellipsis".
+
+ Используется в Pydantic и FastAPI для определения, что значение требуется обязательно.
+
+Таким образом, **FastAPI** определяет, что параметр является обязательным.
+
+### Обязательный параметр с `None`
+
+Вы можете определить, что параметр может принимать `None`, но всё ещё является обязательным. Это может потребоваться для того, чтобы пользователи явно указали параметр, даже если его значение будет `None`.
+
+Чтобы этого добиться, вам нужно определить `None` как валидный тип для параметра запроса, но также указать `default=...`:
+
+=== "Python 3.10+"
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="10"
+ {!> ../../../docs_src/query_params_str_validations/tutorial006c_an.py!}
+ ```
+
+=== "Python 3.10+ без Annotated"
+
+ !!! tip "Подсказка"
+ Рекомендуется использовать версию с `Annotated` если возможно.
+
+ ```Python hl_lines="7"
+ {!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!}
+ ```
+
+=== "Python 3.6+ без Annotated"
+
+ !!! tip "Подсказка"
+ Рекомендуется использовать версию с `Annotated` если возможно.
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/query_params_str_validations/tutorial006c.py!}
+ ```
+
+!!! tip "Подсказка"
+ Pydantic, мощь которого используется в FastAPI для валидации и сериализации, имеет специальное поведение для `Optional` или `Union[Something, None]` без значения по умолчанию. Вы можете узнать об этом больше в документации Pydantic, раздел Обязательные Опциональные поля.
+
+### Использование Pydantic's `Required` вместо Ellipsis (`...`)
+
+Если вас смущает `...`, вы можете использовать `Required` из Pydantic:
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="4 10"
+ {!> ../../../docs_src/query_params_str_validations/tutorial006d_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="2 9"
+ {!> ../../../docs_src/query_params_str_validations/tutorial006d_an.py!}
+ ```
+
+=== "Python 3.6+ без Annotated"
+
+ !!! tip "Подсказка"
+ Рекомендуется использовать версию с `Annotated` если возможно.
+
+ ```Python hl_lines="2 8"
+ {!> ../../../docs_src/query_params_str_validations/tutorial006d.py!}
+ ```
+
+!!! tip "Подсказка"
+ Запомните, когда вам необходимо объявить query-параметр обязательным, вы можете просто не указывать параметр `default`. Таким образом, вам редко придётся использовать `...` или `Required`.
+
+## Множество значений для query-параметра
+
+Для query-параметра `Query` можно указать, что он принимает список значений (множество значений).
+
+Например, query-параметр `q` может быть указан в URL несколько раз. И если вы ожидаете такой формат запроса, то можете указать это следующим образом:
+
+=== "Python 3.10+"
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/query_params_str_validations/tutorial011_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/query_params_str_validations/tutorial011_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="10"
+ {!> ../../../docs_src/query_params_str_validations/tutorial011_an.py!}
+ ```
+
+=== "Python 3.10+ без Annotated"
+
+ !!! tip "Подсказка"
+ Рекомендуется использовать версию с `Annotated` если возможно.
+
+ ```Python hl_lines="7"
+ {!> ../../../docs_src/query_params_str_validations/tutorial011_py310.py!}
+ ```
+
+=== "Python 3.9+ без Annotated"
+
+ !!! tip "Подсказка"
+ Рекомендуется использовать версию с `Annotated` если возможно.
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!}
+ ```
+
+=== "Python 3.6+ без Annotated"
+
+ !!! tip "Подсказка"
+ Рекомендуется использовать версию с `Annotated` если возможно.
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/query_params_str_validations/tutorial011.py!}
+ ```
+
+Затем, получив такой URL:
+
+```
+http://localhost:8000/items/?q=foo&q=bar
+```
+
+вы бы получили несколько значений (`foo` и `bar`), которые относятся к параметру `q`, в виде Python `list` внутри вашей *функции обработки пути*, в *параметре функции* `q`.
+
+Таким образом, ответ на этот URL будет:
+
+```JSON
+{
+ "q": [
+ "foo",
+ "bar"
+ ]
+}
+```
+
+!!! tip "Подсказка"
+ Чтобы объявить query-параметр типом `list`, как в примере выше, вам нужно явно использовать `Query`, иначе он будет интерпретирован как тело запроса.
+
+Интерактивная документация API будет обновлена соответствующим образом, где будет разрешено множество значений:
+
+
+
+### Query-параметр со множеством значений по умолчанию
+
+Вы также можете указать тип `list` со списком значений по умолчанию на случай, если вам их не предоставят:
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/query_params_str_validations/tutorial012_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="10"
+ {!> ../../../docs_src/query_params_str_validations/tutorial012_an.py!}
+ ```
+
+=== "Python 3.9+ без Annotated"
+
+ !!! tip "Подсказка"
+ Рекомендуется использовать версию с `Annotated` если возможно.
+
+ ```Python hl_lines="7"
+ {!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!}
+ ```
+
+=== "Python 3.6+ без Annotated"
+
+ !!! tip "Подсказка"
+ Рекомендуется использовать версию с `Annotated` если возможно.
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/query_params_str_validations/tutorial012.py!}
+ ```
+
+Если вы перейдёте по ссылке:
+
+```
+http://localhost:8000/items/
+```
+
+значение по умолчанию для `q` будет: `["foo", "bar"]` и ответом для вас будет:
+
+```JSON
+{
+ "q": [
+ "foo",
+ "bar"
+ ]
+}
+```
+
+#### Использование `list`
+
+Вы также можете использовать `list` напрямую вместо `List[str]` (или `list[str]` в Python 3.9+):
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/query_params_str_validations/tutorial013_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="8"
+ {!> ../../../docs_src/query_params_str_validations/tutorial013_an.py!}
+ ```
+
+=== "Python 3.6+ без Annotated"
+
+ !!! tip "Подсказка"
+ Рекомендуется использовать версию с `Annotated` если возможно.
+
+ ```Python hl_lines="7"
+ {!> ../../../docs_src/query_params_str_validations/tutorial013.py!}
+ ```
+
+!!! note "Технические детали"
+ Запомните, что в таком случае, FastAPI не будет проверять содержимое списка.
+
+ Например, для List[int] список будет провалидирован (и задокументирован) на содержание только целочисленных элементов. Но для простого `list` такой проверки не будет.
+
+## Больше метаданных
+
+Вы можете добавить больше информации об query-параметре.
+
+Указанная информация будет включена в генерируемую OpenAPI документацию и использована в пользовательском интерфейсе и внешних инструментах.
+
+!!! note "Технические детали"
+ Имейте в виду, что разные инструменты могут иметь разные уровни поддержки OpenAPI.
+
+ Некоторые из них могут не отображать (на данный момент) всю заявленную дополнительную информацию, хотя в большинстве случаев отсутствующая функция уже запланирована к разработке.
+
+Вы можете указать название query-параметра, используя параметр `title`:
+
+=== "Python 3.10+"
+
+ ```Python hl_lines="10"
+ {!> ../../../docs_src/query_params_str_validations/tutorial007_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="10"
+ {!> ../../../docs_src/query_params_str_validations/tutorial007_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="11"
+ {!> ../../../docs_src/query_params_str_validations/tutorial007_an.py!}
+ ```
+
+=== "Python 3.10+ без Annotated"
+
+ !!! tip "Подсказка"
+ Рекомендуется использовать версию с `Annotated` если возможно.
+
+ ```Python hl_lines="8"
+ {!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!}
+ ```
+
+=== "Python 3.6+ без Annotated"
+
+ !!! tip "Подсказка"
+ Рекомендуется использовать версию с `Annotated` если возможно.
+
+ ```Python hl_lines="10"
+ {!> ../../../docs_src/query_params_str_validations/tutorial007.py!}
+ ```
+
+Добавить описание, используя параметр `description`:
+
+=== "Python 3.10+"
+
+ ```Python hl_lines="14"
+ {!> ../../../docs_src/query_params_str_validations/tutorial008_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="14"
+ {!> ../../../docs_src/query_params_str_validations/tutorial008_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="15"
+ {!> ../../../docs_src/query_params_str_validations/tutorial008_an.py!}
+ ```
+
+=== "Python 3.10+ без Annotated"
+
+ !!! tip "Подсказка"
+ Рекомендуется использовать версию с `Annotated` если возможно.
+
+ ```Python hl_lines="12"
+ {!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!}
+ ```
+
+=== "Python 3.6+ без Annotated"
+
+ !!! tip "Подсказка"
+ Рекомендуется использовать версию с `Annotated` если возможно.
+
+ ```Python hl_lines="13"
+ {!> ../../../docs_src/query_params_str_validations/tutorial008.py!}
+ ```
+
+## Псевдонимы параметров
+
+Представьте, что вы хотите использовать query-параметр с названием `item-query`.
+
+Например:
+
+```
+http://127.0.0.1:8000/items/?item-query=foobaritems
+```
+
+Но `item-query` является невалидным именем переменной в Python.
+
+Наиболее похожее валидное имя `item_query`.
+
+Но вам всё равно необходим `item-query`...
+
+Тогда вы можете объявить `псевдоним`, и этот псевдоним будет использоваться для поиска значения параметра запроса:
+
+=== "Python 3.10+"
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/query_params_str_validations/tutorial009_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/query_params_str_validations/tutorial009_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="10"
+ {!> ../../../docs_src/query_params_str_validations/tutorial009_an.py!}
+ ```
+
+=== "Python 3.10+ без Annotated"
+
+ !!! tip "Подсказка"
+ Рекомендуется использовать версию с `Annotated` если возможно.
+
+ ```Python hl_lines="7"
+ {!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!}
+ ```
+
+=== "Python 3.6+ без Annotated"
+
+ !!! tip "Подсказка"
+ Рекомендуется использовать версию с `Annotated` если возможно.
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/query_params_str_validations/tutorial009.py!}
+ ```
+
+## Устаревшие параметры
+
+Предположим, вы больше не хотите использовать какой-либо параметр.
+
+Вы решили оставить его, потому что клиенты всё ещё им пользуются. Но вы хотите отобразить это в документации как устаревший функционал.
+
+Тогда для `Query` укажите параметр `deprecated=True`:
+
+=== "Python 3.10+"
+
+ ```Python hl_lines="19"
+ {!> ../../../docs_src/query_params_str_validations/tutorial010_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="19"
+ {!> ../../../docs_src/query_params_str_validations/tutorial010_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="20"
+ {!> ../../../docs_src/query_params_str_validations/tutorial010_an.py!}
+ ```
+
+=== "Python 3.10+ без Annotated"
+
+ !!! tip "Подсказка"
+ Рекомендуется использовать версию с `Annotated` если возможно.
+
+ ```Python hl_lines="17"
+ {!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!}
+ ```
+
+=== "Python 3.6+ без Annotated"
+
+ !!! tip "Подсказка"
+ Рекомендуется использовать версию с `Annotated` если возможно.
+
+ ```Python hl_lines="18"
+ {!> ../../../docs_src/query_params_str_validations/tutorial010.py!}
+ ```
+
+В документации это будет отображено следующим образом:
+
+
+
+## Исключить из OpenAPI
+
+Чтобы исключить query-параметр из генерируемой OpenAPI схемы (а также из системы автоматической генерации документации), укажите в `Query` параметр `include_in_schema=False`:
+
+=== "Python 3.10+"
+
+ ```Python hl_lines="10"
+ {!> ../../../docs_src/query_params_str_validations/tutorial014_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="10"
+ {!> ../../../docs_src/query_params_str_validations/tutorial014_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="11"
+ {!> ../../../docs_src/query_params_str_validations/tutorial014_an.py!}
+ ```
+
+=== "Python 3.10+ без Annotated"
+
+ !!! tip "Подсказка"
+ Рекомендуется использовать версию с `Annotated` если возможно.
+
+ ```Python hl_lines="8"
+ {!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!}
+ ```
+
+=== "Python 3.6+ без Annotated"
+
+ !!! tip "Подсказка"
+ Рекомендуется использовать версию с `Annotated` если возможно.
+
+ ```Python hl_lines="10"
+ {!> ../../../docs_src/query_params_str_validations/tutorial014.py!}
+ ```
+
+## Резюме
+
+Вы можете объявлять дополнительные правила валидации и метаданные для ваших параметров запроса.
+
+Общие метаданные:
+
+* `alias`
+* `title`
+* `description`
+* `deprecated`
+* `include_in_schema`
+
+Специфичные правила валидации для строк:
+
+* `min_length`
+* `max_length`
+* `regex`
+
+В рассмотренных примерах показано объявление правил валидации для строковых значений `str`.
+
+В следующих главах вы увидете, как объявлять правила валидации для других типов (например, чисел).
diff --git a/docs/ru/docs/tutorial/response-status-code.md b/docs/ru/docs/tutorial/response-status-code.md
new file mode 100644
index 000000000..b2f9b7704
--- /dev/null
+++ b/docs/ru/docs/tutorial/response-status-code.md
@@ -0,0 +1,89 @@
+# HTTP коды статуса ответа
+
+Вы можете задать HTTP код статуса ответа с помощью параметра `status_code` подобно тому, как вы определяете схему ответа в любой из *операций пути*:
+
+* `@app.get()`
+* `@app.post()`
+* `@app.put()`
+* `@app.delete()`
+* и других.
+
+```Python hl_lines="6"
+{!../../../docs_src/response_status_code/tutorial001.py!}
+```
+
+!!! note "Примечание"
+ Обратите внимание, что `status_code` является атрибутом метода-декоратора (`get`, `post` и т.д.), а не *функции-обработчика пути* в отличие от всех остальных параметров и тела запроса.
+
+Параметр `status_code` принимает число, обозначающее HTTP код статуса ответа.
+
+!!! info "Информация"
+ В качестве значения параметра `status_code` также может использоваться `IntEnum`, например, из библиотеки `http.HTTPStatus` в Python.
+
+Это позволит:
+
+* Возвращать указанный код статуса в ответе.
+* Документировать его как код статуса ответа в OpenAPI схеме (а значит, и в пользовательском интерфейсе):
+
+
+
+!!! note "Примечание"
+ Некоторые коды статуса ответа (см. следующий раздел) указывают на то, что ответ не имеет тела.
+
+ FastAPI знает об этом и создаст документацию OpenAPI, в которой будет указано, что тело ответа отсутствует.
+
+## Об HTTP кодах статуса ответа
+
+!!! note "Примечание"
+ Если вы уже знаете, что представляют собой HTTP коды статуса ответа, можете перейти к следующему разделу.
+
+В протоколе HTTP числовой код состояния из 3 цифр отправляется как часть ответа.
+
+У кодов статуса есть названия, чтобы упростить их распознавание, но важны именно числовые значения.
+
+Кратко о значениях кодов:
+
+* `1XX` – статус-коды информационного типа. Они редко используются разработчиками напрямую. Ответы с этими кодами не могут иметь тела.
+* **`2XX`** – статус-коды, сообщающие об успешной обработке запроса. Они используются чаще всего.
+ * `200` – это код статуса ответа по умолчанию, который означает, что все прошло "OK".
+ * Другим примером может быть статус `201`, "Created". Он обычно используется после создания новой записи в базе данных.
+ * Особый случай – `204`, "No Content". Этот статус ответа используется, когда нет содержимого для возврата клиенту, и поэтому ответ не должен иметь тела.
+* **`3XX`** – статус-коды, сообщающие о перенаправлениях. Ответы с этими кодами статуса могут иметь или не иметь тело, за исключением ответов со статусом `304`, "Not Modified", у которых не должно быть тела.
+* **`4XX`** – статус-коды, сообщающие о клиентской ошибке. Это ещё одна наиболее часто используемая категория.
+ * Пример – код `404` для статуса "Not Found".
+ * Для общих ошибок со стороны клиента можно просто использовать код `400`.
+* `5XX` – статус-коды, сообщающие о серверной ошибке. Они почти никогда не используются разработчиками напрямую. Когда что-то идет не так в какой-то части кода вашего приложения или на сервере, он автоматически вернёт один из 5XX кодов.
+
+!!! tip "Подсказка"
+ Чтобы узнать больше о HTTP кодах статуса и о том, для чего каждый из них предназначен, ознакомьтесь с документацией MDN об HTTP кодах статуса ответа.
+
+## Краткие обозначения для запоминания названий кодов
+
+Рассмотрим предыдущий пример еще раз:
+
+```Python hl_lines="6"
+{!../../../docs_src/response_status_code/tutorial001.py!}
+```
+
+`201` – это код статуса "Создано".
+
+Но вам не обязательно запоминать, что означает каждый из этих кодов.
+
+Для удобства вы можете использовать переменные из `fastapi.status`.
+
+```Python hl_lines="1 6"
+{!../../../docs_src/response_status_code/tutorial002.py!}
+```
+
+Они содержат те же числовые значения, но позволяют использовать подсказки редактора для выбора кода статуса:
+
+
+
+!!! note "Технические детали"
+ Вы также можете использовать `from starlette import status` вместо `from fastapi import status`.
+
+ **FastAPI** позволяет использовать как `starlette.status`, так и `fastapi.status` исключительно для удобства разработчиков. Но поставляется fastapi.status непосредственно из Starlette.
+
+## Изменение кода статуса по умолчанию
+
+Позже, в [Руководстве для продвинутых пользователей](../advanced/response-change-status-code.md){.internal-link target=_blank}, вы узнаете, как возвращать HTTP коды статуса, отличные от используемого здесь кода статуса по умолчанию.
diff --git a/docs/ru/mkdocs.yml b/docs/ru/mkdocs.yml
index f35ee968c..5b6e338ce 100644
--- a/docs/ru/mkdocs.yml
+++ b/docs/ru/mkdocs.yml
@@ -40,11 +40,14 @@ nav:
- Languages:
- en: /
- az: /az/
+ - cs: /cs/
- de: /de/
+ - em: /em/
- es: /es/
- fa: /fa/
- fr: /fr/
- he: /he/
+ - hy: /hy/
- id: /id/
- it: /it/
- ja: /ja/
@@ -55,6 +58,7 @@ nav:
- ru: /ru/
- sq: /sq/
- sv: /sv/
+ - ta: /ta/
- tr: /tr/
- uk: /uk/
- zh: /zh/
@@ -62,12 +66,23 @@ nav:
- fastapi-people.md
- python-types.md
- Учебник - руководство пользователя:
+ - tutorial/query-params-str-validations.md
+ - tutorial/body-fields.md
- tutorial/background-tasks.md
+ - tutorial/extra-data-types.md
+ - tutorial/cookie-params.md
+ - tutorial/response-status-code.md
- async.md
- Развёртывание:
- deployment/index.md
- deployment/versions.md
+- project-generation.md
+- alternatives.md
+- history-design-future.md
- external-links.md
+- benchmarks.md
+- help-fastapi.md
+- contributing.md
markdown_extensions:
- toc:
permalink: true
@@ -90,7 +105,7 @@ markdown_extensions:
extra:
analytics:
provider: google
- property: UA-133183413-1
+ property: G-YNEVN69SC3
social:
- icon: fontawesome/brands/github-alt
link: https://github.com/tiangolo/fastapi
@@ -111,8 +126,12 @@ extra:
name: en - English
- link: /az/
name: az
+ - link: /cs/
+ name: cs
- link: /de/
name: de
+ - link: /em/
+ name: 😉
- link: /es/
name: es - español
- link: /fa/
@@ -121,6 +140,8 @@ extra:
name: fr - français
- link: /he/
name: he
+ - link: /hy/
+ name: hy
- link: /id/
name: id
- link: /it/
@@ -141,6 +162,8 @@ extra:
name: sq - shqip
- link: /sv/
name: sv - svenska
+ - link: /ta/
+ name: ta - தமிழ்
- link: /tr/
name: tr - Türkçe
- link: /uk/
diff --git a/docs/sq/mkdocs.yml b/docs/sq/mkdocs.yml
index b07f3bc63..ca20bce30 100644
--- a/docs/sq/mkdocs.yml
+++ b/docs/sq/mkdocs.yml
@@ -40,11 +40,14 @@ nav:
- Languages:
- en: /
- az: /az/
+ - cs: /cs/
- de: /de/
+ - em: /em/
- es: /es/
- fa: /fa/
- fr: /fr/
- he: /he/
+ - hy: /hy/
- id: /id/
- it: /it/
- ja: /ja/
@@ -55,6 +58,7 @@ nav:
- ru: /ru/
- sq: /sq/
- sv: /sv/
+ - ta: /ta/
- tr: /tr/
- uk: /uk/
- zh: /zh/
@@ -80,7 +84,7 @@ markdown_extensions:
extra:
analytics:
provider: google
- property: UA-133183413-1
+ property: G-YNEVN69SC3
social:
- icon: fontawesome/brands/github-alt
link: https://github.com/tiangolo/fastapi
@@ -101,8 +105,12 @@ extra:
name: en - English
- link: /az/
name: az
+ - link: /cs/
+ name: cs
- link: /de/
name: de
+ - link: /em/
+ name: 😉
- link: /es/
name: es - español
- link: /fa/
@@ -111,6 +119,8 @@ extra:
name: fr - français
- link: /he/
name: he
+ - link: /hy/
+ name: hy
- link: /id/
name: id
- link: /it/
@@ -131,6 +141,8 @@ extra:
name: sq - shqip
- link: /sv/
name: sv - svenska
+ - link: /ta/
+ name: ta - தமிழ்
- link: /tr/
name: tr - Türkçe
- link: /uk/
diff --git a/docs/sv/mkdocs.yml b/docs/sv/mkdocs.yml
index 3332d232d..ce6ee3f83 100644
--- a/docs/sv/mkdocs.yml
+++ b/docs/sv/mkdocs.yml
@@ -40,11 +40,14 @@ nav:
- Languages:
- en: /
- az: /az/
+ - cs: /cs/
- de: /de/
+ - em: /em/
- es: /es/
- fa: /fa/
- fr: /fr/
- he: /he/
+ - hy: /hy/
- id: /id/
- it: /it/
- ja: /ja/
@@ -55,6 +58,7 @@ nav:
- ru: /ru/
- sq: /sq/
- sv: /sv/
+ - ta: /ta/
- tr: /tr/
- uk: /uk/
- zh: /zh/
@@ -80,7 +84,7 @@ markdown_extensions:
extra:
analytics:
provider: google
- property: UA-133183413-1
+ property: G-YNEVN69SC3
social:
- icon: fontawesome/brands/github-alt
link: https://github.com/tiangolo/fastapi
@@ -101,8 +105,12 @@ extra:
name: en - English
- link: /az/
name: az
+ - link: /cs/
+ name: cs
- link: /de/
name: de
+ - link: /em/
+ name: 😉
- link: /es/
name: es - español
- link: /fa/
@@ -111,6 +119,8 @@ extra:
name: fr - français
- link: /he/
name: he
+ - link: /hy/
+ name: hy
- link: /id/
name: id
- link: /it/
@@ -131,6 +141,8 @@ extra:
name: sq - shqip
- link: /sv/
name: sv - svenska
+ - link: /ta/
+ name: ta - தமிழ்
- link: /tr/
name: tr - Türkçe
- link: /uk/
diff --git a/docs/ta/mkdocs.yml b/docs/ta/mkdocs.yml
new file mode 100644
index 000000000..d66fc5740
--- /dev/null
+++ b/docs/ta/mkdocs.yml
@@ -0,0 +1,157 @@
+site_name: FastAPI
+site_description: FastAPI framework, high performance, easy to learn, fast to code, ready for production
+site_url: https://fastapi.tiangolo.com/ta/
+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: en
+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/
+ - cs: /cs/
+ - de: /de/
+ - em: /em/
+ - es: /es/
+ - fa: /fa/
+ - fr: /fr/
+ - he: /he/
+ - hy: /hy/
+ - id: /id/
+ - it: /it/
+ - ja: /ja/
+ - ko: /ko/
+ - nl: /nl/
+ - pl: /pl/
+ - pt: /pt/
+ - ru: /ru/
+ - sq: /sq/
+ - sv: /sv/
+ - ta: /ta/
+ - 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: G-YNEVN69SC3
+ 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: /cs/
+ name: cs
+ - link: /de/
+ name: de
+ - link: /em/
+ name: 😉
+ - link: /es/
+ name: es - español
+ - link: /fa/
+ name: fa
+ - link: /fr/
+ name: fr - français
+ - link: /he/
+ name: he
+ - link: /hy/
+ name: hy
+ - 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: /ta/
+ name: ta - தமிழ்
+ - 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/ta/overrides/.gitignore b/docs/ta/overrides/.gitignore
new file mode 100644
index 000000000..e69de29bb
diff --git a/docs/tr/docs/tutorial/first_steps.md b/docs/tr/docs/tutorial/first_steps.md
new file mode 100644
index 000000000..b39802f5d
--- /dev/null
+++ b/docs/tr/docs/tutorial/first_steps.md
@@ -0,0 +1,336 @@
+# İlk Adımlar
+
+En basit FastAPI dosyası şu şekildedir:
+
+```Python
+{!../../../docs_src/first_steps/tutorial001.py!}
+```
+
+Bunu bir `main.py` dosyasına kopyalayın.
+
+Projeyi çalıştırın:
+
+
+
+```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.
+```
+
+
+
+!!! note
+ `uvicorn main:app` komutu şunu ifade eder:
+
+ * `main`: `main.py` dosyası (the Python "module").
+ * `app`: `main.py` dosyası içerisinde `app = FastAPI()` satırıyla oluşturulan nesne.
+ * `--reload`: Kod değişikliği sonrasında sunucunun yeniden başlatılmasını sağlar. Yalnızca geliştirme için kullanın.
+
+Çıktıda şu şekilde bir satır vardır:
+
+```hl_lines="4"
+INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
+```
+
+Bu satır, yerel makinenizde uygulamanızın sunulduğu URL'yi gösterir.
+
+### Kontrol Et
+
+Tarayıcınızda http://127.0.0.1:8000 adresini açın.
+
+Bir JSON yanıtı göreceksiniz:
+
+```JSON
+{"message": "Hello World"}
+```
+
+### İnteraktif API dokümantasyonu
+
+http://127.0.0.1:8000/docs adresine gidin.
+
+Otomatik oluşturulmuş( Swagger UI tarafından sağlanan) interaktif bir API dokümanı göreceksiniz:
+
+
+
+### Alternatif API dokümantasyonu
+
+Şimdi, http://127.0.0.1:8000/redoc adresine gidin.
+
+Otomatik oluşturulmuş(ReDoc tarafından sağlanan) bir API dokümanı göreceksiniz:
+
+
+
+### OpenAPI
+
+**FastAPI**, **OpenAPI** standardını kullanarak tüm API'lerinizi açıklayan bir "şema" oluşturur.
+
+#### "Şema"
+
+Bir "şema", bir şeyin tanımı veya açıklamasıdır. Soyut bir açıklamadır, uygulayan kod değildir.
+
+#### API "şemaları"
+
+Bu durumda, OpenAPI, API şemasını nasıl tanımlayacağınızı belirten şartnamelerdir.
+
+Bu şema tanımı, API yollarınızı, aldıkları olası parametreleri vb. içerir.
+
+#### Data "şema"
+
+"Şema" terimi, JSON içeriği gibi bazı verilerin şeklini de ifade edebilir.
+
+Bu durumda, JSON öznitelikleri ve sahip oldukları veri türleri vb. anlamına gelir.
+
+#### OpenAPI and JSON Şema
+
+OpenAPI, API'niz için bir API şeması tanımlar. Ve bu şema, JSON veri şemaları standardı olan **JSON Şema** kullanılarak API'niz tarafından gönderilen ve alınan verilerin tanımlarını (veya "şemalarını") içerir.
+
+#### `openapi.json` kontrol et
+
+OpenAPI şemasının nasıl göründüğünü merak ediyorsanız, FastAPI otomatik olarak tüm API'nizin açıklamalarını içeren bir JSON (şema) oluşturur.
+
+Doğrudan şu adreste görebilirsiniz: http://127.0.0.1:8000/openapi.json.
+
+Aşağıdaki gibi bir şeyle başlayan bir JSON gösterecektir:
+
+```JSON
+{
+ "openapi": "3.0.2",
+ "info": {
+ "title": "FastAPI",
+ "version": "0.1.0"
+ },
+ "paths": {
+ "/items/": {
+ "get": {
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+
+
+
+...
+```
+
+#### OpenAPI ne içindir?
+
+OpenAPI şeması, dahili olarak bulunan iki etkileşimli dokümantasyon sistemine güç veren şeydir.
+
+Ve tamamen OpenAPI'ye dayalı düzinelerce alternatif vardır. **FastAPI** ile oluşturulmuş uygulamanıza bu alternatiflerden herhangi birini kolayca ekleyebilirsiniz.
+
+API'nizle iletişim kuran istemciler için otomatik olarak kod oluşturmak için de kullanabilirsiniz. Örneğin, frontend, mobil veya IoT uygulamaları.
+
+## Adım adım özet
+
+### Adım 1: `FastAPI`yi içe aktarın
+
+```Python hl_lines="1"
+{!../../../docs_src/first_steps/tutorial001.py!}
+```
+
+`FastAPI`, API'niz için tüm fonksiyonları sağlayan bir Python sınıfıdır.
+
+!!! note "Teknik Detaylar"
+ `FastAPI` doğrudan `Starlette` kalıtım alan bir sınıftır.
+
+ Tüm Starlette fonksiyonlarını `FastAPI` ile de kullanabilirsiniz.
+
+### Adım 2: Bir `FastAPI` örneği oluşturun
+
+```Python hl_lines="3"
+{!../../../docs_src/first_steps/tutorial001.py!}
+```
+
+Burada `app` değişkeni `FastAPI` sınıfının bir örneği olacaktır.
+
+Bu tüm API'yi oluşturmak için ana etkileşim noktası olacaktır.
+
+`uvicorn` komutunda atıfta bulunulan `app` ile aynıdır.
+
+
+
+```console
+$ uvicorn main:app --reload
+
+INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
+```
+
+
+
+Uygulamanızı aşağıdaki gibi oluşturursanız:
+
+```Python hl_lines="3"
+{!../../../docs_src/first_steps/tutorial002.py!}
+```
+
+Ve bunu `main.py` dosyasına koyduktan sonra `uvicorn` komutunu şu şekilde çağırabilirsiniz:
+
+
+
+```console
+$ uvicorn main:my_awesome_api --reload
+
+INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
+```
+
+