diff --git a/.github/DISCUSSION_TEMPLATE/questions.yml b/.github/DISCUSSION_TEMPLATE/questions.yml index 3726b7d18dfea..98424a341db7b 100644 --- a/.github/DISCUSSION_TEMPLATE/questions.yml +++ b/.github/DISCUSSION_TEMPLATE/questions.yml @@ -123,6 +123,20 @@ body: ``` validations: required: true + - type: input + id: pydantic-version + attributes: + label: Pydantic Version + description: | + What Pydantic version are you using? + + You can find the Pydantic version with: + + ```bash + python -c "import pydantic; print(pydantic.version.VERSION)" + ``` + validations: + required: true - type: input id: python-version attributes: diff --git a/.github/actions/comment-docs-preview-in-pr/Dockerfile b/.github/actions/comment-docs-preview-in-pr/Dockerfile index 4f20c5f10bc46..42627fe190ebf 100644 --- a/.github/actions/comment-docs-preview-in-pr/Dockerfile +++ b/.github/actions/comment-docs-preview-in-pr/Dockerfile @@ -1,6 +1,8 @@ -FROM python:3.7 +FROM python:3.10 -RUN pip install httpx "pydantic==1.5.1" pygithub +COPY ./requirements.txt /app/requirements.txt + +RUN pip install -r /app/requirements.txt COPY ./app /app diff --git a/.github/actions/comment-docs-preview-in-pr/app/main.py b/.github/actions/comment-docs-preview-in-pr/app/main.py index 68914fdb9a818..8cc119fe0af8c 100644 --- a/.github/actions/comment-docs-preview-in-pr/app/main.py +++ b/.github/actions/comment-docs-preview-in-pr/app/main.py @@ -6,7 +6,8 @@ import httpx from github import Github from github.PullRequest import PullRequest -from pydantic import BaseModel, BaseSettings, SecretStr, ValidationError +from pydantic import BaseModel, SecretStr, ValidationError +from pydantic_settings import BaseSettings github_api = "https://api.github.com" diff --git a/.github/actions/comment-docs-preview-in-pr/requirements.txt b/.github/actions/comment-docs-preview-in-pr/requirements.txt new file mode 100644 index 0000000000000..74a3631f48fa3 --- /dev/null +++ b/.github/actions/comment-docs-preview-in-pr/requirements.txt @@ -0,0 +1,4 @@ +PyGithub +pydantic>=2.5.3,<3.0.0 +pydantic-settings>=2.1.0,<3.0.0 +httpx diff --git a/.github/actions/notify-translations/Dockerfile b/.github/actions/notify-translations/Dockerfile index fa4197e6a88d1..b68b4bb1a29c9 100644 --- a/.github/actions/notify-translations/Dockerfile +++ b/.github/actions/notify-translations/Dockerfile @@ -1,4 +1,4 @@ -FROM python:3.7 +FROM python:3.9 RUN pip install httpx PyGithub "pydantic==1.5.1" "pyyaml>=5.3.1,<6.0.0" diff --git a/.github/actions/notify-translations/app/main.py b/.github/actions/notify-translations/app/main.py index 494fe6ad8e660..8ac1f233d6981 100644 --- a/.github/actions/notify-translations/app/main.py +++ b/.github/actions/notify-translations/app/main.py @@ -9,7 +9,7 @@ from github import Github from pydantic import BaseModel, BaseSettings, SecretStr -awaiting_label = "awaiting review" +awaiting_label = "awaiting-review" lang_all_label = "lang-all" approved_label = "approved-2" translations_path = Path(__file__).parent / "translations.yml" diff --git a/.github/actions/people/Dockerfile b/.github/actions/people/Dockerfile index fa4197e6a88d1..1455106bde3c8 100644 --- a/.github/actions/people/Dockerfile +++ b/.github/actions/people/Dockerfile @@ -1,6 +1,6 @@ -FROM python:3.7 +FROM python:3.9 -RUN pip install httpx PyGithub "pydantic==1.5.1" "pyyaml>=5.3.1,<6.0.0" +RUN pip install httpx PyGithub "pydantic==2.0.2" pydantic-settings "pyyaml>=5.3.1,<6.0.0" COPY ./app /app diff --git a/.github/actions/people/action.yml b/.github/actions/people/action.yml index 16bc8cdcb8d7b..71745b8747a74 100644 --- a/.github/actions/people/action.yml +++ b/.github/actions/people/action.yml @@ -3,10 +3,7 @@ description: "Generate the data for the FastAPI People page" author: "Sebastián Ramírez " inputs: token: - description: 'User token, to read the GitHub API. Can be passed in using {{ secrets.ACTION_TOKEN }}' - required: true - standard_token: - description: 'Default GitHub Action token, used for the PR. Can be passed in using {{ secrets.GITHUB_TOKEN }}' + description: 'User token, to read the GitHub API. Can be passed in using {{ secrets.FASTAPI_PEOPLE }}' required: true runs: using: 'docker' diff --git a/.github/actions/people/app/main.py b/.github/actions/people/app/main.py index 2bf59f25e62f8..9f2b9369d0a30 100644 --- a/.github/actions/people/app/main.py +++ b/.github/actions/people/app/main.py @@ -9,7 +9,8 @@ import httpx import yaml from github import Github -from pydantic import BaseModel, BaseSettings, SecretStr +from pydantic import BaseModel, SecretStr +from pydantic_settings import BaseSettings github_graphql_url = "https://api.github.com/graphql" questions_category_id = "MDE4OkRpc2N1c3Npb25DYXRlZ29yeTMyMDAxNDM0" @@ -57,38 +58,6 @@ } """ -issues_query = """ -query Q($after: String) { - repository(name: "fastapi", owner: "tiangolo") { - issues(first: 100, after: $after) { - edges { - cursor - node { - number - author { - login - avatarUrl - url - } - title - createdAt - state - comments(first: 100) { - nodes { - createdAt - author { - login - avatarUrl - url - } - } - } - } - } - } - } -} -""" prs_query = """ query Q($after: String) { @@ -175,7 +144,7 @@ class Author(BaseModel): url: str -# Issues and Discussions +# Discussions class CommentsNode(BaseModel): @@ -199,15 +168,6 @@ class DiscussionsComments(BaseModel): nodes: List[DiscussionsCommentsNode] -class IssuesNode(BaseModel): - number: int - author: Union[Author, None] = None - title: str - createdAt: datetime - state: str - comments: Comments - - class DiscussionsNode(BaseModel): number: int author: Union[Author, None] = None @@ -216,44 +176,23 @@ class DiscussionsNode(BaseModel): 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 @@ -352,7 +291,6 @@ class SponsorsResponse(BaseModel): class Settings(BaseSettings): input_token: SecretStr - input_standard_token: SecretStr github_repository: str httpx_timeout: int = 30 @@ -383,17 +321,12 @@ def get_graphql_response( data = response.json() if "errors" in data: logging.error(f"Errors in response, after: {after}, category_id: {category_id}") + logging.error(data["errors"]) logging.error(response.text) raise RuntimeError(response.text) return data -def get_graphql_issue_edges(*, settings: Settings, after: Union[str, None] = None): - data = get_graphql_response(settings=settings, query=issues_query, after=after) - graphql_response = IssuesResponse.parse_obj(data) - return graphql_response.data.repository.issues.edges - - def get_graphql_question_discussion_edges( *, settings: Settings, @@ -405,59 +338,32 @@ def get_graphql_question_discussion_edges( after=after, category_id=questions_category_id, ) - graphql_response = DiscussionsResponse.parse_obj(data) + graphql_response = DiscussionsResponse.model_validate(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) + graphql_response = PRsResponse.model_validate(data) return graphql_response.data.repository.pullRequests.edges def get_graphql_sponsor_edges(*, settings: Settings, after: Union[str, None] = None): data = get_graphql_response(settings=settings, query=sponsors_query, after=after) - graphql_response = SponsorsResponse.parse_obj(data) + graphql_response = SponsorsResponse.model_validate(data) return graphql_response.data.user.sponsorshipsAsMaintainer.edges -def get_issues_experts(settings: Settings): - issue_nodes: List[IssuesNode] = [] - issue_edges = get_graphql_issue_edges(settings=settings) +class DiscussionExpertsResults(BaseModel): + commenters: Counter + last_month_commenters: Counter + three_months_commenters: Counter + six_months_commenters: Counter + one_year_commenters: Counter + authors: Dict[str, Author] - while issue_edges: - for edge in issue_edges: - issue_nodes.append(edge.node) - last_edge = issue_edges[-1] - issue_edges = get_graphql_issue_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 issue in issue_nodes: - issue_author_name = None - if issue.author: - authors[issue.author.login] = issue.author - issue_author_name = issue.author.login - issue_commentors = set() - for comment in issue.comments.nodes: - if comment.author: - authors[comment.author.login] = comment.author - 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): +def get_discussion_nodes(settings: Settings) -> List[DiscussionsNode]: discussion_nodes: List[DiscussionsNode] = [] discussion_edges = get_graphql_question_discussion_edges(settings=settings) @@ -468,61 +374,73 @@ def get_discussions_experts(settings: Settings): discussion_edges = get_graphql_question_discussion_edges( settings=settings, after=last_edge.cursor ) + return discussion_nodes + - commentors = Counter() - last_month_commentors = Counter() +def get_discussions_experts( + discussion_nodes: List[DiscussionsNode], +) -> DiscussionExpertsResults: + commenters = Counter() + last_month_commenters = Counter() + three_months_commenters = Counter() + six_months_commenters = Counter() + one_year_commenters = Counter() authors: Dict[str, Author] = {} now = datetime.now(tz=timezone.utc) one_month_ago = now - timedelta(days=30) + three_months_ago = now - timedelta(days=90) + six_months_ago = now - timedelta(days=180) + one_year_ago = now - timedelta(days=365) 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() + discussion_commentors: dict[str, datetime] = {} 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) + author_time = discussion_commentors.get( + comment.author.login, comment.createdAt + ) + discussion_commentors[comment.author.login] = max( + author_time, comment.createdAt + ) 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 - - -def get_contributors(settings: Settings): + author_time = discussion_commentors.get( + reply.author.login, reply.createdAt + ) + discussion_commentors[reply.author.login] = max( + author_time, reply.createdAt + ) + for author_name, author_time in discussion_commentors.items(): + commenters[author_name] += 1 + if author_time > one_month_ago: + last_month_commenters[author_name] += 1 + if author_time > three_months_ago: + three_months_commenters[author_name] += 1 + if author_time > six_months_ago: + six_months_commenters[author_name] += 1 + if author_time > one_year_ago: + one_year_commenters[author_name] += 1 + discussion_experts_results = DiscussionExpertsResults( + authors=authors, + commenters=commenters, + last_month_commenters=last_month_commenters, + three_months_commenters=three_months_commenters, + six_months_commenters=six_months_commenters, + one_year_commenters=one_year_commenters, + ) + return discussion_experts_results + + +def get_pr_nodes(settings: Settings) -> List[PullRequestNode]: pr_nodes: List[PullRequestNode] = [] pr_edges = get_graphql_pr_edges(settings=settings) @@ -531,10 +449,22 @@ def get_contributors(settings: Settings): pr_nodes.append(edge.node) last_edge = pr_edges[-1] pr_edges = get_graphql_pr_edges(settings=settings, after=last_edge.cursor) + return pr_nodes + +class ContributorsResults(BaseModel): + contributors: Counter + commenters: Counter + reviewers: Counter + translation_reviewers: Counter + authors: Dict[str, Author] + + +def get_contributors(pr_nodes: List[PullRequestNode]) -> ContributorsResults: contributors = Counter() - commentors = Counter() + commenters = Counter() reviewers = Counter() + translation_reviewers = Counter() authors: Dict[str, Author] = {} for pr in pr_nodes: @@ -551,16 +481,26 @@ def get_contributors(settings: Settings): continue pr_commentors.add(comment.author.login) for author_name in pr_commentors: - commentors[author_name] += 1 + commenters[author_name] += 1 for review in pr.reviews.nodes: if review.author: authors[review.author.login] = review.author pr_reviewers.add(review.author.login) + for label in pr.labels.nodes: + if label.name == "lang-all": + translation_reviewers[review.author.login] += 1 + break for reviewer in pr_reviewers: reviewers[reviewer] += 1 if pr.state == "MERGED" and pr.author: contributors[pr.author.login] += 1 - return contributors, commentors, reviewers, authors + return ContributorsResults( + contributors=contributors, + commenters=commenters, + reviewers=reviewers, + translation_reviewers=translation_reviewers, + authors=authors, + ) def get_individual_sponsors(settings: Settings): @@ -584,19 +524,19 @@ def get_individual_sponsors(settings: Settings): def get_top_users( *, counter: Counter, - min_count: int, authors: Dict[str, Author], skip_users: Container[str], + min_count: int = 2, ): users = [] - for commentor, count in counter.most_common(50): - if commentor in skip_users: + for commenter, count in counter.most_common(50): + if commenter in skip_users: continue if count >= min_count: - author = authors[commentor] + author = authors[commenter] users.append( { - "login": commentor, + "login": commenter, "count": count, "avatarUrl": author.avatarUrl, "url": author.url, @@ -608,16 +548,14 @@ def get_top_users( if __name__ == "__main__": logging.basicConfig(level=logging.INFO) settings = Settings() - logging.info(f"Using config: {settings.json()}") - g = Github(settings.input_standard_token.get_secret_value()) + logging.info(f"Using config: {settings.model_dump_json()}") + g = Github(settings.input_token.get_secret_value()) repo = g.get_repo(settings.github_repository) - question_commentors, question_last_month_commentors, question_authors = get_experts( - settings=settings - ) - contributors, pr_commentors, reviewers, pr_authors = get_contributors( - settings=settings - ) - authors = {**question_authors, **pr_authors} + discussion_nodes = get_discussion_nodes(settings=settings) + experts_results = get_discussions_experts(discussion_nodes=discussion_nodes) + pr_nodes = get_pr_nodes(settings=settings) + contributors_results = get_contributors(pr_nodes=pr_nodes) + authors = {**experts_results.authors, **contributors_results.authors} maintainers_logins = {"tiangolo"} bot_names = {"codecov", "github-actions", "pre-commit-ci", "dependabot"} maintainers = [] @@ -626,39 +564,51 @@ def get_top_users( maintainers.append( { "login": login, - "answers": question_commentors[login], - "prs": contributors[login], + "answers": experts_results.commenters[login], + "prs": contributors_results.contributors[login], "avatarUrl": user.avatarUrl, "url": user.url, } ) - min_count_expert = 10 - min_count_last_month = 3 - min_count_contributor = 4 - min_count_reviewer = 4 skip_users = maintainers_logins | bot_names experts = get_top_users( - counter=question_commentors, - min_count=min_count_expert, + counter=experts_results.commenters, authors=authors, skip_users=skip_users, ) - last_month_active = get_top_users( - counter=question_last_month_commentors, - min_count=min_count_last_month, + last_month_experts = get_top_users( + counter=experts_results.last_month_commenters, + authors=authors, + skip_users=skip_users, + ) + three_months_experts = get_top_users( + counter=experts_results.three_months_commenters, + authors=authors, + skip_users=skip_users, + ) + six_months_experts = get_top_users( + counter=experts_results.six_months_commenters, + authors=authors, + skip_users=skip_users, + ) + one_year_experts = get_top_users( + counter=experts_results.one_year_commenters, authors=authors, skip_users=skip_users, ) top_contributors = get_top_users( - counter=contributors, - min_count=min_count_contributor, + counter=contributors_results.contributors, authors=authors, skip_users=skip_users, ) top_reviewers = get_top_users( - counter=reviewers, - min_count=min_count_reviewer, + counter=contributors_results.reviewers, + authors=authors, + skip_users=skip_users, + ) + top_translations_reviewers = get_top_users( + counter=contributors_results.translation_reviewers, authors=authors, skip_users=skip_users, ) @@ -678,13 +628,19 @@ def get_top_users( people = { "maintainers": maintainers, "experts": experts, - "last_month_active": last_month_active, + "last_month_experts": last_month_experts, + "three_months_experts": three_months_experts, + "six_months_experts": six_months_experts, + "one_year_experts": one_year_experts, "top_contributors": top_contributors, "top_reviewers": top_reviewers, + "top_translations_reviewers": top_translations_reviewers, } github_sponsors = { "sponsors": sponsors, } + # For local development + # people_path = Path("../../../../docs/en/data/people.yml") people_path = Path("./docs/en/data/people.yml") github_sponsors_path = Path("./docs/en/data/github_sponsors.yml") people_old_content = people_path.read_text(encoding="utf-8") diff --git a/.github/dependabot.yml b/.github/dependabot.yml index cd972a0ba4722..0a59adbd6b474 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -11,6 +11,10 @@ updates: - package-ecosystem: "pip" directory: "/" schedule: - interval: "daily" + interval: "monthly" + groups: + python-packages: + patterns: + - "*" commit-message: prefix: ⬆ diff --git a/.github/workflows/build-docs.yml b/.github/workflows/build-docs.yml index a155ecfeca6cc..9b167ee66c2f6 100644 --- a/.github/workflows/build-docs.yml +++ b/.github/workflows/build-docs.yml @@ -17,9 +17,9 @@ jobs: outputs: docs: ${{ steps.filter.outputs.docs }} steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 # For pull requests it's not necessary to checkout the code but for master it is - - uses: dorny/paths-filter@v2 + - uses: dorny/paths-filter@v3 id: filter with: filters: | @@ -28,6 +28,11 @@ jobs: - docs/** - docs_src/** - requirements-docs.txt + - pyproject.toml + - mkdocs.yml + - mkdocs.insiders.yml + - .github/workflows/build-docs.yml + - .github/workflows/deploy-docs.yml langs: needs: - changes @@ -35,23 +40,28 @@ jobs: outputs: langs: ${{ steps.show-langs.outputs.langs }} steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Set up Python - uses: actions/setup-python@v4 + uses: actions/setup-python@v5 with: python-version: "3.11" - uses: actions/cache@v3 id: cache with: path: ${{ env.pythonLocation }} - key: ${{ runner.os }}-python-docs-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml', 'requirements-docs.txt') }}-v05 + key: ${{ runner.os }}-python-docs-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml', 'requirements-docs.txt', 'requirements-docs-tests.txt') }}-v07 - name: Install docs extras if: steps.cache.outputs.cache-hit != 'true' run: pip install -r requirements-docs.txt # Install MkDocs Material Insiders here just to put it in the cache for the rest of the steps - name: Install Material for MkDocs Insiders - if: ( github.event_name != 'pull_request' || github.event.pull_request.head.repo.fork == false ) && steps.cache.outputs.cache-hit != 'true' - run: pip install git+https://${{ secrets.ACTIONS_TOKEN }}@github.com/squidfunk/mkdocs-material-insiders.git + if: ( github.event_name != 'pull_request' || github.secret_source == 'Actions' ) && steps.cache.outputs.cache-hit != 'true' + run: | + pip install git+https://${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}@github.com/squidfunk/mkdocs-material-insiders.git + pip install git+https://${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}@github.com/pawamoy-insiders/griffe-typing-deprecated.git + pip install git+https://${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}@github.com/pawamoy-insiders/mkdocstrings-python.git + - name: Verify Docs + run: python ./scripts/docs.py verify-docs - name: Export Language Codes id: show-langs run: | @@ -71,22 +81,25 @@ jobs: env: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Set up Python - uses: actions/setup-python@v4 + uses: actions/setup-python@v5 with: python-version: "3.11" - uses: actions/cache@v3 id: cache with: path: ${{ env.pythonLocation }} - key: ${{ runner.os }}-python-docs-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml', 'requirements-docs.txt') }}-v05 + key: ${{ runner.os }}-python-docs-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml', 'requirements-docs.txt', 'requirements-docs-tests.txt') }}-v08 - name: Install docs extras if: steps.cache.outputs.cache-hit != 'true' run: pip install -r requirements-docs.txt - name: Install Material for MkDocs Insiders - if: ( github.event_name != 'pull_request' || github.event.pull_request.head.repo.fork == false ) && steps.cache.outputs.cache-hit != 'true' - run: pip install git+https://${{ secrets.ACTIONS_TOKEN }}@github.com/squidfunk/mkdocs-material-insiders.git + if: ( github.event_name != 'pull_request' || github.secret_source == 'Actions' ) && steps.cache.outputs.cache-hit != 'true' + run: | + pip install git+https://${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}@github.com/squidfunk/mkdocs-material-insiders.git + pip install git+https://${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}@github.com/pawamoy-insiders/griffe-typing-deprecated.git + pip install git+https://${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}@github.com/pawamoy-insiders/mkdocstrings-python.git - name: Update Languages run: python ./scripts/docs.py update-languages - uses: actions/cache@v3 diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index 312d835af8724..b8dbb7dc5a74b 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -14,14 +14,14 @@ jobs: env: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Clean site run: | rm -rf ./site mkdir ./site - name: Download Artifact Docs id: download - uses: dawidd6/action-download-artifact@v2.27.0 + uses: dawidd6/action-download-artifact@v3.1.4 with: if_no_artifact_found: ignore github_token: ${{ secrets.FASTAPI_PREVIEW_DOCS_DOWNLOAD_ARTIFACTS }} @@ -29,21 +29,20 @@ jobs: run_id: ${{ github.event.workflow_run.id }} name: docs-site path: ./site/ - - name: Deploy to Netlify + - name: Deploy to Cloudflare Pages if: steps.download.outputs.found_artifact == 'true' - id: netlify - uses: nwtgck/actions-netlify@v2.0.0 + id: deploy + uses: cloudflare/pages-action@v1 with: - publish-dir: './site' - production-deploy: ${{ github.event.workflow_run.head_repository.full_name == github.repository && github.event.workflow_run.head_branch == 'master' }} - github-token: ${{ secrets.FASTAPI_PREVIEW_DOCS_NETLIFY }} - enable-commit-comment: false - env: - NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }} - NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }} + apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }} + accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} + projectName: fastapitiangolo + directory: './site' + gitHubToken: ${{ secrets.GITHUB_TOKEN }} + branch: ${{ ( github.event.workflow_run.head_repository.full_name == github.repository && github.event.workflow_run.head_branch == 'master' && 'main' ) || ( github.event.workflow_run.head_sha ) }} - name: Comment Deploy - if: steps.netlify.outputs.deploy-url != '' + if: steps.deploy.outputs.url != '' uses: ./.github/actions/comment-docs-preview-in-pr with: token: ${{ secrets.FASTAPI_PREVIEW_DOCS_COMMENT_DEPLOY }} - deploy_url: "${{ steps.netlify.outputs.deploy-url }}" + deploy_url: "${{ steps.deploy.outputs.url }}" diff --git a/.github/workflows/issue-manager.yml b/.github/workflows/issue-manager.yml index 32462310312c5..0f564d7218e35 100644 --- a/.github/workflows/issue-manager.yml +++ b/.github/workflows/issue-manager.yml @@ -19,7 +19,11 @@ jobs: if: github.repository_owner == 'tiangolo' runs-on: ubuntu-latest steps: - - uses: tiangolo/issue-manager@0.4.0 + - name: Dump GitHub context + env: + GITHUB_CONTEXT: ${{ toJson(github) }} + run: echo "$GITHUB_CONTEXT" + - uses: tiangolo/issue-manager@0.5.0 with: token: ${{ secrets.FASTAPI_ISSUE_MANAGER }} config: > @@ -27,5 +31,9 @@ jobs: "answered": { "delay": 864000, "message": "Assuming the original need was handled, this will be automatically closed now. But feel free to add more comments or create new issues or PRs." + }, + "changes-requested": { + "delay": 2628000, + "message": "As this PR had requested changes to be applied but has been inactive for a while, it's now going to be closed. But if there's anyone interested, feel free to create a new PR." } } diff --git a/.github/workflows/label-approved.yml b/.github/workflows/label-approved.yml index 976d29f74d758..51be2413d68b4 100644 --- a/.github/workflows/label-approved.yml +++ b/.github/workflows/label-approved.yml @@ -3,12 +3,25 @@ name: Label Approved on: schedule: - cron: "0 12 * * *" + workflow_dispatch: jobs: label-approved: if: github.repository_owner == 'tiangolo' runs-on: ubuntu-latest steps: - - uses: docker://tiangolo/label-approved:0.0.2 + - name: Dump GitHub context + env: + GITHUB_CONTEXT: ${{ toJson(github) }} + run: echo "$GITHUB_CONTEXT" + - uses: docker://tiangolo/label-approved:0.0.4 with: token: ${{ secrets.FASTAPI_LABEL_APPROVED }} + config: > + { + "approved-1": + { + "number": 1, + "await_label": "awaiting-review" + } + } diff --git a/.github/workflows/latest-changes.yml b/.github/workflows/latest-changes.yml index f11a638487025..27e062d090546 100644 --- a/.github/workflows/latest-changes.yml +++ b/.github/workflows/latest-changes.yml @@ -14,25 +14,32 @@ on: debug_enabled: description: 'Run the build with tmate debugging enabled (https://github.com/marketplace/actions/debugging-with-tmate)' required: false - default: false + default: 'false' jobs: latest-changes: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - name: Dump GitHub context + env: + GITHUB_CONTEXT: ${{ toJson(github) }} + run: echo "$GITHUB_CONTEXT" + - uses: actions/checkout@v4 with: - # To allow latest-changes to commit to master - token: ${{ secrets.ACTIONS_TOKEN }} + # To allow latest-changes to commit to the main branch + token: ${{ secrets.FASTAPI_LATEST_CHANGES }} # Allow debugging with tmate - name: Setup tmate session uses: mxschmitt/action-tmate@v3 - if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled }} + if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled == 'true' }} with: limit-access-to-actor: true - - uses: docker://tiangolo/latest-changes:0.0.3 + - uses: docker://tiangolo/latest-changes:0.3.0 + # - uses: tiangolo/latest-changes@main with: - token: ${{ secrets.FASTAPI_LATEST_CHANGES }} + token: ${{ secrets.GITHUB_TOKEN }} latest_changes_file: docs/en/docs/release-notes.md - latest_changes_header: '## Latest Changes\n\n' + latest_changes_header: '## Latest Changes' + end_regex: '^## ' debug_logs: true + label_header_prefix: '### ' diff --git a/.github/workflows/notify-translations.yml b/.github/workflows/notify-translations.yml index 0926486e9b0db..c0904ce486105 100644 --- a/.github/workflows/notify-translations.yml +++ b/.github/workflows/notify-translations.yml @@ -5,16 +5,29 @@ on: types: - labeled - closed + workflow_dispatch: + inputs: + number: + description: PR number + required: true + debug_enabled: + description: 'Run the build with tmate debugging enabled (https://github.com/marketplace/actions/debugging-with-tmate)' + required: false + default: 'false' jobs: notify-translations: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - name: Dump GitHub context + env: + GITHUB_CONTEXT: ${{ toJson(github) }} + run: echo "$GITHUB_CONTEXT" + - uses: actions/checkout@v4 # Allow debugging with tmate - name: Setup tmate session uses: mxschmitt/action-tmate@v3 - if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled }} + if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled == 'true' }} with: limit-access-to-actor: true - uses: ./.github/actions/notify-translations diff --git a/.github/workflows/people.yml b/.github/workflows/people.yml index 15ea464a1f587..b0868771dc42c 100644 --- a/.github/workflows/people.yml +++ b/.github/workflows/people.yml @@ -8,24 +8,27 @@ on: debug_enabled: description: 'Run the build with tmate debugging enabled (https://github.com/marketplace/actions/debugging-with-tmate)' required: false - default: false + default: 'false' jobs: fastapi-people: if: github.repository_owner == 'tiangolo' runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - name: Dump GitHub context + env: + GITHUB_CONTEXT: ${{ toJson(github) }} + run: echo "$GITHUB_CONTEXT" + - uses: actions/checkout@v4 # 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 - if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled }} + if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled == 'true' }} with: limit-access-to-actor: true - uses: ./.github/actions/people with: - token: ${{ secrets.ACTIONS_TOKEN }} - standard_token: ${{ secrets.FASTAPI_PEOPLE }} + token: ${{ secrets.FASTAPI_PEOPLE }} diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index b84c5bf17ad9d..899e49057fc8a 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -13,26 +13,20 @@ jobs: env: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Set up Python - uses: actions/setup-python@v4 + uses: actions/setup-python@v5 with: - python-version: "3.7" + python-version: "3.10" # Issue ref: https://github.com/actions/setup-python/issues/436 # cache: "pip" - cache-dependency-path: pyproject.toml - - uses: actions/cache@v3 - id: cache - with: - path: ${{ env.pythonLocation }} - key: ${{ runner.os }}-python-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml') }}-publish + # cache-dependency-path: pyproject.toml - name: Install build dependencies - if: steps.cache.outputs.cache-hit != 'true' run: pip install build - name: Build distribution run: python -m build - name: Publish - uses: pypa/gh-action-pypi-publish@v1.8.6 + uses: pypa/gh-action-pypi-publish@v1.8.11 with: password: ${{ secrets.PYPI_API_TOKEN }} - name: Dump GitHub context diff --git a/.github/workflows/smokeshow.yml b/.github/workflows/smokeshow.yml index c6d894d9f61eb..c4043cc6ae0b0 100644 --- a/.github/workflows/smokeshow.yml +++ b/.github/workflows/smokeshow.yml @@ -14,13 +14,17 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/setup-python@v4 + - name: Dump GitHub context + env: + GITHUB_CONTEXT: ${{ toJson(github) }} + run: echo "$GITHUB_CONTEXT" + - uses: actions/setup-python@v5 with: python-version: '3.9' - run: pip install smokeshow - - uses: dawidd6/action-download-artifact@v2.27.0 + - uses: dawidd6/action-download-artifact@v3.1.4 with: github_token: ${{ secrets.FASTAPI_SMOKESHOW_DOWNLOAD_ARTIFACTS }} workflow: test.yml diff --git a/.github/workflows/test-redistribute.yml b/.github/workflows/test-redistribute.yml new file mode 100644 index 0000000000000..c2e05013b6de3 --- /dev/null +++ b/.github/workflows/test-redistribute.yml @@ -0,0 +1,51 @@ +name: Test Redistribute + +on: + push: + branches: + - master + pull_request: + types: + - opened + - synchronize + +jobs: + test-redistribute: + runs-on: ubuntu-latest + steps: + - name: Dump GitHub context + env: + GITHUB_CONTEXT: ${{ toJson(github) }} + run: echo "$GITHUB_CONTEXT" + - uses: actions/checkout@v4 + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: "3.10" + # Issue ref: https://github.com/actions/setup-python/issues/436 + # cache: "pip" + # cache-dependency-path: pyproject.toml + - name: Install build dependencies + run: pip install build + - name: Build source distribution + run: python -m build --sdist + - name: Decompress source distribution + run: | + cd dist + tar xvf fastapi*.tar.gz + - name: Install test dependencies + run: | + cd dist/fastapi-*/ + pip install -r requirements-tests.txt + - name: Run source distribution tests + run: | + cd dist/fastapi-*/ + bash scripts/test.sh + - name: Build wheel distribution + run: | + cd dist + pip wheel --no-deps fastapi-*.tar.gz + - name: Dump GitHub context + env: + GITHUB_CONTEXT: ${{ toJson(github) }} + run: echo "$GITHUB_CONTEXT" diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 84f101424ecc6..b6b1736851e1f 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -13,9 +13,13 @@ jobs: lint: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - name: Dump GitHub context + env: + GITHUB_CONTEXT: ${{ toJson(github) }} + run: echo "$GITHUB_CONTEXT" + - uses: actions/checkout@v4 - name: Set up Python - uses: actions/setup-python@v4 + uses: actions/setup-python@v5 with: python-version: "3.11" # Issue ref: https://github.com/actions/setup-python/issues/436 @@ -25,10 +29,12 @@ jobs: id: cache with: path: ${{ env.pythonLocation }} - key: ${{ runner.os }}-python-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml', 'requirements-tests.txt') }}-test-v03 + key: ${{ runner.os }}-python-${{ env.pythonLocation }}-pydantic-v2-${{ hashFiles('pyproject.toml', 'requirements-tests.txt', 'requirements-docs-tests.txt') }}-test-v07 - name: Install Dependencies if: steps.cache.outputs.cache-hit != 'true' run: pip install -r requirements-tests.txt + - name: Install Pydantic v2 + run: pip install "pydantic>=2.0.2,<3.0.0" - name: Lint run: bash scripts/lint.sh @@ -36,12 +42,22 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - python-version: ["3.7", "3.8", "3.9", "3.10", "3.11"] + python-version: + - "3.12" + - "3.11" + - "3.10" + - "3.9" + - "3.8" + pydantic-version: ["pydantic-v1", "pydantic-v2"] fail-fast: false steps: - - uses: actions/checkout@v3 + - name: Dump GitHub context + env: + GITHUB_CONTEXT: ${{ toJson(github) }} + run: echo "$GITHUB_CONTEXT" + - uses: actions/checkout@v4 - name: Set up Python - uses: actions/setup-python@v4 + uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} # Issue ref: https://github.com/actions/setup-python/issues/436 @@ -51,10 +67,16 @@ jobs: id: cache with: path: ${{ env.pythonLocation }} - key: ${{ runner.os }}-python-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml', 'requirements-tests.txt') }}-test-v03 + key: ${{ runner.os }}-python-${{ env.pythonLocation }}-${{ matrix.pydantic-version }}-${{ hashFiles('pyproject.toml', 'requirements-tests.txt', 'requirements-docs-tests.txt') }}-test-v07 - name: Install Dependencies if: steps.cache.outputs.cache-hit != 'true' run: pip install -r requirements-tests.txt + - name: Install Pydantic v1 + if: matrix.pydantic-version == 'pydantic-v1' + run: pip install "pydantic>=1.10.0,<2.0.0" + - name: Install Pydantic v2 + if: matrix.pydantic-version == 'pydantic-v2' + run: pip install "pydantic>=2.0.2,<3.0.0" - run: mkdir coverage - name: Test run: bash scripts/test.sh @@ -71,8 +93,12 @@ jobs: needs: [test] runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 - - uses: actions/setup-python@v4 + - name: Dump GitHub context + env: + GITHUB_CONTEXT: ${{ toJson(github) }} + run: echo "$GITHUB_CONTEXT" + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 with: python-version: '3.8' # Issue ref: https://github.com/actions/setup-python/issues/436 @@ -101,6 +127,10 @@ jobs: - coverage-combine runs-on: ubuntu-latest steps: + - name: Dump GitHub context + env: + GITHUB_CONTEXT: ${{ toJson(github) }} + run: echo "$GITHUB_CONTEXT" - name: Decide whether the needed jobs succeeded or failed uses: re-actors/alls-green@release/v1 with: diff --git a/.gitignore b/.gitignore index d380d16b7d7b3..9be494cec0a92 100644 --- a/.gitignore +++ b/.gitignore @@ -25,3 +25,6 @@ archive.zip *~ .*.sw? .cache + +# macOS +.DS_Store diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 2a8a031363f1c..4d49845d6730d 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -13,23 +13,13 @@ repos: - --unsafe - id: end-of-file-fixer - id: trailing-whitespace -- repo: https://github.com/asottile/pyupgrade - rev: v3.3.1 - hooks: - - id: pyupgrade - args: - - --py3-plus - - --keep-runtime-typing - repo: https://github.com/charliermarsh/ruff-pre-commit - rev: v0.0.272 + rev: v0.2.0 hooks: - id: ruff args: - --fix -- repo: https://github.com/psf/black - rev: 23.3.0 - hooks: - - id: black + - id: ruff-format ci: autofix_commit_msg: 🎨 [pre-commit.ci] Auto format from pre-commit.com hooks autoupdate_commit_msg: ⬆ [pre-commit.ci] pre-commit autoupdate diff --git a/CITATION.cff b/CITATION.cff new file mode 100644 index 0000000000000..9028248b1d17b --- /dev/null +++ b/CITATION.cff @@ -0,0 +1,24 @@ +# This CITATION.cff file was generated with cffinit. +# Visit https://bit.ly/cffinit to generate yours today! + +cff-version: 1.2.0 +title: FastAPI +message: >- + If you use this software, please cite it using the + metadata from this file. +type: software +authors: + - given-names: Sebastián + family-names: Ramírez + email: tiangolo@gmail.com +identifiers: +repository-code: 'https://github.com/tiangolo/fastapi' +url: 'https://fastapi.tiangolo.com' +abstract: >- + FastAPI framework, high performance, easy to learn, fast to code, + ready for production +keywords: + - fastapi + - pydantic + - starlette +license: MIT diff --git a/README.md b/README.md index 7dc199367e905..67275d29dcecf 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ --- -FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints. +FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.8+ based on standard Python type hints. The key features are: @@ -48,13 +48,19 @@ The key features are: - - - + + + + + + + + - - + + + @@ -116,12 +122,12 @@ If you are building a CLI app to be ## Requirements -Python 3.7+ +Python 3.8+ FastAPI stands on the shoulders of giants: * Starlette for the web parts. -* Pydantic for the data parts. +* Pydantic for the data parts. ## Installation @@ -332,7 +338,7 @@ 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+**. +Just standard **Python 3.8+**. For example, for an `int`: @@ -447,12 +453,14 @@ To understand more about it, see the section email_validator - for email validation. +* pydantic-settings - for settings management. +* pydantic-extra-types - for extra types to be used with Pydantic. 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()`. +* 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`. diff --git a/docs/az/docs/fastapi-people.md b/docs/az/docs/fastapi-people.md new file mode 100644 index 0000000000000..2ca8e109ee9c7 --- /dev/null +++ b/docs/az/docs/fastapi-people.md @@ -0,0 +1,185 @@ +--- +hide: + - navigation +--- + +# FastAPI İnsanlar + +FastAPI-ın bütün mənşəli insanları qəbul edən heyrətamiz icması var. + + + +## Yaradıcı - İcraçı + +Salam! 👋 + +Bu mənəm: + +{% if people %} +
+{% for user in people.maintainers %} + +
@{{ user.login }}
Cavablar: {{ user.answers }}
Pull Request-lər: {{ user.prs }}
+{% endfor %} + +
+{% endif %} + +Mən **FastAPI**-ın yaradıcısı və icraçısıyam. Əlavə məlumat almaq üçün [Yardım FastAPI - Yardım alın - Müəlliflə əlaqə qurun](help-fastapi.md#connect-with-the-author){.internal-link target=_blank} səhifəsinə baxa bilərsiniz. + +...Burada isə sizə icmanı göstərmək istəyirəm. + +--- + +**FastAPI** icmadan çoxlu dəstək alır və mən onların əməyini vurğulamaq istəyirəm. + +Bu insanlar: + +* [GitHub-da başqalarının suallarına kömək edirlər](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}. +* [Pull Request-lər yaradırlar](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}. +* Pull Request-ləri ([xüsusilə tərcümələr üçün vacib olan](contributing.md#translations){.internal-link target=_blank}.) nəzərdən keçirirlər. + +Bu insanlara təşəkkür edirəm. 👏 🙇 + +## Keçən ayın ən fəal istifadəçiləri + +Bu istifadəçilər keçən ay [GitHub-da başqalarının suallarına](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} ən çox kömək edənlərdir. ☕ + +{% if people %} +
+{% for user in people.last_month_experts[:10] %} + +
@{{ user.login }}
Cavablandırılmış suallar: {{ user.count }}
+{% endfor %} + +
+{% endif %} + +## Mütəxəssislər + +Burada **FastAPI Mütəxəssisləri** var. 🤓 + +Bu istifadəçilər indiyə qədər [GitHub-da başqalarının suallarına](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} ən çox kömək edənlərdir. + +Onlar bir çox insanlara kömək edərək mütəxəssis olduqlarını sübut ediblər. ✨ + +{% if people %} +
+{% for user in people.experts[:50] %} + +
@{{ user.login }}
Cavablandırılmış suallar: {{ user.count }}
+{% endfor %} + +
+{% endif %} + +## Ən yaxşı əməkdaşlar + +Burada **Ən yaxşı əməkdaşlar** var. 👷 + +Bu istifadəçilərin ən çox *birləşdirilmiş* [Pull Request-ləri var](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}. + +Onlar mənbə kodu, sənədləmə, tərcümələr və s. barədə əmək göstərmişlər. 📦 + +{% if people %} +
+{% for user in people.top_contributors[:50] %} + +
@{{ user.login }}
Pull Request-lər: {{ user.count }}
+{% endfor %} + +
+{% endif %} + +Bundan başqa bir neçə (yüzdən çox) əməkdaş var ki, onları FastAPI GitHub Əməkdaşlar səhifəsində görə bilərsiniz. 👷 + +## Ən çox rəy verənlər + +Bu istifadəçilər **ən çox rəy verənlər**dir. + +### Tərcümələr üçün rəylər + +Mən yalnız bir neçə dildə danışıram (və çox da yaxşı deyil 😅). Bu səbəbdən, rəy verənlər sənədlərin [**tərcümələrini təsdiqləmək üçün gücə malik olanlar**](contributing.md#translations){.internal-link target=_blank}dır. Onlar olmadan, bir çox dilə tərcümə olunmuş sənədlər olmazdı. + +--- + +Başqalarının Pull Request-lərinə **Ən çox rəy verənlər** 🕵️ kodun, sənədlərin və xüsusilə də **tərcümələrin** keyfiyyətini təmin edirlər. + +{% if people %} +
+{% for user in people.top_translations_reviewers[:50] %} + +
@{{ user.login }}
Rəylər: {{ user.count }}
+{% endfor %} + +
+{% endif %} + +## Sponsorlar + +Bunlar **Sponsorlar**dır. 😎 + +Onlar mənim **FastAPI** (və digər) işlərimi əsasən GitHub Sponsorlar vasitəsilə dəstəkləyirlər. + +{% if sponsors %} + +{% if sponsors.gold %} + +### Qızıl Sponsorlar + +{% for sponsor in sponsors.gold -%} + +{% endfor %} +{% endif %} + +{% if sponsors.silver %} + +### Gümüş Sponsorlar + +{% for sponsor in sponsors.silver -%} + +{% endfor %} +{% endif %} + +{% if sponsors.bronze %} + +### Bürünc Sponsorlar + +{% for sponsor in sponsors.bronze -%} + +{% endfor %} +{% endif %} + +{% endif %} + +### Fərdi Sponsorlar + +{% if github_sponsors %} +{% for group in github_sponsors.sponsors %} + +
+ +{% for user in group %} +{% if user.login not in sponsors_badge.logins %} + + + +{% endif %} +{% endfor %} + +
+ +{% endfor %} +{% endif %} + +## Məlumatlar haqqında - texniki detallar + +Bu səhifənin əsas məqsədi, icmanın başqalarına kömək etmək üçün göstərdiyi əməyi vurğulamaqdır. + +Xüsusilə də normalda daha az görünən və bir çox hallarda daha çətin olan, başqalarının suallarına kömək etmək və tərcümələrlə bağlı Pull Request-lərə rəy vermək kimi səy göstərmək. + +Bu səhifənin məlumatları hər ay hesablanır və siz buradan mənbə kodunu oxuya bilərsiniz. + +Burada sponsorların əməyini də vurğulamaq istəyirəm. + +Mən həmçinin alqoritmi, bölmələri, eşikləri və s. yeniləmək hüququnu da qoruyuram (hər ehtimala qarşı 🤷). diff --git a/docs/az/docs/index.md b/docs/az/docs/index.md new file mode 100644 index 0000000000000..33bcc15568f17 --- /dev/null +++ b/docs/az/docs/index.md @@ -0,0 +1,469 @@ +

+ FastAPI +

+

+ FastAPI framework, yüksək məshuldarlı, öyrənməsi asan, çevik kodlama, istifadəyə hazırdır +

+

+ + Test + + + Əhatə + + + Paket versiyası + + + Dəstəklənən Python versiyaları + +

+ +--- + +**Sənədlər**: https://fastapi.tiangolo.com + +**Qaynaq Kodu**: https://github.com/tiangolo/fastapi + +--- + +FastAPI Python 3.8+ ilə API yaratmaq üçün standart Python tip məsləhətlərinə əsaslanan, müasir, sürətli (yüksək performanslı) framework-dür. + +Əsas xüsusiyyətləri bunlardır: + +* **Sürətli**: Çox yüksək performans, **NodeJS** və **Go** səviyyəsində (Starlette və Pydantic-ə təşəkkürlər). [Ən sürətli Python frameworklərindən biridir](#performans). +* **Çevik kodlama**: Funksiyanallıqları inkişaf etdirmək sürətini təxminən 200%-dən 300%-ə qədər artırın. * +* **Daha az xəta**: İnsan (developer) tərəfindən törədilən səhvlərin təxminən 40% -ni azaldın. * +* **İntuitiv**: Əla redaktor dəstəyi. Hər yerdə otomatik tamamlama. Xətaları müəyyənləşdirməyə daha az vaxt sərf edəcəksiniz. +* **Asan**: İstifadəsi və öyrənilməsi asan olması üçün nəzərdə tutulmuşdur. Sənədləri oxumaq üçün daha az vaxt ayıracaqsınız. +* **Qısa**: Kod təkrarlanmasını minimuma endirin. Hər bir parametr tərifində birdən çox xüsusiyyət ilə və daha az səhvlə qarşılaşacaqsınız. +* **Güclü**: Avtomatik və interaktiv sənədlərlə birlikdə istifadəyə hazır kod əldə edə bilərsiniz. +* **Standartlara əsaslanan**: API-lar üçün açıq standartlara əsaslanır (və tam uyğun gəlir): OpenAPI (əvvəlki adı ilə Swagger) və JSON Schema. + +* Bu fikirlər daxili development komandasının hazırladıqları məhsulların sınaqlarına əsaslanır. + +## Sponsorlar + + + +{% if sponsors %} +{% for sponsor in sponsors.gold -%} + +{% endfor -%}` +{%- for sponsor in sponsors.silver -%} + +{% endfor %} +{% endif %} + + + +Digər sponsorlar + +## Rəylər + +"_[...] Son günlərdə **FastAPI**-ı çox istifadə edirəm. [...] Əslində onu komandamın bütün **Microsoftda ML sevislərində** istifadə etməyi planlayıram. Onların bəziləri **windows**-un əsas məhsuluna və bəzi **Office** məhsullarına inteqrasiya olunurlar._" + +
Kabir Khan - Microsoft (ref)
+ +--- + +"_**FastAPI** kitabxanasını **Proqnozlar** əldə etmək üçün sorğulana bilən **REST** serverini yaratmaqda istifadə etdik._" + +
Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala - Uber (ref)
+ +--- + +"_**Netflix** **böhran idarəçiliyi** orkestrləşmə framework-nün açıq qaynaqlı buraxılışını elan etməkdən məmnundur: **Dispatch**! [**FastAPI** ilə quruldu]_" + +
Kevin Glisson, Marc Vilanova, Forest Monsen - Netflix (ref)
+ +--- + +"_**FastAPI** üçün həyəcanlıyam. Çox əyləncəlidir!_" + +
Brian Okken - Python Bytes podcast host (ref)
+ +--- + +"_Düzünü desəm, sizin qurduğunuz şey həqiqətən möhkəm və peşəkar görünür. Bir çox cəhətdən **Hug**-un olmasını istədiyim kimdir - kiminsə belə bir şey qurduğunu görmək həqiqətən ruhlandırıcıdır._" + +
Timothy Crosley - Hug creator (ref)
+ +--- + +"_Əgər REST API-lər yaratmaq üçün **müasir framework** öyrənmək istəyirsinizsə, **FastAPI**-a baxın [...] Sürətli, istifadəsi və öyrənməsi asandır. [...]_" + +"_**API** xidmətlərimizi **FastAPI**-a köçürdük [...] Sizin də bəyənəcəyinizi düşünürük._" + +
Ines Montani - Matthew Honnibal - Explosion AI founders - spaCy creators (ref) - (ref)
+ +--- + +"_Python ilə istifadəyə hazır API qurmaq istəyən hər kəsə **FastAPI**-ı tövsiyə edirəm. **Möhtəşəm şəkildə dizayn edilmiş**, **istifadəsi asan** və **yüksək dərəcədə genişlənə bilən**-dir, API əsaslı inkişaf strategiyamızın **əsas komponentinə** çevrilib və Virtual TAC Engineer kimi bir çox avtomatlaşdırma və servisləri idarə edir._" + +
Deon Pillsbury - Cisco (ref)
+ +--- + +## **Typer**, CLI-ların FastAPI-ı + + + +Əgər siz veb API əvəzinə terminalda istifadə ediləcək CLI proqramı qurursunuzsa, **Typer**-a baxa bilərsiniz. + +**Typer** FastAPI-ın kiçik qardaşıdır. Və o, CLI-lərin **FastAPI**-ı olmaq üçün nəzərdə tutulub. ⌨️ 🚀 + +## Tələblər + +Python 3.8+ + +FastAPI nəhənglərin çiyinlərində dayanır: + +* Web tərəfi üçün Starlette. +* Data tərəfi üçün Pydantic. + +## Quraşdırma + +
+ +```console +$ pip install fastapi + +---> 100% +``` + +
+ +Tətbiqimizi əlçatan etmək üçün bizə Uvicorn və ya Hypercorn kimi ASGI server lazımdır. + +
+ +```console +$ pip install "uvicorn[standard]" + +---> 100% +``` + +
+ +## Nümunə + +### Kodu yaradaq + +* `main.py` adlı fayl yaradaq və ona aşağıdakı kodu yerləşdirək: + +```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} +``` + +
+Və ya async def... + +Əgər kodunuzda `async` və ya `await` vardırsa `async def` istifadə edə bilərik: + +```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} +``` + +**Qeyd**: + +Əgər bu mövzu haqqında məlumatınız yoxdursa `async` və `await` sənədindəki _"Tələsirsən?"_ bölməsinə baxa bilərsiniz. + +
+ +### Kodu işə salaq + +Serveri aşağıdakı əmr ilə işə salaq: + +
+ +```console +$ uvicorn main:app --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +INFO: Started reloader process [28720] +INFO: Started server process [28722] +INFO: Waiting for application startup. +INFO: Application startup complete. +``` + +
+ +
+uvicorn main:app --reload əmri haqqında... + +`uvicorn main:app` əmri aşağıdakılara instinad edir: + +* `main`: `main.py` faylı (yəni Python "modulu"). +* `app`: `main.py` faylında `app = FastAPI()` sətrində yaratdığımız `FastAPI` obyektidir. +* `--reload`: kod dəyişikliyindən sonra avtomatik olaraq serveri yenidən işə salır. Bu parametrdən yalnız development mərhələsində istifadə etməliyik. + +
+ +### İndi yoxlayaq + +Bu linki brauzerimizdə açaq http://127.0.0.1:8000/items/5?q=somequery. + +Aşağıdakı kimi bir JSON cavabı görəcəksiniz: + +```JSON +{"item_id": 5, "q": "somequery"} +``` + +Siz artıq bir API yaratmısınız, hansı ki: + +* `/` və `/items/{item_id}` _yollarında_ HTTP sorğularını qəbul edir. +* Hər iki _yolda_ `GET` əməliyyatlarını (həmçinin HTTP _metodları_ kimi bilinir) aparır. +* `/items/{item_id}` _yolu_ `item_id` adlı `int` qiyməti almalı olan _yol parametrinə_ sahibdir. +* `/items/{item_id}` _yolunun_ `q` adlı yol parametri var və bu parametr istəyə bağlı olsa da, `str` qiymətini almalıdır. + +### İnteraktiv API Sənədləri + +İndi http://127.0.0.1:8000/docs ünvanına daxil olun. + +Avtomatik interaktiv API sənədlərini görəcəksiniz (Swagger UI tərəfindən təmin edilir): + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +### Alternativ API sənədləri + +İndi isə http://127.0.0.1:8000/redoc ünvanına daxil olun. + +ReDoc tərəfindən təqdim edilən avtomatik sənədləri görəcəksiniz: + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +## Nümunəni Yeniləyək + +İndi gəlin `main.py` faylını `PUT` sorğusu ilə birlikdə gövdə qəbul edəcək şəkildə dəyişdirək. + +Pydantic sayəsində standart Python tiplərindən istifadə edərək gövdəni müəyyən edək. + +```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} +``` +Server avtomatik olaraq yenidən işə salınmalı idi (çünki biz yuxarıda `uvicorn` əmri ilə `--reload` parametrindən istifadə etmişik). + +### İnteraktiv API sənədlərindəki dəyişikliyə baxaq + +Yenidən http://127.0.0.1:8000/docs ünvanına daxil olun. + +* İnteraktiv API sənədləri yeni gövdə də daxil olmaq ilə avtomatik olaraq yenilənəcək: + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) + +* "Try it out" düyməsini klikləyin, bu, parametrləri doldurmağa və API ilə birbaşa əlaqə saxlamağa imkan verir: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png) + +* Sonra "Execute" düyməsini klikləyin, istifadəçi interfeysi API ilə əlaqə quracaq, parametrləri göndərəcək, nəticələri əldə edəcək və onları ekranda göstərəcək: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png) + +### Alternativ API Sənədlərindəki Dəyişikliyə Baxaq + +İndi isə yenidən http://127.0.0.1:8000/redoc ünvanına daxil olun. + +* Alternativ sənədlər həm də yeni sorğu parametri və gövdəsini əks etdirəcək: + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) + +### Xülasə + +Ümumiləşdirsək, parametrlər, gövdə və s. Biz məlumat növlərini **bir dəfə** funksiya parametrləri kimi təyin edirik. + +Bunu standart müasir Python tipləri ilə edirsiniz. + +Yeni sintaksis, müəyyən bir kitabxananın metodlarını və ya siniflərini və s. öyrənmək məcburiyyətində deyilsiniz. + +Sadəcə standart **Python 3.8+**. + +Məsələn, `int` üçün: + +```Python +item_id: int +``` + +və ya daha mürəkkəb `Item` modeli üçün: + +```Python +item: Item +``` + +...və yalnız parametr tipini təyin etməklə bunları əldə edirsiniz: + +* Redaktor dəstəyi ilə: + * Avtomatik tamamlama. + * Tip yoxlanması. +* Məlumatların Təsdiqlənməsi: + * Məlumat etibarsız olduqda avtomatik olaraq aydın xətalar göstərir. + * Hətta çox dərin JSON obyektlərində belə doğrulama aparır. +* Daxil olan məlumatları çevirmək üçün aşağıdakı məlumat növlərindən istifadə edilir: + * JSON. + * Yol parametrləri. + * Sorğu parametrləri. + * Çərəzlər. + * Başlıqlaq. + * Formalar. + * Fayllar. +* Daxil olan məlumatları çevirmək üçün aşağıdakı məlumat növlərindən istifadə edilir (JSON olaraq): + * Python tiplərinin (`str`, `int`, `float`, `bool`, `list`, və s) çevrilməsi. + * `datetime` obyektləri. + * `UUID` obyektləri. + * Verilənlər bazası modelləri. + * və daha çoxu... +* 2 alternativ istifadəçi interfeysi daxil olmaqla avtomatik interaktiv API sənədlərini təmin edir: + * Swagger UI. + * ReDoc. + +--- + +Gəlin əvvəlki nümunəyə qayıdaq və **FastAPI**-nin nələr edəcəyinə nəzər salaq: + +* `GET` və `PUT` sorğuları üçün `item_id`-nin yolda olub-olmadığını yoxlayacaq. +* `item_id`-nin `GET` və `PUT` sorğuları üçün növünün `int` olduğunu yoxlayacaq. + * Əgər `int` deyilsə, səbəbini göstərən bir xəta mesajı göstərəcəkdir. +* məcburi olmayan `q` parametrinin `GET` (`http://127.0.0.1:8000/items/foo?q=somequery` burdakı kimi) sorğusu içərisində olub olmadığını yoxlayacaq. + * `q` parametrini `= None` ilə yaratdığımız üçün, məcburi olmayan parametr olacaq. + * Əgər `None` olmasaydı, bu məcburi parametr olardı (`PUT` metodunun gövdəsində olduğu kimi). +* `PUT` sorğusu üçün, `/items/{item_id}` gövdəsini JSON olaraq oxuyacaq: + * `name` adında məcburi bir parametr olub olmadığını və əgər varsa, tipinin `str` olub olmadığını yoxlayacaq. + * `price` adında məcburi bir parametr olub olmadığını və əgər varsa, tipinin `float` olub olmadığını yoxlayacaq. + * `is_offer` adında məcburi olmayan bir parametr olub olmadığını və əgər varsa, tipinin `float` olub olmadığını yoxlayacaq. + * Bütün bunlar ən dərin JSON obyektlərində belə işləyəcək. +* Məlumatların JSON-a və JSON-un Python obyektinə çevrilməsi avtomatik həyata keçiriləcək. +* Hər şeyi OpenAPI ilə uyğun olacaq şəkildə avtomatik olaraq sənədləşdirəcək və onları aşağıdakı kimi istifadə edə biləcək: + * İnteraktiv sənədləşmə sistemləri. + * Bir çox proqramlaşdırma dilləri üçün avtomatlaşdırılmış müştəri kodu yaratma sistemləri. +* 2 interaktiv sənədləşmə veb interfeysini birbaşa təmin edəcək. + +--- + +Yeni başlamışıq, amma siz artıq işin məntiqini başa düşmüsünüz. + +İndi aşağıdakı sətri dəyişdirməyə çalışın: + +```Python + return {"item_name": item.name, "item_id": item_id} +``` + +...bundan: + +```Python + ... "item_name": item.name ... +``` + +...buna: + +```Python + ... "item_price": item.price ... +``` + +...və redaktorun məlumat tiplərini bildiyini və avtomatik tamaladığını görəcəksiniz: + +![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) + +Daha çox funksiyaya malik daha dolğun nümunə üçün Öyrədici - İstifadəçi Təlimatı səhifəsinə baxa bilərsiniz. + +**Spoiler xəbərdarlığı**: Öyrədici - istifadəçi təlimatına bunlar daxildir: + +* **Parametrlərin**, **başlıqlar**, çərəzlər, **forma sahələri** və **fayllar** olaraq müəyyən edilməsi. +* `maximum_length` və ya `regex` kimi **doğrulama məhdudiyyətlərinin** necə təyin ediləcəyi. +* Çox güclü və istifadəsi asan **Dependency Injection** sistemi. +* Təhlükəsizlik və autentifikasiya, **JWT tokenləri** ilə **OAuth2** dəstəyi və **HTTP Basic** autentifikasiyası. +* **çox dərin JSON modellərini** müəyyən etmək üçün daha irəli səviyyə (lakin eyni dərəcədə asan) üsullar (Pydantic sayəsində). +* Strawberry və digər kitabxanalar ilə **GraphQL** inteqrasiyası. +* Digər əlavə xüsusiyyətlər (Starlette sayəsində): + * **WebSockets** + * HTTPX və `pytest` sayəsində çox asan testlər + * **CORS** + * **Cookie Sessions** + * ...və daha çoxu. + +## Performans + +Müstəqil TechEmpower meyarları göstərir ki, Uvicorn üzərində işləyən **FastAPI** proqramları ən sürətli Python kitabxanalarından biridir, yalnız Starlette və Uvicorn-un özündən yavaşdır, ki FastAPI bunların üzərinə qurulmuş bir framework-dür. (*) + +Ətraflı məlumat üçün bu bölməyə nəzər salın Müqayisələr. + +## Məcburi Olmayan Tələblər + +Pydantic tərəfindən istifadə olunanlar: + +* email_validator - e-poçtun yoxlanılması üçün. +* pydantic-settings - parametrlərin idarə edilməsi üçün. +* pydantic-extra-types - Pydantic ilə istifadə edilə bilən əlavə tiplər üçün. + +Starlette tərəfindən istifadə olunanlar: + +* httpx - Əgər `TestClient` strukturundan istifadə edəcəksinizsə, tələb olunur. +* jinja2 - Standart şablon konfiqurasiyasından istifadə etmək istəyirsinizsə, tələb olunur. +* python-multipart - `request.form()` ilə forma "çevirmə" dəstəyindən istifadə etmək istəyirsinizsə, tələb olunur. +* itsdangerous - `SessionMiddleware` dəstəyi üçün tələb olunur. +* pyyaml - `SchemaGenerator` dəstəyi üçün tələb olunur (Çox güman ki, FastAPI istifadə edərkən buna ehtiyacınız olmayacaq). +* ujson - `UJSONResponse` istifadə etmək istəyirsinizsə, tələb olunur. + +Həm FastAPI, həm də Starlette tərəfindən istifadə olunur: + +* uvicorn - Yaratdığımız proqramı servis edəcək veb server kimi fəaliyyət göstərir. +* orjson - `ORJSONResponse` istifadə edəcəksinizsə tələb olunur. + +Bütün bunları `pip install fastapi[all]` ilə quraşdıra bilərsiniz. + +## Lisenziya + +Bu layihə MIT lisenziyasının şərtlərinə əsasən lisenziyalaşdırılıb. diff --git a/docs/az/docs/learn/index.md b/docs/az/docs/learn/index.md new file mode 100644 index 0000000000000..cc32108bf1504 --- /dev/null +++ b/docs/az/docs/learn/index.md @@ -0,0 +1,5 @@ +# Öyrən + +Burada **FastAPI** öyrənmək üçün giriş bölmələri və dərsliklər yer alır. + +Siz bunu kitab, kurs, FastAPI öyrənmək üçün rəsmi və tövsiyə olunan üsul hesab edə bilərsiniz. 😎 diff --git a/docs/az/mkdocs.yml b/docs/az/mkdocs.yml new file mode 100644 index 0000000000000..de18856f445aa --- /dev/null +++ b/docs/az/mkdocs.yml @@ -0,0 +1 @@ +INHERIT: ../en/mkdocs.yml diff --git a/docs/bn/docs/index.md b/docs/bn/docs/index.md new file mode 100644 index 0000000000000..688f3f95ac25f --- /dev/null +++ b/docs/bn/docs/index.md @@ -0,0 +1,464 @@ +

+ FastAPI +

+

+ FastAPI উচ্চক্ষমতা সম্পন্ন, সহজে শেখার এবং দ্রুত কোড করে প্রোডাকশনের জন্য ফ্রামওয়ার্ক। +

+

+ + Test + + + Coverage + + + Package version + +

+ +--- + +**নির্দেশিকা নথি**: https://fastapi.tiangolo.com + +**সোর্স কোড**: https://github.com/tiangolo/fastapi + +--- + +FastAPI একটি আধুনিক, দ্রুত ( বেশি ক্ষমতা ) সম্পন্ন, Python 3.6+ দিয়ে API তৈরির জন্য স্ট্যান্ডার্ড পাইথন টাইপ ইঙ্গিত ভিত্তিক ওয়েব ফ্রেমওয়ার্ক। + +এর মূল বৈশিষ্ট্য গুলো হলঃ + +- **গতি**: এটি **NodeJS** এবং **Go** এর মত কার্যক্ষমতা সম্পন্ন (Starlette এবং Pydantic এর সাহায্যে)। [পাইথন এর দ্রুততম ফ্রেমওয়ার্ক গুলোর মধ্যে এটি একটি](#_11)। +- **দ্রুত কোড করা**:বৈশিষ্ট্য তৈরির গতি ২০০% থেকে ৩০০% বৃদ্ধি করে৷ \* +- **স্বল্প bugs**: মানুব (ডেভেলপার) সৃষ্ট ত্রুটির প্রায় ৪০% হ্রাস করে। \* +- **স্বজ্ঞাত**: দুর্দান্ত এডিটর সাহায্য Completion নামেও পরিচিত। দ্রুত ডিবাগ করা যায়। + +- **সহজ**: এটি এমন ভাবে সজানো হয়েছে যেন নির্দেশিকা নথি পড়ে সহজে শেখা এবং ব্যবহার করা যায়। +- **সংক্ষিপ্ত**: কোড পুনরাবৃত্তি কমানোর পাশাপাশি, bug কমায় এবং প্রতিটি প্যারামিটার ঘোষণা থেকে একাধিক ফিচার পাওয়া যায় । +- **জোরালো**: স্বয়ংক্রিয় ভাবে তৈরি ক্রিয়াশীল নির্দেশনা নথি (documentation) সহ উৎপাদন উপযোগি (Production-ready) কোড পাওয়া যায়। +- **মান-ভিত্তিক**: এর ভিত্তি OpenAPI (যা পুর্বে Swagger নামে পরিচিত ছিল) এবং JSON Schema এর আদর্শের মানের ওপর + +\* উৎপাদনমুখি এপ্লিকেশন বানানোর এক দল ডেভেলপার এর মতামত ভিত্তিক ফলাফল। + +## স্পনসর গণ + + + +{% if sponsors %} +{% for sponsor in sponsors.gold -%} + +{% endfor -%} +{%- for sponsor in sponsors.silver -%} + +{% endfor %} +{% endif %} + + + +অন্যান্য স্পনসর গণ + +## মতামত সমূহ + +"_আমি আজকাল **FastAPI** ব্যবহার করছি। [...] আমরা ভাবছি মাইক্রোসফ্টে **ML সার্ভিস** এ সকল দলের জন্য এটি ব্যবহার করব। যার মধ্যে কিছু পণ্য **Windows** এ সংযোযন হয় এবং কিছু **Office** এর সাথে সংযোযন হচ্ছে।_" + +
কবির খান - মাইক্রোসফ্টে (ref)
+ +--- + +"_আমরা **FastAPI** লাইব্রেরি গ্রহণ করেছি একটি **REST** সার্ভার তৈরি করতে, যা **ভবিষ্যদ্বাণী** পাওয়ার জন্য কুয়েরি করা যেতে পারে। [লুডউইগের জন্য]_" + +
পিয়েরো মোলিনো, ইয়ারোস্লাভ দুদিন, এবং সাই সুমন্থ মিরিয়ালা - উবার (ref)
+ +--- + +"_**Netflix** আমাদের **ক্রাইসিস ম্যানেজমেন্ট** অর্কেস্ট্রেশন ফ্রেমওয়ার্ক: **ডিসপ্যাচ** এর ওপেন সোর্স রিলিজ ঘোষণা করতে পেরে আনন্দিত! [যাকিনা **FastAPI** দিয়ে নির্মিত]_" + +
কেভিন গ্লিসন, মার্ক ভিলানোভা, ফরেস্ট মনসেন - নেটফ্লিক্স (ref)
+ +--- + +"_আমি **FastAPI** নিয়ে চাঁদের সমান উৎসাহিত। এটি খুবই মজার!_" + +
ব্রায়ান ওকেন - পাইথন বাইটস পডকাস্ট হোস্ট (ref)
+ +--- + +"\_সত্যিই, আপনি যা তৈরি করেছেন তা খুব মজবুত এবং পরিপূর্ন৷ অনেক উপায়ে, আমি যা **Hug** এ করতে চেয়েছিলাম - তা কাউকে তৈরি করতে দেখে আমি সত্যিই অনুপ্রানিত৷\_" + +
টিমোথি ক্রসলে - Hug স্রষ্টা (ref)
+ +--- + +"আপনি যদি REST API তৈরির জন্য একটি **আধুনিক ফ্রেমওয়ার্ক** শিখতে চান, তাহলে **FastAPI** দেখুন [...] এটি দ্রুত, ব্যবহার করা সহজ এবং শিখতেও সহজ [...]\_" + +"_আমরা আমাদের **APIs** [...] এর জন্য **FastAPI**- তে এসেছি [...] আমি মনে করি আপনিও এটি পছন্দ করবেন [...]_" + +
ইনেস মন্টানি - ম্যাথিউ হোনিবাল - Explosion AI প্রতিষ্ঠাতা - spaCy স্রষ্টা (ref) - (ref)
+ +--- + +## **Typer**, CLI এর জন্য FastAPI + + + +আপনি যদি CLI অ্যাপ বানাতে চান, যা কিনা ওয়েব API এর পরিবর্তে টার্মিনালে ব্যবহার হবে, তাহলে দেখুন**Typer**. + +**টাইপার** হল FastAPI এর ছোট ভাইয়ের মত। এবং এটির উদ্দেশ্য ছিল **CLIs এর FastAPI** হওয়া। ⌨️ 🚀 + +## প্রয়োজনীয়তা গুলো + +Python 3.7+ + +FastAPI কিছু দানবেদের কাঁধে দাঁড়িয়ে আছে: + +- Starlette ওয়েব অংশের জন্য. +- Pydantic ডেটা অংশগুলির জন্য. + +## ইনস্টলেশন প্রক্রিয়া + +
+ +```console +$ pip install fastapi + +---> 100% +``` + +
+ +আপনার একটি ASGI সার্ভারেরও প্রয়োজন হবে, প্রোডাকশনের জন্য Uvicorn অথবা Hypercorn. + +
+ +```console +$ pip install "uvicorn[standard]" + +---> 100% +``` + +
+ +## উদাহরণ + +### তৈরি + +- `main.py` নামে একটি ফাইল তৈরি করুন: + +```Python +from typing import Union + +from fastapi import FastAPI + +app = FastAPI() + + +@app.get("/") +def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} +``` + +
+অথবা ব্যবহার করুন async def... + +যদি আপনার কোড `async` / `await`, ব্যবহার করে তাহলে `async def` ব্যবহার করুন: + +```Python hl_lines="9 14" +from typing import Union + +from fastapi import FastAPI + +app = FastAPI() + + +@app.get("/") +async def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +async def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} +``` + +**টীকা**: + +আপনি যদি না জানেন, _"তাড়াহুড়ো?"_ বিভাগটি দেখুন `async` এবং `await` নথির মধ্যে দেখুন . + +
+ +### এটি চালান + +সার্ভার চালু করুন: + +
+ +```console +$ uvicorn main:app --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +INFO: Started reloader process [28720] +INFO: Started server process [28722] +INFO: Waiting for application startup. +INFO: Application startup complete. +``` + +
+ +
+নির্দেশনা সম্পর্কে uvicorn main:app --reload... + +`uvicorn main:app` নির্দেশনাটি দ্বারা বোঝায়: + +- `main`: ফাইল `main.py` (পাইথন "মডিউল")। +- `app`: `app = FastAPI()` লাইন দিয়ে `main.py` এর ভিতরে তৈরি করা অবজেক্ট। +- `--reload`: কোড পরিবর্তনের পরে সার্ভার পুনরায় চালু করুন। এটি শুধুমাত্র ডেভেলপমেন্ট এর সময় ব্যবহার করুন। + +
+ +### এটা চেক করুন + +আপনার ব্রাউজার খুলুন http://127.0.0.1:8000/items/5?q=somequery এ। + +আপনি JSON রেসপন্স দেখতে পাবেন: + +```JSON +{"item_id": 5, "q": "somequery"} +``` + +আপনি ইতিমধ্যে একটি API তৈরি করেছেন যা: + +- `/` এবং `/items/{item_id}` _paths_ এ HTTP অনুরোধ গ্রহণ করে। +- উভয় *path*ই `GET` অপারেশন নেয় ( যা HTTP _methods_ নামেও পরিচিত)। +- _path_ `/items/{item_id}`-এ একটি _path প্যারামিটার_ `item_id` আছে যা কিনা `int` হতে হবে। +- _path_ `/items/{item_id}`-এর একটি ঐচ্ছিক `str` _query প্যারামিটার_ `q` আছে। + +### ক্রিয়াশীল API নির্দেশিকা নথি + +এখন যান http://127.0.0.1:8000/docs. + +আপনি স্বয়ংক্রিয় ভাবে প্রস্তুত ক্রিয়াশীল API নির্দেশিকা নথি দেখতে পাবেন (Swagger UI প্রদত্ত): + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +### বিকল্প API নির্দেশিকা নথি + +এবং এখন http://127.0.0.1:8000/redoc এ যান. + +আপনি স্বয়ংক্রিয় ভাবে প্রস্তুত বিকল্প নির্দেশিকা নথি দেখতে পাবেন (ReDoc প্রদত্ত): + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +## উদাহরণস্বরূপ আপগ্রেড + +এখন `main.py` ফাইলটি পরিবর্তন করুন যেন এটি `PUT` রিকুয়েস্ট থেকে বডি পেতে পারে। + +Python স্ট্যান্ডার্ড লাইব্রেরি, 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} +``` + +সার্ভারটি স্বয়ংক্রিয়ভাবে পুনরায় লোড হওয়া উচিত (কারণ আপনি উপরের `uvicorn` কমান্ডে `--reload` যোগ করেছেন)। + +### ক্রিয়াশীল API নির্দেশিকা নথি উন্নীতকরণ + +এখন http://127.0.0.1:8000/docs এডড্রেসে যান. + +- ক্রিয়াশীল API নির্দেশিকা নথিটি স্বয়ংক্রিয়ভাবে উন্নীত হযে যাবে, নতুন বডি সহ: + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) + +- "Try it out" বাটনে চাপুন, এটি আপনাকে পেরামিটারগুলো পূরণ করতে এবং API এর সাথে সরাসরি ক্রিয়া-কলাপ করতে দিবে: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png) + +- তারপরে "Execute" বাটনে চাপুন, ব্যবহারকারীর ইন্টারফেস আপনার API এর সাথে যোগাযোগ করবে, পেরামিটার পাঠাবে, ফলাফলগুলি পাবে এবং সেগুলি পর্রদায় দেখাবে: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png) + +### বিকল্প API নির্দেশিকা নথি আপগ্রেড + +এবং এখন http://127.0.0.1:8000/redoc এ যান। + +- বিকল্প নির্দেশিকা নথিতেও নতুন কুয়েরি প্যারামিটার এবং বডি প্রতিফলিত হবে: + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) + +### সংক্ষিপ্তকরণ + +সংক্ষেপে, আপনি **শুধু একবার** প্যারামিটারের ধরন, বডি ইত্যাদি ফাংশন প্যারামিটার হিসেবে ঘোষণা করেন। + +আপনি সেটি আধুনিক পাইথনের সাথে করেন। + +আপনাকে নতুন করে নির্দিষ্ট কোন লাইব্রেরির বাক্য গঠন, ফাংশন বা ক্লাস কিছুই শিখতে হচ্ছে না। + +শুধুই আধুনিক **Python 3.6+** + +উদাহরণস্বরূপ, `int` এর জন্য: + +```Python +item_id: int +``` + +অথবা আরও জটিল `Item` মডেলের জন্য: + +```Python +item: Item +``` + +...এবং সেই একই ঘোষণার সাথে আপনি পাবেন: + +- এডিটর সাহায্য, যেমন + - সমাপ্তি। + - ধরণ যাচাই +- তথ্য যাচাইকরণ: + - ডেটা অবৈধ হলে স্বয়ংক্রিয় এবং পরিষ্কার ত্রুটির নির্দেশনা। + - এমনকি গভীরভাবে নেস্ট করা JSON অবজেক্টের জন্য বৈধতা। +- প্রেরিত তথ্য রূপান্তর: যা নেটওয়ার্ক থেকে পাইথনের তথ্য এবং ধরনে আসে, এবং সেখান থেকে পড়া: + + - JSON। + - পাথ প্যারামিটার। + - কুয়েরি প্যারামিটার। + - কুকিজ + - হেডার + - ফর্ম + - ফাইল + +- আউটপুট ডেটার রূপান্তর: পাইথন ডেটা এবং টাইপ থেকে নেটওয়ার্ক ডেটাতে রূপান্তর করা (JSON হিসাবে): + -পাইথন টাইপে রূপান্তর করুন (`str`, `int`, `float`, `bool`, `list`, ইত্যাদি)। + - `datetime` অবজেক্ট। + - `UUID` objeঅবজেক্টcts। + - ডাটাবেস মডেল। + - ...এবং আরো অনেক। +- স্বয়ংক্রিয় ক্রিয়াশীল API নির্দেশিকা নথি, 2টি বিকল্প ব্যবহারকারীর ইন্টারফেস সহ: + - সোয়াগার ইউ আই (Swagger UI)। + - রিডক (ReDoc)। + +--- + +পূর্ববর্তী কোড উদাহরণে ফিরে আসা যাক, **FastAPI** যা করবে: + +- `GET` এবং `PUT` অনুরোধের জন্য পথে `item_id` আছে কিনা তা যাচাই করবে। +- `GET` এবং `PUT` অনুরোধের জন্য `item_id` টাইপ `int` এর হতে হবে তা যাচাই করবে। + - যদি না হয় তবে ক্লায়েন্ট একটি উপযুক্ত, পরিষ্কার ত্রুটি দেখতে পাবেন। +- `GET` অনুরোধের জন্য একটি ঐচ্ছিক ক্যুয়েরি প্যারামিটার নামক `q` (যেমন `http://127.0.0.1:8000/items/foo?q=somequery`) আছে কি তা চেক করবে। + - যেহেতু `q` প্যারামিটারটি `= None` দিয়ে ঘোষণা করা হয়েছে, তাই এটি ঐচ্ছিক। + - `None` ছাড়া এটি প্রয়োজনীয় হতো (যেমন `PUT` এর ক্ষেত্রে হয়েছে)। +- `/items/{item_id}` এর জন্য `PUT` অনুরোধের বডি JSON হিসাবে পড়ুন: + - লক্ষ করুন, `name` একটি প্রয়োজনীয় অ্যাট্রিবিউট হিসাবে বিবেচনা করেছে এবং এটি `str` হতে হবে। + - লক্ষ করুন এখানে, `price` অ্যাট্রিবিউটটি আবশ্যক এবং এটি `float` হতে হবে। + - লক্ষ করুন `is_offer` একটি ঐচ্ছিক অ্যাট্রিবিউট এবং এটি `bool` হতে হবে যদি উপস্থিত থাকে। + - এই সবটি গভীরভাবে অবস্থানরত JSON অবজেক্টগুলিতেও কাজ করবে। +- স্বয়ংক্রিয়ভাবে JSON হতে এবং JSON থেকে কনভার্ট করুন। +- OpenAPI দিয়ে সবকিছু ডকুমেন্ট করুন, যা ব্যবহার করা যেতে পারে: + - ক্রিয়াশীল নির্দেশিকা নথি। + - অনেক ভাষার জন্য স্বয়ংক্রিয় ক্লায়েন্ট কোড তৈরির ব্যবস্থা। +- সরাসরি 2টি ক্রিয়াশীল নির্দেশিকা নথি ওয়েব পৃষ্ঠ প্রদান করা হয়েছে। + +--- + +আমরা এতক্ষন শুধু এর পৃষ্ঠ তৈরি করেছি, কিন্তু আপনি ইতমধ্যেই এটি কিভাবে কাজ করে তার ধারণাও পেয়ে গিয়েছেন। + +নিম্নোক্ত লাইন গুলো পরিবর্তন করার চেষ্টা করুন: + +```Python + return {"item_name": item.name, "item_id": item_id} +``` + +...পুর্বে: + +```Python + ... "item_name": item.name ... +``` + +...পরবর্তীতে: + +```Python + ... "item_price": item.price ... +``` + +...এবং দেখুন কিভাবে আপনার এডিটর উপাদানগুলোকে সয়ংক্রিয়ভাবে-সম্পন্ন করবে এবং তাদের ধরন জানতে পারবে: + +![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) + +আরও বৈশিষ্ট্য সম্পন্ন উদাহরণের জন্য, দেখুন টিউটোরিয়াল - ব্যবহারকারীর গাইড. + +**স্পয়লার সতর্কতা**: টিউটোরিয়াল - ব্যবহারকারীর গাইড নিম্নোক্ত বিষয়গুলি অন্তর্ভুক্ত করে: + +- **হেডার**, **কুকিজ**, **ফর্ম ফিল্ড** এবং **ফাইলগুলি** এমন অন্যান্য জায়গা থেকে প্যারামিটার ঘোষণা করা। +- `maximum_length` বা `regex` এর মতো **যাচাইকরণ বাধামুক্তি** সেট করা হয় কিভাবে, তা নিয়ে আলোচনা করা হবে। +- একটি খুব শক্তিশালী এবং ব্যবহার করা সহজ ডিপেন্ডেন্সি ইনজেকশন পদ্ধতি +- **OAuth2** এবং **JWT টোকেন** এবং **HTTP Basic** auth সহ নিরাপত্তা এবং অনুমোদনপ্রাপ্তি সম্পর্কিত বিষয়সমূহের উপর। +- **গভীরভাবে অবস্থানরত JSON মডেল** ঘোষণা করার জন্য আরও উন্নত (কিন্তু সমান সহজ) কৌশল (Pydantic কে ধন্যবাদ)। +- আরো অতিরিক্ত বৈশিষ্ট্য (স্টারলেটকে ধন্যবাদ) হিসাবে: + - **WebSockets** + - **GraphQL** + - HTTPX এবং `pytest` ভিত্তিক অত্যন্ত সহজ পরীক্ষা + - **CORS** + - **Cookie Sessions** + - ...এবং আরো। + +## কর্মক্ষমতা + +স্বাধীন TechEmpower Benchmarks দেখায় যে **FastAPI** অ্যাপ্লিকেশনগুলি Uvicorn-এর অধীনে চলমান দ্রুততমপাইথন ফ্রেমওয়ার্কগুলির মধ্যে একটি, শুধুমাত্র Starlette এবং Uvicorn-এর পর (FastAPI দ্বারা অভ্যন্তরীণভাবে ব্যবহৃত)। (\*) + +এটি সম্পর্কে আরও বুঝতে, দেখুন Benchmarks. + +## ঐচ্ছিক নির্ভরশীলতা + +Pydantic দ্বারা ব্যবহৃত: + +- ujson - দ্রুত JSON এর জন্য "parsing". +- email_validator - ইমেল যাচাইকরণের জন্য। + +স্টারলেট দ্বারা ব্যবহৃত: + +- httpx - আপনি যদি `TestClient` ব্যবহার করতে চান তাহলে আবশ্যক। +- jinja2 - আপনি যদি প্রদত্ত টেমপ্লেট রূপরেখা ব্যবহার করতে চান তাহলে প্রয়োজন। +- python-multipart - আপনি যদি ফর্ম সহায়তা করতে চান তাহলে প্রয়োজন "parsing", `request.form()` সহ। +- itsdangerous - `SessionMiddleware` সহায়তার জন্য প্রয়োজন। +- pyyaml - স্টারলেটের SchemaGenerator সাপোর্ট এর জন্য প্রয়োজন (আপনার সম্ভাবত FastAPI প্রয়োজন নেই)। +- graphene - `GraphQLApp` সহায়তার জন্য প্রয়োজন। +- ujson - আপনি `UJSONResponse` ব্যবহার করতে চাইলে প্রয়োজন। + +FastAPI / Starlette দ্বারা ব্যবহৃত: + +- uvicorn - সার্ভারের জন্য যা আপনার অ্যাপ্লিকেশন লোড করে এবং পরিবেশন করে। +- orjson - আপনি `ORJSONResponse` ব্যবহার করতে চাইলে প্রয়োজন। + +আপনি এই সব ইনস্টল করতে পারেন `pip install fastapi[all]` দিয়ে. + +## লাইসেন্স + +এই প্রজেক্ট MIT লাইসেন্স নীতিমালার অধীনে শর্তায়িত। diff --git a/docs/bn/docs/learn/index.md b/docs/bn/docs/learn/index.md new file mode 100644 index 0000000000000..4e4c62038cfae --- /dev/null +++ b/docs/bn/docs/learn/index.md @@ -0,0 +1,5 @@ +# শিখুন + +এখানে **FastAPI** শিখার জন্য প্রাথমিক বিভাগগুলি এবং টিউটোরিয়ালগুলি রয়েছে। + +আপনি এটিকে একটি **বই**, একটি **কোর্স**, এবং FastAPI শিখার **অফিসিয়াল** এবং প্রস্তাবিত উপায় বিবেচনা করতে পারেন। 😎 diff --git a/docs/bn/mkdocs.yml b/docs/bn/mkdocs.yml new file mode 100644 index 0000000000000..de18856f445aa --- /dev/null +++ b/docs/bn/mkdocs.yml @@ -0,0 +1 @@ +INHERIT: ../en/mkdocs.yml diff --git a/docs/de/docs/about/index.md b/docs/de/docs/about/index.md new file mode 100644 index 0000000000000..4c309e02a5adf --- /dev/null +++ b/docs/de/docs/about/index.md @@ -0,0 +1,3 @@ +# Über + +Über FastAPI, sein Design, seine Inspiration und mehr. 🤓 diff --git a/docs/de/docs/advanced/additional-responses.md b/docs/de/docs/advanced/additional-responses.md new file mode 100644 index 0000000000000..2bfcfab334ea3 --- /dev/null +++ b/docs/de/docs/advanced/additional-responses.md @@ -0,0 +1,240 @@ +# Zusätzliche Responses in OpenAPI + +!!! warning "Achtung" + Dies ist ein eher fortgeschrittenes Thema. + + Wenn Sie mit **FastAPI** beginnen, benötigen Sie dies möglicherweise nicht. + +Sie können zusätzliche Responses mit zusätzlichen Statuscodes, Medientypen, Beschreibungen, usw. deklarieren. + +Diese zusätzlichen Responses werden in das OpenAPI-Schema aufgenommen, sodass sie auch in der API-Dokumentation erscheinen. + +Für diese zusätzlichen Responses müssen Sie jedoch sicherstellen, dass Sie eine `Response`, wie etwa `JSONResponse`, direkt zurückgeben, mit Ihrem Statuscode und Inhalt. + +## Zusätzliche Response mit `model` + +Sie können Ihren *Pfadoperation-Dekoratoren* einen Parameter `responses` übergeben. + +Der nimmt ein `dict` entgegen, die Schlüssel sind Statuscodes für jede Response, wie etwa `200`, und die Werte sind andere `dict`s mit den Informationen für jede Response. + +Jedes dieser Response-`dict`s kann einen Schlüssel `model` haben, welcher ein Pydantic-Modell enthält, genau wie `response_model`. + +**FastAPI** nimmt dieses Modell, generiert dessen JSON-Schema und fügt es an der richtigen Stelle in OpenAPI ein. + +Um beispielsweise eine weitere Response mit dem Statuscode `404` und einem Pydantic-Modell `Message` zu deklarieren, können Sie schreiben: + +```Python hl_lines="18 22" +{!../../../docs_src/additional_responses/tutorial001.py!} +``` + +!!! note "Hinweis" + Beachten Sie, dass Sie die `JSONResponse` direkt zurückgeben müssen. + +!!! info + Der `model`-Schlüssel ist nicht Teil von OpenAPI. + + **FastAPI** nimmt das Pydantic-Modell von dort, generiert das JSON-Schema und fügt es an der richtigen Stelle ein. + + Die richtige Stelle ist: + + * Im Schlüssel `content`, der als Wert ein weiteres JSON-Objekt (`dict`) hat, welches Folgendes enthält: + * Ein Schlüssel mit dem Medientyp, z. B. `application/json`, der als Wert ein weiteres JSON-Objekt hat, welches Folgendes enthält: + * Ein Schlüssel `schema`, der als Wert das JSON-Schema aus dem Modell hat, hier ist die richtige Stelle. + * **FastAPI** fügt hier eine Referenz auf die globalen JSON-Schemas an einer anderen Stelle in Ihrer OpenAPI hinzu, anstatt es direkt einzubinden. Auf diese Weise können andere Anwendungen und Clients diese JSON-Schemas direkt verwenden, bessere Tools zur Codegenerierung bereitstellen, usw. + +Die generierten Responses in der OpenAPI für diese *Pfadoperation* lauten: + +```JSON hl_lines="3-12" +{ + "responses": { + "404": { + "description": "Additional Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Message" + } + } + } + }, + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Item" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } +} +``` + +Die Schemas werden von einer anderen Stelle innerhalb des OpenAPI-Schemas referenziert: + +```JSON hl_lines="4-16" +{ + "components": { + "schemas": { + "Message": { + "title": "Message", + "required": [ + "message" + ], + "type": "object", + "properties": { + "message": { + "title": "Message", + "type": "string" + } + } + }, + "Item": { + "title": "Item", + "required": [ + "id", + "value" + ], + "type": "object", + "properties": { + "id": { + "title": "Id", + "type": "string" + }, + "value": { + "title": "Value", + "type": "string" + } + } + }, + "ValidationError": { + "title": "ValidationError", + "required": [ + "loc", + "msg", + "type" + ], + "type": "object", + "properties": { + "loc": { + "title": "Location", + "type": "array", + "items": { + "type": "string" + } + }, + "msg": { + "title": "Message", + "type": "string" + }, + "type": { + "title": "Error Type", + "type": "string" + } + } + }, + "HTTPValidationError": { + "title": "HTTPValidationError", + "type": "object", + "properties": { + "detail": { + "title": "Detail", + "type": "array", + "items": { + "$ref": "#/components/schemas/ValidationError" + } + } + } + } + } + } +} +``` + +## Zusätzliche Medientypen für die Haupt-Response + +Sie können denselben `responses`-Parameter verwenden, um verschiedene Medientypen für dieselbe Haupt-Response hinzuzufügen. + +Sie können beispielsweise einen zusätzlichen Medientyp `image/png` hinzufügen und damit deklarieren, dass Ihre *Pfadoperation* ein JSON-Objekt (mit dem Medientyp `application/json`) oder ein PNG-Bild zurückgeben kann: + +```Python hl_lines="19-24 28" +{!../../../docs_src/additional_responses/tutorial002.py!} +``` + +!!! note "Hinweis" + Beachten Sie, dass Sie das Bild direkt mit einer `FileResponse` zurückgeben müssen. + +!!! info + Sofern Sie in Ihrem Parameter `responses` nicht explizit einen anderen Medientyp angeben, geht FastAPI davon aus, dass die Response denselben Medientyp wie die Haupt-Response-Klasse hat (Standardmäßig `application/json`). + + Wenn Sie jedoch eine benutzerdefinierte Response-Klasse mit `None` als Medientyp angegeben haben, verwendet FastAPI `application/json` für jede zusätzliche Response, die über ein zugehöriges Modell verfügt. + +## Informationen kombinieren + +Sie können auch Response-Informationen von mehreren Stellen kombinieren, einschließlich der Parameter `response_model`, `status_code` und `responses`. + +Sie können ein `response_model` deklarieren, indem Sie den Standardstatuscode `200` (oder bei Bedarf einen benutzerdefinierten) verwenden und dann zusätzliche Informationen für dieselbe Response in `responses` direkt im OpenAPI-Schema deklarieren. + +**FastAPI** behält die zusätzlichen Informationen aus `responses` und kombiniert sie mit dem JSON-Schema aus Ihrem Modell. + +Sie können beispielsweise eine Response mit dem Statuscode `404` deklarieren, die ein Pydantic-Modell verwendet und über eine benutzerdefinierte Beschreibung (`description`) verfügt. + +Und eine Response mit dem Statuscode `200`, die Ihr `response_model` verwendet, aber ein benutzerdefiniertes Beispiel (`example`) enthält: + +```Python hl_lines="20-31" +{!../../../docs_src/additional_responses/tutorial003.py!} +``` + +Es wird alles kombiniert und in Ihre OpenAPI eingebunden und in der API-Dokumentation angezeigt: + + + +## Vordefinierte und benutzerdefinierte Responses kombinieren + +Möglicherweise möchten Sie einige vordefinierte Responses haben, die für viele *Pfadoperationen* gelten, Sie möchten diese jedoch mit benutzerdefinierten Responses kombinieren, die für jede *Pfadoperation* erforderlich sind. + +In diesen Fällen können Sie die Python-Technik zum „Entpacken“ eines `dict`s mit `**dict_to_unpack` verwenden: + +```Python +old_dict = { + "old key": "old value", + "second old key": "second old value", +} +new_dict = {**old_dict, "new key": "new value"} +``` + +Hier wird `new_dict` alle Schlüssel-Wert-Paare von `old_dict` plus das neue Schlüssel-Wert-Paar enthalten: + +```Python +{ + "old key": "old value", + "second old key": "second old value", + "new key": "new value", +} +``` + +Mit dieser Technik können Sie einige vordefinierte Responses in Ihren *Pfadoperationen* wiederverwenden und sie mit zusätzlichen benutzerdefinierten Responses kombinieren. + +Zum Beispiel: + +```Python hl_lines="13-17 26" +{!../../../docs_src/additional_responses/tutorial004.py!} +``` + +## Weitere Informationen zu OpenAPI-Responses + +Um zu sehen, was genau Sie in die Responses aufnehmen können, können Sie die folgenden Abschnitte in der OpenAPI-Spezifikation überprüfen: + +* OpenAPI Responses Object, enthält das `Response Object`. +* OpenAPI Response Object, Sie können alles davon direkt in jede Response innerhalb Ihres `responses`-Parameter einfügen. Einschließlich `description`, `headers`, `content` (darin deklarieren Sie verschiedene Medientypen und JSON-Schemas) und `links`. diff --git a/docs/de/docs/advanced/additional-status-codes.md b/docs/de/docs/advanced/additional-status-codes.md new file mode 100644 index 0000000000000..e9de267cf9039 --- /dev/null +++ b/docs/de/docs/advanced/additional-status-codes.md @@ -0,0 +1,69 @@ +# Zusätzliche Statuscodes + +Standardmäßig liefert **FastAPI** die Rückgabewerte (Responses) als `JSONResponse` zurück und fügt den Inhalt der jeweiligen *Pfadoperation* in das `JSONResponse` Objekt ein. + +Es wird der Default-Statuscode oder derjenige verwendet, den Sie in Ihrer *Pfadoperation* festgelegt haben. + +## Zusätzliche Statuscodes + +Wenn Sie neben dem Hauptstatuscode weitere Statuscodes zurückgeben möchten, können Sie dies tun, indem Sie direkt eine `Response` zurückgeben, wie etwa eine `JSONResponse`, und den zusätzlichen Statuscode direkt festlegen. + +Angenommen, Sie möchten eine *Pfadoperation* haben, die das Aktualisieren von Artikeln ermöglicht und bei Erfolg den HTTP-Statuscode 200 „OK“ zurückgibt. + +Sie möchten aber auch, dass sie neue Artikel akzeptiert. Und wenn die Elemente vorher nicht vorhanden waren, werden diese Elemente erstellt und der HTTP-Statuscode 201 „Created“ zurückgegeben. + +Um dies zu erreichen, importieren Sie `JSONResponse`, und geben Sie Ihren Inhalt direkt zurück, indem Sie den gewünschten `status_code` setzen: + +=== "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.8+" + + ```Python hl_lines="4 26" + {!> ../../../docs_src/additional_status_codes/tutorial001_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="2 23" + {!> ../../../docs_src/additional_status_codes/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="4 25" + {!> ../../../docs_src/additional_status_codes/tutorial001.py!} + ``` + +!!! warning "Achtung" + Wenn Sie eine `Response` direkt zurückgeben, wie im obigen Beispiel, wird sie direkt zurückgegeben. + + Sie wird nicht mit einem Modell usw. serialisiert. + + Stellen Sie sicher, dass sie die gewünschten Daten enthält und dass die Werte gültiges JSON sind (wenn Sie `JSONResponse` verwenden). + +!!! note "Technische Details" + Sie können auch `from starlette.responses import JSONResponse` verwenden. + + **FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. Das Gleiche gilt für `status`. + +## OpenAPI- und API-Dokumentation + +Wenn Sie zusätzliche Statuscodes und Responses direkt zurückgeben, werden diese nicht in das OpenAPI-Schema (die API-Dokumentation) aufgenommen, da FastAPI keine Möglichkeit hat, im Voraus zu wissen, was Sie zurückgeben werden. + +Sie können das jedoch in Ihrem Code dokumentieren, indem Sie Folgendes verwenden: [Zusätzliche Responses](additional-responses.md){.internal-link target=_blank}. diff --git a/docs/de/docs/advanced/advanced-dependencies.md b/docs/de/docs/advanced/advanced-dependencies.md new file mode 100644 index 0000000000000..33b93b3325502 --- /dev/null +++ b/docs/de/docs/advanced/advanced-dependencies.md @@ -0,0 +1,138 @@ +# Fortgeschrittene Abhängigkeiten + +## Parametrisierte Abhängigkeiten + +Alle Abhängigkeiten, die wir bisher gesehen haben, waren festgelegte Funktionen oder Klassen. + +Es kann jedoch Fälle geben, in denen Sie Parameter für eine Abhängigkeit festlegen möchten, ohne viele verschiedene Funktionen oder Klassen zu deklarieren. + +Stellen wir uns vor, wir möchten eine Abhängigkeit haben, die prüft, ob ein Query-Parameter `q` einen vordefinierten Inhalt hat. + +Aber wir wollen diesen vordefinierten Inhalt per Parameter festlegen können. + +## Eine „aufrufbare“ Instanz + +In Python gibt es eine Möglichkeit, eine Instanz einer Klasse „aufrufbar“ („callable“) zu machen. + +Nicht die Klasse selbst (die bereits aufrufbar ist), sondern eine Instanz dieser Klasse. + +Dazu deklarieren wir eine Methode `__call__`: + +=== "Python 3.9+" + + ```Python hl_lines="12" + {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="11" + {!> ../../../docs_src/dependencies/tutorial011_an.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="10" + {!> ../../../docs_src/dependencies/tutorial011.py!} + ``` + +In diesem Fall ist dieses `__call__` das, was **FastAPI** verwendet, um nach zusätzlichen Parametern und Unterabhängigkeiten zu suchen, und das ist es auch, was später aufgerufen wird, um einen Wert an den Parameter in Ihrer *Pfadoperation-Funktion* zu übergeben. + +## Die Instanz parametrisieren + +Und jetzt können wir `__init__` verwenden, um die Parameter der Instanz zu deklarieren, die wir zum `Parametrisieren` der Abhängigkeit verwenden können: + +=== "Python 3.9+" + + ```Python hl_lines="9" + {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="8" + {!> ../../../docs_src/dependencies/tutorial011_an.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="7" + {!> ../../../docs_src/dependencies/tutorial011.py!} + ``` + +In diesem Fall wird **FastAPI** `__init__` nie berühren oder sich darum kümmern, wir werden es direkt in unserem Code verwenden. + +## Eine Instanz erstellen + +Wir könnten eine Instanz dieser Klasse erstellen mit: + +=== "Python 3.9+" + + ```Python hl_lines="18" + {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="17" + {!> ../../../docs_src/dependencies/tutorial011_an.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="16" + {!> ../../../docs_src/dependencies/tutorial011.py!} + ``` + +Und auf diese Weise können wir unsere Abhängigkeit „parametrisieren“, die jetzt `"bar"` enthält, als das Attribut `checker.fixed_content`. + +## Die Instanz als Abhängigkeit verwenden + +Dann könnten wir diesen `checker` in einem `Depends(checker)` anstelle von `Depends(FixedContentQueryChecker)` verwenden, da die Abhängigkeit die Instanz `checker` und nicht die Klasse selbst ist. + +Und beim Auflösen der Abhängigkeit ruft **FastAPI** diesen `checker` wie folgt auf: + +```Python +checker(q="somequery") +``` + +... und übergibt, was immer das als Wert dieser Abhängigkeit in unserer *Pfadoperation-Funktion* zurückgibt, als den Parameter `fixed_content_included`: + +=== "Python 3.9+" + + ```Python hl_lines="22" + {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="21" + {!> ../../../docs_src/dependencies/tutorial011_an.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="20" + {!> ../../../docs_src/dependencies/tutorial011.py!} + ``` + +!!! tip "Tipp" + Das alles mag gekünstelt wirken. Und es ist möglicherweise noch nicht ganz klar, welchen Nutzen das hat. + + Diese Beispiele sind bewusst einfach gehalten, zeigen aber, wie alles funktioniert. + + In den Kapiteln zum Thema Sicherheit gibt es Hilfsfunktionen, die auf die gleiche Weise implementiert werden. + + Wenn Sie das hier alles verstanden haben, wissen Sie bereits, wie diese Sicherheits-Hilfswerkzeuge unter der Haube funktionieren. diff --git a/docs/de/docs/advanced/async-tests.md b/docs/de/docs/advanced/async-tests.md new file mode 100644 index 0000000000000..2e2c222108501 --- /dev/null +++ b/docs/de/docs/advanced/async-tests.md @@ -0,0 +1,95 @@ +# Asynchrone Tests + +Sie haben bereits gesehen, wie Sie Ihre **FastAPI**-Anwendungen mit dem bereitgestellten `TestClient` testen. Bisher haben Sie nur gesehen, wie man synchrone Tests schreibt, ohne `async`hrone Funktionen zu verwenden. + +Die Möglichkeit, in Ihren Tests asynchrone Funktionen zu verwenden, könnte beispielsweise nützlich sein, wenn Sie Ihre Datenbank asynchron abfragen. Stellen Sie sich vor, Sie möchten das Senden von Requests an Ihre FastAPI-Anwendung testen und dann überprüfen, ob Ihr Backend die richtigen Daten erfolgreich in die Datenbank geschrieben hat, während Sie eine asynchrone Datenbankbibliothek verwenden. + +Schauen wir uns an, wie wir das machen können. + +## pytest.mark.anyio + +Wenn wir in unseren Tests asynchrone Funktionen aufrufen möchten, müssen unsere Testfunktionen asynchron sein. AnyIO stellt hierfür ein nettes Plugin zur Verfügung, mit dem wir festlegen können, dass einige Testfunktionen asynchron aufgerufen werden sollen. + +## HTTPX + +Auch wenn Ihre **FastAPI**-Anwendung normale `def`-Funktionen anstelle von `async def` verwendet, handelt es sich darunter immer noch um eine `async`hrone Anwendung. + +Der `TestClient` macht unter der Haube magisches, um die asynchrone FastAPI-Anwendung in Ihren normalen `def`-Testfunktionen, mithilfe von Standard-Pytest aufzurufen. Aber diese Magie funktioniert nicht mehr, wenn wir sie in asynchronen Funktionen verwenden. Durch die asynchrone Ausführung unserer Tests können wir den `TestClient` nicht mehr in unseren Testfunktionen verwenden. + +Der `TestClient` basiert auf HTTPX und glücklicherweise können wir ihn direkt verwenden, um die API zu testen. + +## Beispiel + +Betrachten wir als einfaches Beispiel eine Dateistruktur ähnlich der in [Größere Anwendungen](../tutorial/bigger-applications.md){.internal-link target=_blank} und [Testen](../tutorial/testing.md){.internal-link target=_blank}: + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +│   └── test_main.py +``` + +Die Datei `main.py` hätte als Inhalt: + +```Python +{!../../../docs_src/async_tests/main.py!} +``` + +Die Datei `test_main.py` hätte die Tests für `main.py`, das könnte jetzt so aussehen: + +```Python +{!../../../docs_src/async_tests/test_main.py!} +``` + +## Es ausführen + +Sie können Ihre Tests wie gewohnt ausführen mit: + +
+ +```console +$ pytest + +---> 100% +``` + +
+ +## Details + +Der Marker `@pytest.mark.anyio` teilt pytest mit, dass diese Testfunktion asynchron aufgerufen werden soll: + +```Python hl_lines="7" +{!../../../docs_src/async_tests/test_main.py!} +``` + +!!! tip "Tipp" + Beachten Sie, dass die Testfunktion jetzt `async def` ist und nicht nur `def` wie zuvor, wenn Sie den `TestClient` verwenden. + +Dann können wir einen `AsyncClient` mit der App erstellen und mit `await` asynchrone Requests an ihn senden. + +```Python hl_lines="9-10" +{!../../../docs_src/async_tests/test_main.py!} +``` + +Das ist das Äquivalent zu: + +```Python +response = client.get('/') +``` + +... welches wir verwendet haben, um unsere Requests mit dem `TestClient` zu machen. + +!!! tip "Tipp" + Beachten Sie, dass wir async/await mit dem neuen `AsyncClient` verwenden – der Request ist asynchron. + +!!! warning "Achtung" + Falls Ihre Anwendung auf Lifespan-Events angewiesen ist, der `AsyncClient` löst diese Events nicht aus. Um sicherzustellen, dass sie ausgelöst werden, verwenden Sie `LifespanManager` von florimondmanca/asgi-lifespan. + +## Andere asynchrone Funktionsaufrufe + +Da die Testfunktion jetzt asynchron ist, können Sie in Ihren Tests neben dem Senden von Requests an Ihre FastAPI-Anwendung jetzt auch andere `async`hrone Funktionen aufrufen (und `await`en), genau so, wie Sie diese an anderer Stelle in Ihrem Code aufrufen würden. + +!!! tip "Tipp" + Wenn Sie einen `RuntimeError: Task attached to a different loop` erhalten, wenn Sie asynchrone Funktionsaufrufe in Ihre Tests integrieren (z. B. bei Verwendung von MongoDBs MotorClient), dann denken Sie daran, Objekte zu instanziieren, die einen Event Loop nur innerhalb asynchroner Funktionen benötigen, z. B. einen `@app.on_event("startup")`-Callback. diff --git a/docs/de/docs/advanced/behind-a-proxy.md b/docs/de/docs/advanced/behind-a-proxy.md new file mode 100644 index 0000000000000..ad0a92e28c12c --- /dev/null +++ b/docs/de/docs/advanced/behind-a-proxy.md @@ -0,0 +1,350 @@ +# Hinter einem Proxy + +In manchen Situationen müssen Sie möglicherweise einen **Proxy**-Server wie Traefik oder Nginx verwenden, mit einer Konfiguration, die ein zusätzliches Pfadpräfix hinzufügt, das von Ihrer Anwendung nicht gesehen wird. + +In diesen Fällen können Sie `root_path` verwenden, um Ihre Anwendung zu konfigurieren. + +Der `root_path` („Wurzelpfad“) ist ein Mechanismus, der von der ASGI-Spezifikation bereitgestellt wird (auf der FastAPI via Starlette aufbaut). + +Der `root_path` wird verwendet, um diese speziellen Fälle zu handhaben. + +Und er wird auch intern beim Mounten von Unteranwendungen verwendet. + +## Proxy mit einem abgetrennten Pfadpräfix + +Ein Proxy mit einem abgetrennten Pfadpräfix bedeutet in diesem Fall, dass Sie einen Pfad unter `/app` in Ihrem Code deklarieren könnten, dann aber, eine Ebene darüber, den Proxy hinzufügen, der Ihre **FastAPI**-Anwendung unter einem Pfad wie `/api/v1` platziert. + +In diesem Fall würde der ursprüngliche Pfad `/app` tatsächlich unter `/api/v1/app` bereitgestellt. + +Auch wenn Ihr gesamter Code unter der Annahme geschrieben ist, dass es nur `/app` gibt. + +```Python hl_lines="6" +{!../../../docs_src/behind_a_proxy/tutorial001.py!} +``` + +Und der Proxy würde das **Pfadpräfix** on-the-fly **"entfernen**", bevor er die Anfrage an Uvicorn übermittelt, dafür sorgend, dass Ihre Anwendung davon überzeugt ist, dass sie unter `/app` bereitgestellt wird, sodass Sie nicht Ihren gesamten Code dahingehend aktualisieren müssen, das Präfix `/api/v1` zu verwenden. + +Bis hierher würde alles wie gewohnt funktionieren. + +Wenn Sie dann jedoch die Benutzeroberfläche der integrierten Dokumentation (das Frontend) öffnen, wird angenommen, dass sich das OpenAPI-Schema unter `/openapi.json` anstelle von `/api/v1/openapi.json` befindet. + +Das Frontend (das im Browser läuft) würde also versuchen, `/openapi.json` zu erreichen und wäre nicht in der Lage, das OpenAPI-Schema abzurufen. + +Da wir für unsere Anwendung einen Proxy mit dem Pfadpräfix `/api/v1` haben, muss das Frontend das OpenAPI-Schema unter `/api/v1/openapi.json` abrufen. + +```mermaid +graph LR + +browser("Browser") +proxy["Proxy auf http://0.0.0.0:9999/api/v1/app"] +server["Server auf http://127.0.0.1:8000/app"] + +browser --> proxy +proxy --> server +``` + +!!! tip "Tipp" + Die IP `0.0.0.0` wird üblicherweise verwendet, um anzudeuten, dass das Programm alle auf diesem Computer/Server verfügbaren IPs abhört. + +Die Benutzeroberfläche der Dokumentation würde benötigen, dass das OpenAPI-Schema deklariert, dass sich dieser API-`server` unter `/api/v1` (hinter dem Proxy) befindet. Zum Beispiel: + +```JSON hl_lines="4-8" +{ + "openapi": "3.1.0", + // Hier mehr Einstellungen + "servers": [ + { + "url": "/api/v1" + } + ], + "paths": { + // Hier mehr Einstellungen + } +} +``` + +In diesem Beispiel könnte der „Proxy“ etwa **Traefik** sein. Und der Server wäre so etwas wie **Uvicorn**, auf dem Ihre FastAPI-Anwendung ausgeführt wird. + +### Bereitstellung des `root_path` + +Um dies zu erreichen, können Sie die Kommandozeilenoption `--root-path` wie folgt verwenden: + +
+ +```console +$ uvicorn main:app --root-path /api/v1 + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Falls Sie Hypercorn verwenden, das hat auch die Option `--root-path`. + +!!! note "Technische Details" + Die ASGI-Spezifikation definiert einen `root_path` für diesen Anwendungsfall. + + Und die Kommandozeilenoption `--root-path` stellt diesen `root_path` bereit. + +### Überprüfen des aktuellen `root_path` + +Sie können den aktuellen `root_path` abrufen, der von Ihrer Anwendung für jede Anfrage verwendet wird. Er ist Teil des `scope`-Dictionarys (das ist Teil der ASGI-Spezifikation). + +Hier fügen wir ihn, nur zu Demonstrationszwecken, in die Nachricht ein. + +```Python hl_lines="8" +{!../../../docs_src/behind_a_proxy/tutorial001.py!} +``` + +Wenn Sie Uvicorn dann starten mit: + +
+ +```console +$ uvicorn main:app --root-path /api/v1 + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +wäre die Response etwa: + +```JSON +{ + "message": "Hello World", + "root_path": "/api/v1" +} +``` + +### Festlegen des `root_path` in der FastAPI-Anwendung + +Falls Sie keine Möglichkeit haben, eine Kommandozeilenoption wie `--root-path` oder ähnlich zu übergeben, können Sie als Alternative beim Erstellen Ihrer FastAPI-Anwendung den Parameter `root_path` setzen: + +```Python hl_lines="3" +{!../../../docs_src/behind_a_proxy/tutorial002.py!} +``` + +Die Übergabe des `root_path` an `FastAPI` wäre das Äquivalent zur Übergabe der `--root-path`-Kommandozeilenoption an Uvicorn oder Hypercorn. + +### Über `root_path` + +Beachten Sie, dass der Server (Uvicorn) diesen `root_path` für nichts anderes außer die Weitergabe an die Anwendung verwendet. + +Aber wenn Sie mit Ihrem Browser auf http://127.0.0.1:8000/app gehen, sehen Sie die normale Antwort: + +```JSON +{ + "message": "Hello World", + "root_path": "/api/v1" +} +``` + +Es wird also nicht erwartet, dass unter `http://127.0.0.1:8000/api/v1/app` darauf zugegriffen wird. + +Uvicorn erwartet, dass der Proxy unter `http://127.0.0.1:8000/app` auf Uvicorn zugreift, und dann liegt es in der Verantwortung des Proxys, das zusätzliche `/api/v1`-Präfix darüber hinzuzufügen. + +## Über Proxys mit einem abgetrennten Pfadpräfix + +Bedenken Sie, dass ein Proxy mit abgetrennten Pfadpräfix nur eine von vielen Konfigurationsmöglichkeiten ist. + +Wahrscheinlich wird in vielen Fällen die Standardeinstellung sein, dass der Proxy kein abgetrenntes Pfadpräfix hat. + +In einem solchen Fall (ohne ein abgetrenntes Pfadpräfix) würde der Proxy auf etwas wie `https://myawesomeapp.com` lauschen, und wenn der Browser dann zu `https://myawesomeapp.com/api/v1/` wechselt, und Ihr Server (z. B. Uvicorn) auf `http://127.0.0.1:8000` lauscht, würde der Proxy (ohne ein abgetrenntes Pfadpräfix) über denselben Pfad auf Uvicorn zugreifen: `http://127.0.0.1:8000/api/v1/app`. + +## Lokal testen mit Traefik + +Sie können das Experiment mit einem abgetrennten Pfadpräfix ganz einfach lokal ausführen, indem Sie Traefik verwenden. + +Laden Sie Traefik herunter, es ist eine einzelne Binärdatei, Sie können die komprimierte Datei extrahieren und sie direkt vom Terminal aus ausführen. + +Dann erstellen Sie eine Datei `traefik.toml` mit: + +```TOML hl_lines="3" +[entryPoints] + [entryPoints.http] + address = ":9999" + +[providers] + [providers.file] + filename = "routes.toml" +``` + +Dadurch wird Traefik angewiesen, Port 9999 abzuhören und eine andere Datei `routes.toml` zu verwenden. + +!!! tip "Tipp" + Wir verwenden Port 9999 anstelle des Standard-HTTP-Ports 80, damit Sie ihn nicht mit Administratorrechten (`sudo`) ausführen müssen. + +Erstellen Sie nun die andere Datei `routes.toml`: + +```TOML hl_lines="5 12 20" +[http] + [http.middlewares] + + [http.middlewares.api-stripprefix.stripPrefix] + prefixes = ["/api/v1"] + + [http.routers] + + [http.routers.app-http] + entryPoints = ["http"] + service = "app" + rule = "PathPrefix(`/api/v1`)" + middlewares = ["api-stripprefix"] + + [http.services] + + [http.services.app] + [http.services.app.loadBalancer] + [[http.services.app.loadBalancer.servers]] + url = "http://127.0.0.1:8000" +``` + +Diese Datei konfiguriert Traefik, das Pfadpräfix `/api/v1` zu verwenden. + +Und dann leitet Traefik seine Anfragen an Ihren Uvicorn weiter, der unter `http://127.0.0.1:8000` läuft. + +Starten Sie nun Traefik: + +
+ +```console +$ ./traefik --configFile=traefik.toml + +INFO[0000] Configuration loaded from file: /home/user/awesomeapi/traefik.toml +``` + +
+ +Und jetzt starten Sie Ihre Anwendung mit Uvicorn, indem Sie die Option `--root-path` verwenden: + +
+ +```console +$ uvicorn main:app --root-path /api/v1 + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +### Die Responses betrachten + +Wenn Sie nun zur URL mit dem Port für Uvicorn gehen: http://127.0.0.1:8000/app, sehen Sie die normale Response: + +```JSON +{ + "message": "Hello World", + "root_path": "/api/v1" +} +``` + +!!! tip "Tipp" + Beachten Sie, dass, obwohl Sie unter `http://127.0.0.1:8000/app` darauf zugreifen, als `root_path` angezeigt wird `/api/v1`, welches aus der Option `--root-path` stammt. + +Öffnen Sie nun die URL mit dem Port für Traefik, einschließlich des Pfadpräfixes: http://127.0.0.1:9999/api/v1/app. + +Wir bekommen die gleiche Response: + +```JSON +{ + "message": "Hello World", + "root_path": "/api/v1" +} +``` + +Diesmal jedoch unter der URL mit dem vom Proxy bereitgestellten Präfixpfad: `/api/v1`. + +Die Idee hier ist natürlich, dass jeder über den Proxy auf die Anwendung zugreifen soll, daher ist die Version mit dem Pfadpräfix `/api/v1` die „korrekte“. + +Und die von Uvicorn direkt bereitgestellte Version ohne Pfadpräfix (`http://127.0.0.1:8000/app`) wäre ausschließlich für den Zugriff durch den _Proxy_ (Traefik) bestimmt. + +Dies demonstriert, wie der Proxy (Traefik) das Pfadpräfix verwendet und wie der Server (Uvicorn) den `root_path` aus der Option `--root-path` verwendet. + +### Es in der Dokumentationsoberfläche betrachten + +Jetzt folgt der spaßige Teil. ✨ + +Der „offizielle“ Weg, auf die Anwendung zuzugreifen, wäre über den Proxy mit dem von uns definierten Pfadpräfix. Wenn Sie also die von Uvicorn direkt bereitgestellte Dokumentationsoberfläche ohne das Pfadpräfix in der URL ausprobieren, wird es erwartungsgemäß nicht funktionieren, da erwartet wird, dass der Zugriff über den Proxy erfolgt. + +Sie können das unter http://127.0.0.1:8000/docs sehen: + + + +Wenn wir jedoch unter der „offiziellen“ URL, über den Proxy mit Port `9999`, unter `/api/v1/docs`, auf die Dokumentationsoberfläche zugreifen, funktioniert es ordnungsgemäß! 🎉 + +Sie können das unter http://127.0.0.1:9999/api/v1/docs testen: + + + +Genau so, wie wir es wollten. ✔️ + +Dies liegt daran, dass FastAPI diesen `root_path` verwendet, um den Default-`server` in OpenAPI mit der von `root_path` bereitgestellten URL zu erstellen. + +## Zusätzliche Server + +!!! warning "Achtung" + Dies ist ein fortgeschrittener Anwendungsfall. Überspringen Sie das gerne. + +Standardmäßig erstellt **FastAPI** einen `server` im OpenAPI-Schema mit der URL für den `root_path`. + +Sie können aber auch andere alternative `server` bereitstellen, beispielsweise wenn Sie möchten, dass *dieselbe* Dokumentationsoberfläche mit einer Staging- und Produktionsumgebung interagiert. + +Wenn Sie eine benutzerdefinierte Liste von Servern (`servers`) übergeben und es einen `root_path` gibt (da Ihre API hinter einem Proxy läuft), fügt **FastAPI** einen „Server“ mit diesem `root_path` am Anfang der Liste ein. + +Zum Beispiel: + +```Python hl_lines="4-7" +{!../../../docs_src/behind_a_proxy/tutorial003.py!} +``` + +Erzeugt ein OpenAPI-Schema, wie: + +```JSON hl_lines="5-7" +{ + "openapi": "3.1.0", + // Hier mehr Einstellungen + "servers": [ + { + "url": "/api/v1" + }, + { + "url": "https://stag.example.com", + "description": "Staging environment" + }, + { + "url": "https://prod.example.com", + "description": "Production environment" + } + ], + "paths": { + // Hier mehr Einstellungen + } +} +``` + +!!! tip "Tipp" + Beachten Sie den automatisch generierten Server mit dem `URL`-Wert `/api/v1`, welcher vom `root_path` stammt. + +In der Dokumentationsoberfläche unter http://127.0.0.1:9999/api/v1/docs würde es so aussehen: + + + +!!! tip "Tipp" + Die Dokumentationsoberfläche interagiert mit dem von Ihnen ausgewählten Server. + +### Den automatischen Server von `root_path` deaktivieren + +Wenn Sie nicht möchten, dass **FastAPI** einen automatischen Server inkludiert, welcher `root_path` verwendet, können Sie den Parameter `root_path_in_servers=False` verwenden: + +```Python hl_lines="9" +{!../../../docs_src/behind_a_proxy/tutorial004.py!} +``` + +Dann wird er nicht in das OpenAPI-Schema aufgenommen. + +## Mounten einer Unteranwendung + +Wenn Sie gleichzeitig eine Unteranwendung mounten (wie beschrieben in [Unteranwendungen – Mounts](sub-applications.md){.internal-link target=_blank}) und einen Proxy mit `root_path` verwenden wollen, können Sie das normal tun, wie Sie es erwarten würden. + +FastAPI verwendet intern den `root_path` auf intelligente Weise, sodass es einfach funktioniert. ✨ diff --git a/docs/de/docs/advanced/custom-response.md b/docs/de/docs/advanced/custom-response.md new file mode 100644 index 0000000000000..68c037ad7baba --- /dev/null +++ b/docs/de/docs/advanced/custom-response.md @@ -0,0 +1,300 @@ +# Benutzerdefinierte Response – HTML, Stream, Datei, andere + +Standardmäßig gibt **FastAPI** die Responses mittels `JSONResponse` zurück. + +Sie können das überschreiben, indem Sie direkt eine `Response` zurückgeben, wie in [Eine Response direkt zurückgeben](response-directly.md){.internal-link target=_blank} gezeigt. + +Wenn Sie jedoch direkt eine `Response` zurückgeben, werden die Daten nicht automatisch konvertiert und die Dokumentation wird nicht automatisch generiert (zum Beispiel wird der spezifische „Medientyp“, der im HTTP-Header `Content-Type` angegeben ist, nicht Teil der generierten OpenAPI). + +Sie können aber auch die `Response`, die Sie verwenden möchten, im *Pfadoperation-Dekorator* deklarieren. + +Der Inhalt, den Sie von Ihrer *Pfadoperation-Funktion* zurückgeben, wird in diese `Response` eingefügt. + +Und wenn diese `Response` einen JSON-Medientyp (`application/json`) hat, wie es bei `JSONResponse` und `UJSONResponse` der Fall ist, werden die von Ihnen zurückgegebenen Daten automatisch mit jedem Pydantic `response_model` konvertiert (und gefiltert), das Sie im *Pfadoperation-Dekorator* deklariert haben. + +!!! note "Hinweis" + Wenn Sie eine Response-Klasse ohne Medientyp verwenden, erwartet FastAPI, dass Ihre Response keinen Inhalt hat, und dokumentiert daher das Format der Response nicht in deren generierter OpenAPI-Dokumentation. + +## `ORJSONResponse` verwenden + +Um beispielsweise noch etwas Leistung herauszuholen, können Sie `orjson` installieren und verwenden, und die Response als `ORJSONResponse` deklarieren. + +Importieren Sie die `Response`-Klasse (-Unterklasse), die Sie verwenden möchten, und deklarieren Sie sie im *Pfadoperation-Dekorator*. + +Bei umfangreichen Responses ist die direkte Rückgabe einer `Response` viel schneller als ein Dictionary zurückzugeben. + +Das liegt daran, dass FastAPI standardmäßig jedes enthaltene Element überprüft und sicherstellt, dass es als JSON serialisierbar ist, und zwar unter Verwendung desselben [JSON-kompatiblen Encoders](../tutorial/encoder.md){.internal-link target=_blank}, der im Tutorial erläutert wurde. Dadurch können Sie **beliebige Objekte** zurückgeben, zum Beispiel Datenbankmodelle. + +Wenn Sie jedoch sicher sind, dass der von Ihnen zurückgegebene Inhalt **mit JSON serialisierbar** ist, können Sie ihn direkt an die Response-Klasse übergeben und die zusätzliche Arbeit vermeiden, die FastAPI hätte, indem es Ihren zurückgegebenen Inhalt durch den `jsonable_encoder` leitet, bevor es ihn an die Response-Klasse übergibt. + +```Python hl_lines="2 7" +{!../../../docs_src/custom_response/tutorial001b.py!} +``` + +!!! info + Der Parameter `response_class` wird auch verwendet, um den „Medientyp“ der Response zu definieren. + + In diesem Fall wird der HTTP-Header `Content-Type` auf `application/json` gesetzt. + + Und er wird als solcher in OpenAPI dokumentiert. + +!!! tip "Tipp" + Die `ORJSONResponse` ist derzeit nur in FastAPI verfügbar, nicht in Starlette. + +## HTML-Response + +Um eine Response mit HTML direkt von **FastAPI** zurückzugeben, verwenden Sie `HTMLResponse`. + +* Importieren Sie `HTMLResponse`. +* Übergeben Sie `HTMLResponse` als den Parameter `response_class` Ihres *Pfadoperation-Dekorators*. + +```Python hl_lines="2 7" +{!../../../docs_src/custom_response/tutorial002.py!} +``` + +!!! info + Der Parameter `response_class` wird auch verwendet, um den „Medientyp“ der Response zu definieren. + + In diesem Fall wird der HTTP-Header `Content-Type` auf `text/html` gesetzt. + + Und er wird als solcher in OpenAPI dokumentiert. + +### Eine `Response` zurückgeben + +Wie in [Eine Response direkt zurückgeben](response-directly.md){.internal-link target=_blank} gezeigt, können Sie die Response auch direkt in Ihrer *Pfadoperation* überschreiben, indem Sie diese zurückgeben. + +Das gleiche Beispiel von oben, das eine `HTMLResponse` zurückgibt, könnte so aussehen: + +```Python hl_lines="2 7 19" +{!../../../docs_src/custom_response/tutorial003.py!} +``` + +!!! warning "Achtung" + Eine `Response`, die direkt von Ihrer *Pfadoperation-Funktion* zurückgegeben wird, wird in OpenAPI nicht dokumentiert (zum Beispiel wird der `Content-Type` nicht dokumentiert) und ist in der automatischen interaktiven Dokumentation nicht sichtbar. + +!!! info + Natürlich stammen der eigentliche `Content-Type`-Header, der Statuscode, usw., aus dem `Response`-Objekt, das Sie zurückgegeben haben. + +### In OpenAPI dokumentieren und `Response` überschreiben + +Wenn Sie die Response innerhalb der Funktion überschreiben und gleichzeitig den „Medientyp“ in OpenAPI dokumentieren möchten, können Sie den `response_class`-Parameter verwenden UND ein `Response`-Objekt zurückgeben. + +Die `response_class` wird dann nur zur Dokumentation der OpenAPI-Pfadoperation* verwendet, Ihre `Response` wird jedoch unverändert verwendet. + +#### Eine `HTMLResponse` direkt zurückgeben + +Es könnte zum Beispiel so etwas sein: + +```Python hl_lines="7 21 23" +{!../../../docs_src/custom_response/tutorial004.py!} +``` + +In diesem Beispiel generiert die Funktion `generate_html_response()` bereits eine `Response` und gibt sie zurück, anstatt das HTML in einem `str` zurückzugeben. + +Indem Sie das Ergebnis des Aufrufs von `generate_html_response()` zurückgeben, geben Sie bereits eine `Response` zurück, die das Standardverhalten von **FastAPI** überschreibt. + +Aber da Sie die `HTMLResponse` auch in der `response_class` übergeben haben, weiß **FastAPI**, dass sie in OpenAPI und der interaktiven Dokumentation als HTML mit `text/html` zu dokumentieren ist: + + + +## Verfügbare Responses + +Hier sind einige der verfügbaren Responses. + +Bedenken Sie, dass Sie `Response` verwenden können, um alles andere zurückzugeben, oder sogar eine benutzerdefinierte Unterklasse zu erstellen. + +!!! note "Technische Details" + Sie können auch `from starlette.responses import HTMLResponse` verwenden. + + **FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. + +### `Response` + +Die Hauptklasse `Response`, alle anderen Responses erben von ihr. + +Sie können sie direkt zurückgeben. + +Sie akzeptiert die folgenden Parameter: + +* `content` – Ein `str` oder `bytes`. +* `status_code` – Ein `int`-HTTP-Statuscode. +* `headers` – Ein `dict` von Strings. +* `media_type` – Ein `str`, der den Medientyp angibt. Z. B. `"text/html"`. + +FastAPI (eigentlich Starlette) fügt automatisch einen Content-Length-Header ein. Außerdem wird es einen Content-Type-Header einfügen, der auf dem media_type basiert, und für Texttypen einen Zeichensatz (charset) anfügen. + +```Python hl_lines="1 18" +{!../../../docs_src/response_directly/tutorial002.py!} +``` + +### `HTMLResponse` + +Nimmt Text oder Bytes entgegen und gibt eine HTML-Response zurück, wie Sie oben gelesen haben. + +### `PlainTextResponse` + +Nimmt Text oder Bytes entgegen und gibt eine Plain-Text-Response zurück. + +```Python hl_lines="2 7 9" +{!../../../docs_src/custom_response/tutorial005.py!} +``` + +### `JSONResponse` + +Nimmt einige Daten entgegen und gibt eine `application/json`-codierte Response zurück. + +Dies ist die Standard-Response, die in **FastAPI** verwendet wird, wie Sie oben gelesen haben. + +### `ORJSONResponse` + +Eine schnelle alternative JSON-Response mit `orjson`, wie Sie oben gelesen haben. + +### `UJSONResponse` + +Eine alternative JSON-Response mit `ujson`. + +!!! warning "Achtung" + `ujson` ist bei der Behandlung einiger Sonderfälle weniger sorgfältig als Pythons eingebaute Implementierung. + +```Python hl_lines="2 7" +{!../../../docs_src/custom_response/tutorial001.py!} +``` + +!!! tip "Tipp" + Möglicherweise ist `ORJSONResponse` eine schnellere Alternative. + +### `RedirectResponse` + +Gibt eine HTTP-Weiterleitung (HTTP-Redirect) zurück. Verwendet standardmäßig den Statuscode 307 – Temporäre Weiterleitung (Temporary Redirect). + +Sie können eine `RedirectResponse` direkt zurückgeben: + +```Python hl_lines="2 9" +{!../../../docs_src/custom_response/tutorial006.py!} +``` + +--- + +Oder Sie können sie im Parameter `response_class` verwenden: + + +```Python hl_lines="2 7 9" +{!../../../docs_src/custom_response/tutorial006b.py!} +``` + +Wenn Sie das tun, können Sie die URL direkt von Ihrer *Pfadoperation*-Funktion zurückgeben. + +In diesem Fall ist der verwendete `status_code` der Standardcode für die `RedirectResponse`, also `307`. + +--- + +Sie können den Parameter `status_code` auch in Kombination mit dem Parameter `response_class` verwenden: + +```Python hl_lines="2 7 9" +{!../../../docs_src/custom_response/tutorial006c.py!} +``` + +### `StreamingResponse` + +Nimmt einen asynchronen Generator oder einen normalen Generator/Iterator und streamt den Responsebody. + +```Python hl_lines="2 14" +{!../../../docs_src/custom_response/tutorial007.py!} +``` + +#### Verwendung von `StreamingResponse` mit dateiähnlichen Objekten + +Wenn Sie ein dateiähnliches (file-like) Objekt haben (z. B. das von `open()` zurückgegebene Objekt), können Sie eine Generatorfunktion erstellen, um über dieses dateiähnliche Objekt zu iterieren. + +Auf diese Weise müssen Sie nicht alles zuerst in den Arbeitsspeicher lesen und können diese Generatorfunktion an `StreamingResponse` übergeben und zurückgeben. + +Das umfasst viele Bibliotheken zur Interaktion mit Cloud-Speicher, Videoverarbeitung und anderen. + +```{ .python .annotate hl_lines="2 10-12 14" } +{!../../../docs_src/custom_response/tutorial008.py!} +``` + +1. Das ist die Generatorfunktion. Es handelt sich um eine „Generatorfunktion“, da sie `yield`-Anweisungen enthält. +2. Durch die Verwendung eines `with`-Blocks stellen wir sicher, dass das dateiähnliche Objekt geschlossen wird, nachdem die Generatorfunktion fertig ist. Also, nachdem sie mit dem Senden der Response fertig ist. +3. Dieses `yield from` weist die Funktion an, über das Ding namens `file_like` zu iterieren. Und dann für jeden iterierten Teil, diesen Teil so zurückzugeben, als wenn er aus dieser Generatorfunktion (`iterfile`) stammen würde. + + Es handelt sich also hier um eine Generatorfunktion, die die „generierende“ Arbeit intern auf etwas anderes überträgt. + + Auf diese Weise können wir das Ganze in einen `with`-Block einfügen und so sicherstellen, dass das dateiartige Objekt nach Abschluss geschlossen wird. + +!!! tip "Tipp" + Beachten Sie, dass wir, da wir Standard-`open()` verwenden, welches `async` und `await` nicht unterstützt, hier die Pfadoperation mit normalen `def` deklarieren. + +### `FileResponse` + +Streamt eine Datei asynchron als Response. + +Nimmt zur Instanziierung einen anderen Satz von Argumenten entgegen als die anderen Response-Typen: + +* `path` – Der Dateipfad zur Datei, die gestreamt werden soll. +* `headers` – Alle benutzerdefinierten Header, die inkludiert werden sollen, als Dictionary. +* `media_type` – Ein String, der den Medientyp angibt. Wenn nicht gesetzt, wird der Dateiname oder Pfad verwendet, um auf einen Medientyp zu schließen. +* `filename` – Wenn gesetzt, wird das in der `Content-Disposition` der Response eingefügt. + +Datei-Responses enthalten die entsprechenden `Content-Length`-, `Last-Modified`- und `ETag`-Header. + +```Python hl_lines="2 10" +{!../../../docs_src/custom_response/tutorial009.py!} +``` + +Sie können auch den Parameter `response_class` verwenden: + +```Python hl_lines="2 8 10" +{!../../../docs_src/custom_response/tutorial009b.py!} +``` + +In diesem Fall können Sie den Dateipfad direkt von Ihrer *Pfadoperation*-Funktion zurückgeben. + +## Benutzerdefinierte Response-Klasse + +Sie können Ihre eigene benutzerdefinierte Response-Klasse erstellen, die von `Response` erbt und diese verwendet. + +Nehmen wir zum Beispiel an, dass Sie `orjson` verwenden möchten, aber mit einigen benutzerdefinierten Einstellungen, die in der enthaltenen `ORJSONResponse`-Klasse nicht verwendet werden. + +Sie möchten etwa, dass Ihre Response eingerücktes und formatiertes JSON zurückgibt. Dafür möchten Sie die orjson-Option `orjson.OPT_INDENT_2` verwenden. + +Sie könnten eine `CustomORJSONResponse` erstellen. Das Wichtigste, was Sie tun müssen, ist, eine `Response.render(content)`-Methode zu erstellen, die den Inhalt als `bytes` zurückgibt: + +```Python hl_lines="9-14 17" +{!../../../docs_src/custom_response/tutorial009c.py!} +``` + +Statt: + +```json +{"message": "Hello World"} +``` + +... wird die Response jetzt Folgendes zurückgeben: + +```json +{ + "message": "Hello World" +} +``` + +Natürlich werden Sie wahrscheinlich viel bessere Möglichkeiten finden, Vorteil daraus zu ziehen, als JSON zu formatieren. 😉 + +## Standard-Response-Klasse + +Beim Erstellen einer **FastAPI**-Klasseninstanz oder eines `APIRouter`s können Sie angeben, welche Response-Klasse standardmäßig verwendet werden soll. + +Der Parameter, der das definiert, ist `default_response_class`. + +Im folgenden Beispiel verwendet **FastAPI** standardmäßig `ORJSONResponse` in allen *Pfadoperationen*, anstelle von `JSONResponse`. + +```Python hl_lines="2 4" +{!../../../docs_src/custom_response/tutorial010.py!} +``` + +!!! tip "Tipp" + Sie können dennoch weiterhin `response_class` in *Pfadoperationen* überschreiben, wie bisher. + +## Zusätzliche Dokumentation + +Sie können auch den Medientyp und viele andere Details in OpenAPI mit `responses` deklarieren: [Zusätzliche Responses in OpenAPI](additional-responses.md){.internal-link target=_blank}. diff --git a/docs/de/docs/advanced/dataclasses.md b/docs/de/docs/advanced/dataclasses.md new file mode 100644 index 0000000000000..c78a6d3dddd05 --- /dev/null +++ b/docs/de/docs/advanced/dataclasses.md @@ -0,0 +1,98 @@ +# Verwendung von Datenklassen + +FastAPI basiert auf **Pydantic** und ich habe Ihnen gezeigt, wie Sie Pydantic-Modelle verwenden können, um Requests und Responses zu deklarieren. + +Aber FastAPI unterstützt auf die gleiche Weise auch die Verwendung von `dataclasses`: + +```Python hl_lines="1 7-12 19-20" +{!../../../docs_src/dataclasses/tutorial001.py!} +``` + +Das ist dank **Pydantic** ebenfalls möglich, da es `dataclasses` intern unterstützt. + +Auch wenn im obige Code Pydantic nicht explizit vorkommt, verwendet FastAPI Pydantic, um diese Standard-Datenklassen in Pydantics eigene Variante von Datenklassen zu konvertieren. + +Und natürlich wird das gleiche unterstützt: + +* Validierung der Daten +* Serialisierung der Daten +* Dokumentation der Daten, usw. + +Das funktioniert genauso wie mit Pydantic-Modellen. Und tatsächlich wird es unter der Haube mittels Pydantic auf die gleiche Weise bewerkstelligt. + +!!! info + Bedenken Sie, dass Datenklassen nicht alles können, was Pydantic-Modelle können. + + Daher müssen Sie möglicherweise weiterhin Pydantic-Modelle verwenden. + + Wenn Sie jedoch eine Menge Datenklassen herumliegen haben, ist dies ein guter Trick, um sie für eine Web-API mithilfe von FastAPI zu verwenden. 🤓 + +## Datenklassen als `response_model` + +Sie können `dataclasses` auch im Parameter `response_model` verwenden: + +```Python hl_lines="1 7-13 19" +{!../../../docs_src/dataclasses/tutorial002.py!} +``` + +Die Datenklasse wird automatisch in eine Pydantic-Datenklasse konvertiert. + +Auf diese Weise wird deren Schema in der Benutzeroberfläche der API-Dokumentation angezeigt: + + + +## Datenklassen in verschachtelten Datenstrukturen + +Sie können `dataclasses` auch mit anderen Typannotationen kombinieren, um verschachtelte Datenstrukturen zu erstellen. + +In einigen Fällen müssen Sie möglicherweise immer noch Pydantics Version von `dataclasses` verwenden. Zum Beispiel, wenn Sie Fehler in der automatisch generierten API-Dokumentation haben. + +In diesem Fall können Sie einfach die Standard-`dataclasses` durch `pydantic.dataclasses` ersetzen, was einen direkten Ersatz darstellt: + +```{ .python .annotate hl_lines="1 5 8-11 14-17 23-25 28" } +{!../../../docs_src/dataclasses/tutorial003.py!} +``` + +1. Wir importieren `field` weiterhin von Standard-`dataclasses`. + +2. `pydantic.dataclasses` ist ein direkter Ersatz für `dataclasses`. + +3. Die Datenklasse `Author` enthält eine Liste von `Item`-Datenklassen. + +4. Die Datenklasse `Author` wird im `response_model`-Parameter verwendet. + +5. Sie können andere Standard-Typannotationen mit Datenklassen als Requestbody verwenden. + + In diesem Fall handelt es sich um eine Liste von `Item`-Datenklassen. + +6. Hier geben wir ein Dictionary zurück, das `items` enthält, welches eine Liste von Datenklassen ist. + + FastAPI ist weiterhin in der Lage, die Daten nach JSON zu serialisieren. + +7. Hier verwendet das `response_model` als Typannotation eine Liste von `Author`-Datenklassen. + + Auch hier können Sie `dataclasses` mit Standard-Typannotationen kombinieren. + +8. Beachten Sie, dass diese *Pfadoperation-Funktion* reguläres `def` anstelle von `async def` verwendet. + + Wie immer können Sie in FastAPI `def` und `async def` beliebig kombinieren. + + Wenn Sie eine Auffrischung darüber benötigen, wann welche Anwendung sinnvoll ist, lesen Sie den Abschnitt „In Eile?“ in der Dokumentation zu [`async` und `await`](../async.md#in-eile){.internal-link target=_blank}. + +9. Diese *Pfadoperation-Funktion* gibt keine Datenklassen zurück (obwohl dies möglich wäre), sondern eine Liste von Dictionarys mit internen Daten. + + FastAPI verwendet den Parameter `response_model` (der Datenklassen enthält), um die Response zu konvertieren. + +Sie können `dataclasses` mit anderen Typannotationen auf vielfältige Weise kombinieren, um komplexe Datenstrukturen zu bilden. + +Weitere Einzelheiten finden Sie in den Bemerkungen im Quellcode oben. + +## Mehr erfahren + +Sie können `dataclasses` auch mit anderen Pydantic-Modellen kombinieren, von ihnen erben, sie in Ihre eigenen Modelle einbinden, usw. + +Weitere Informationen finden Sie in der Pydantic-Dokumentation zu Datenklassen. + +## Version + +Dies ist verfügbar seit FastAPI-Version `0.67.0`. 🔖 diff --git a/docs/de/docs/advanced/events.md b/docs/de/docs/advanced/events.md new file mode 100644 index 0000000000000..e29f61ab9284f --- /dev/null +++ b/docs/de/docs/advanced/events.md @@ -0,0 +1,162 @@ +# Lifespan-Events + +Sie können Logik (Code) definieren, die ausgeführt werden soll, bevor die Anwendung **hochfährt**. Dies bedeutet, dass dieser Code **einmal** ausgeführt wird, **bevor** die Anwendung **beginnt, Requests entgegenzunehmen**. + +Auf die gleiche Weise können Sie Logik (Code) definieren, die ausgeführt werden soll, wenn die Anwendung **heruntergefahren** wird. In diesem Fall wird dieser Code **einmal** ausgeführt, **nachdem** möglicherweise **viele Requests** bearbeitet wurden. + +Da dieser Code ausgeführt wird, bevor die Anwendung **beginnt**, Requests entgegenzunehmen, und unmittelbar, nachdem sie die Bearbeitung von Requests **abgeschlossen hat**, deckt er die gesamte **Lebensdauer – „Lifespan“** – der Anwendung ab (das Wort „Lifespan“ wird gleich wichtig sein 😉). + +Dies kann sehr nützlich sein, um **Ressourcen** einzurichten, die Sie in der gesamten Anwendung verwenden wollen und die von Requests **gemeinsam genutzt** werden und/oder die Sie anschließend **aufräumen** müssen. Zum Beispiel ein Pool von Datenbankverbindungen oder das Laden eines gemeinsam genutzten Modells für maschinelles Lernen. + +## Anwendungsfall + +Beginnen wir mit einem Beispiel-**Anwendungsfall** und schauen uns dann an, wie wir ihn mit dieser Methode implementieren können. + +Stellen wir uns vor, Sie verfügen über einige **Modelle für maschinelles Lernen**, die Sie zur Bearbeitung von Requests verwenden möchten. 🤖 + +Die gleichen Modelle werden von den Requests gemeinsam genutzt, es handelt sich also nicht um ein Modell pro Request, pro Benutzer, oder ähnliches. + +Stellen wir uns vor, dass das Laden des Modells **eine ganze Weile dauern** kann, da viele **Daten von der Festplatte** gelesen werden müssen. Sie möchten das also nicht für jeden Request tun. + +Sie könnten das auf der obersten Ebene des Moduls/der Datei machen, aber das würde auch bedeuten, dass **das Modell geladen wird**, selbst wenn Sie nur einen einfachen automatisierten Test ausführen, dann wäre dieser Test **langsam**, weil er warten müsste, bis das Modell geladen ist, bevor er einen davon unabhängigen Teil des Codes ausführen könnte. + +Das wollen wir besser machen: Laden wir das Modell, bevor die Requests bearbeitet werden, aber unmittelbar bevor die Anwendung beginnt, Requests zu empfangen, und nicht, während der Code geladen wird. + +## Lifespan + +Sie können diese Logik beim *Hochfahren* und *Herunterfahren* mithilfe des `lifespan`-Parameters der `FastAPI`-App und eines „Kontextmanagers“ definieren (ich zeige Ihnen gleich, was das ist). + +Beginnen wir mit einem Beispiel und sehen es uns dann im Detail an. + +Wir erstellen eine asynchrone Funktion `lifespan()` mit `yield` wie folgt: + +```Python hl_lines="16 19" +{!../../../docs_src/events/tutorial003.py!} +``` + +Hier simulieren wir das langsame *Hochfahren*, das Laden des Modells, indem wir die (Fake-)Modellfunktion vor dem `yield` in das Dictionary mit Modellen für maschinelles Lernen einfügen. Dieser Code wird ausgeführt, **bevor** die Anwendung **beginnt, Requests entgegenzunehmen**, während des *Hochfahrens*. + +Und dann, direkt nach dem `yield`, entladen wir das Modell. Dieser Code wird unmittelbar vor dem *Herunterfahren* ausgeführt, **nachdem** die Anwendung **die Bearbeitung von Requests abgeschlossen hat**. Dadurch könnten beispielsweise Ressourcen wie Arbeitsspeicher oder eine GPU freigegeben werden. + +!!! tip "Tipp" + Das *Herunterfahren* würde erfolgen, wenn Sie die Anwendung **stoppen**. + + Möglicherweise müssen Sie eine neue Version starten, oder Sie haben es einfach satt, sie auszuführen. 🤷 + +### Lifespan-Funktion + +Das Erste, was auffällt, ist, dass wir eine asynchrone Funktion mit `yield` definieren. Das ist sehr ähnlich zu Abhängigkeiten mit `yield`. + +```Python hl_lines="14-19" +{!../../../docs_src/events/tutorial003.py!} +``` + +Der erste Teil der Funktion, vor dem `yield`, wird ausgeführt **bevor** die Anwendung startet. + +Und der Teil nach `yield` wird ausgeführt, **nachdem** die Anwendung beendet ist. + +### Asynchroner Kontextmanager + +Wie Sie sehen, ist die Funktion mit einem `@asynccontextmanager` versehen. + +Dadurch wird die Funktion in einen sogenannten „**asynchronen Kontextmanager**“ umgewandelt. + +```Python hl_lines="1 13" +{!../../../docs_src/events/tutorial003.py!} +``` + +Ein **Kontextmanager** in Python ist etwas, das Sie in einer `with`-Anweisung verwenden können, zum Beispiel kann `open()` als Kontextmanager verwendet werden: + +```Python +with open("file.txt") as file: + file.read() +``` + +In neueren Versionen von Python gibt es auch einen **asynchronen Kontextmanager**. Sie würden ihn mit `async with` verwenden: + +```Python +async with lifespan(app): + await do_stuff() +``` + +Wenn Sie wie oben einen Kontextmanager oder einen asynchronen Kontextmanager erstellen, führt dieser vor dem Betreten des `with`-Blocks den Code vor dem `yield` aus, und nach dem Verlassen des `with`-Blocks wird er den Code nach dem `yield` ausführen. + +In unserem obigen Codebeispiel verwenden wir ihn nicht direkt, sondern übergeben ihn an FastAPI, damit es ihn verwenden kann. + +Der Parameter `lifespan` der `FastAPI`-App benötigt einen **asynchronen Kontextmanager**, wir können ihm also unseren neuen asynchronen Kontextmanager `lifespan` übergeben. + +```Python hl_lines="22" +{!../../../docs_src/events/tutorial003.py!} +``` + +## Alternative Events (deprecated) + +!!! warning "Achtung" + Der empfohlene Weg, das *Hochfahren* und *Herunterfahren* zu handhaben, ist die Verwendung des `lifespan`-Parameters der `FastAPI`-App, wie oben beschrieben. Wenn Sie einen `lifespan`-Parameter übergeben, werden die `startup`- und `shutdown`-Eventhandler nicht mehr aufgerufen. Es ist entweder alles `lifespan` oder alles Events, nicht beides. + + Sie können diesen Teil wahrscheinlich überspringen. + +Es gibt eine alternative Möglichkeit, diese Logik zu definieren, sodass sie beim *Hochfahren* und beim *Herunterfahren* ausgeführt wird. + +Sie können Eventhandler (Funktionen) definieren, die ausgeführt werden sollen, bevor die Anwendung hochgefahren wird oder wenn die Anwendung heruntergefahren wird. + +Diese Funktionen können mit `async def` oder normalem `def` deklariert werden. + +### `startup`-Event + +Um eine Funktion hinzuzufügen, die vor dem Start der Anwendung ausgeführt werden soll, deklarieren Sie diese mit dem Event `startup`: + +```Python hl_lines="8" +{!../../../docs_src/events/tutorial001.py!} +``` + +In diesem Fall initialisiert die Eventhandler-Funktion `startup` die „Datenbank“ der Items (nur ein `dict`) mit einigen Werten. + +Sie können mehr als eine Eventhandler-Funktion hinzufügen. + +Und Ihre Anwendung empfängt erst dann Anfragen, wenn alle `startup`-Eventhandler abgeschlossen sind. + +### `shutdown`-Event + +Um eine Funktion hinzuzufügen, die beim Herunterfahren der Anwendung ausgeführt werden soll, deklarieren Sie sie mit dem Event `shutdown`: + +```Python hl_lines="6" +{!../../../docs_src/events/tutorial002.py!} +``` + +Hier schreibt die `shutdown`-Eventhandler-Funktion eine Textzeile `"Application shutdown"` in eine Datei `log.txt`. + +!!! info + In der Funktion `open()` bedeutet `mode="a"` „append“ („anhängen“), sodass die Zeile nach dem, was sich in dieser Datei befindet, hinzugefügt wird, ohne den vorherigen Inhalt zu überschreiben. + +!!! tip "Tipp" + Beachten Sie, dass wir in diesem Fall eine Standard-Python-Funktion `open()` verwenden, die mit einer Datei interagiert. + + Es handelt sich also um I/O (Input/Output), welches „Warten“ erfordert, bis Dinge auf die Festplatte geschrieben werden. + + Aber `open()` verwendet nicht `async` und `await`. + + Daher deklarieren wir die Eventhandler-Funktion mit Standard-`def` statt mit `async def`. + +### `startup` und `shutdown` zusammen + +Es besteht eine hohe Wahrscheinlichkeit, dass die Logik für Ihr *Hochfahren* und *Herunterfahren* miteinander verknüpft ist. Vielleicht möchten Sie etwas beginnen und es dann beenden, eine Ressource laden und sie dann freigeben usw. + +Bei getrennten Funktionen, die keine gemeinsame Logik oder Variablen haben, ist dies schwieriger, da Sie Werte in globalen Variablen speichern oder ähnliche Tricks verwenden müssen. + +Aus diesem Grund wird jetzt empfohlen, stattdessen `lifespan` wie oben erläutert zu verwenden. + +## Technische Details + +Nur ein technisches Detail für die neugierigen Nerds. 🤓 + +In der technischen ASGI-Spezifikation ist dies Teil des Lifespan Protokolls und definiert Events namens `startup` und `shutdown`. + +!!! info + Weitere Informationen zu Starlettes `lifespan`-Handlern finden Sie in Starlettes Lifespan-Dokumentation. + + Einschließlich, wie man Lifespan-Zustand handhabt, der in anderen Bereichen Ihres Codes verwendet werden kann. + +## Unteranwendungen + +🚨 Beachten Sie, dass diese Lifespan-Events (Hochfahren und Herunterfahren) nur für die Hauptanwendung ausgeführt werden, nicht für [Unteranwendungen – Mounts](sub-applications.md){.internal-link target=_blank}. diff --git a/docs/de/docs/advanced/generate-clients.md b/docs/de/docs/advanced/generate-clients.md new file mode 100644 index 0000000000000..2fcba59569337 --- /dev/null +++ b/docs/de/docs/advanced/generate-clients.md @@ -0,0 +1,286 @@ +# Clients generieren + +Da **FastAPI** auf der OpenAPI-Spezifikation basiert, erhalten Sie automatische Kompatibilität mit vielen Tools, einschließlich der automatischen API-Dokumentation (bereitgestellt von Swagger UI). + +Ein besonderer Vorteil, der nicht unbedingt offensichtlich ist, besteht darin, dass Sie für Ihre API **Clients generieren** können (manchmal auch **SDKs** genannt), für viele verschiedene **Programmiersprachen**. + +## OpenAPI-Client-Generatoren + +Es gibt viele Tools zum Generieren von Clients aus **OpenAPI**. + +Ein gängiges Tool ist OpenAPI Generator. + +Wenn Sie ein **Frontend** erstellen, ist openapi-typescript-codegen eine sehr interessante Alternative. + +## Client- und SDK-Generatoren – Sponsor + +Es gibt auch einige **vom Unternehmen entwickelte** Client- und SDK-Generatoren, die auf OpenAPI (FastAPI) basieren. In einigen Fällen können diese Ihnen **weitere Funktionalität** zusätzlich zu qualitativ hochwertigen generierten SDKs/Clients bieten. + +Einige von diesen ✨ [**sponsern FastAPI**](../help-fastapi.md#den-autor-sponsern){.internal-link target=_blank} ✨, das gewährleistet die kontinuierliche und gesunde **Entwicklung** von FastAPI und seinem **Ökosystem**. + +Und es zeigt deren wahres Engagement für FastAPI und seine **Community** (Sie), da diese Ihnen nicht nur einen **guten Service** bieten möchten, sondern auch sicherstellen möchten, dass Sie über ein **gutes und gesundes Framework** verfügen, FastAPI. 🙇 + +Beispielsweise könnten Sie Speakeasy ausprobieren. + +Es gibt auch mehrere andere Unternehmen, welche ähnliche Dienste anbieten und die Sie online suchen und finden können. 🤓 + +## Einen TypeScript-Frontend-Client generieren + +Beginnen wir mit einer einfachen FastAPI-Anwendung: + +=== "Python 3.9+" + + ```Python hl_lines="7-9 12-13 16-17 21" + {!> ../../../docs_src/generate_clients/tutorial001_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9-11 14-15 18 19 23" + {!> ../../../docs_src/generate_clients/tutorial001.py!} + ``` + +Beachten Sie, dass die *Pfadoperationen* die Modelle definieren, welche diese für die Request- und Response-Payload verwenden, indem sie die Modelle `Item` und `ResponseMessage` verwenden. + +### API-Dokumentation + +Wenn Sie zur API-Dokumentation gehen, werden Sie sehen, dass diese die **Schemas** für die Daten enthält, welche in Requests gesendet und in Responses empfangen werden: + + + +Sie können diese Schemas sehen, da sie mit den Modellen in der Anwendung deklariert wurden. + +Diese Informationen sind im **OpenAPI-Schema** der Anwendung verfügbar und werden dann in der API-Dokumentation angezeigt (von Swagger UI). + +Und dieselben Informationen aus den Modellen, die in OpenAPI enthalten sind, können zum **Generieren des Client-Codes** verwendet werden. + +### Einen TypeScript-Client generieren + +Nachdem wir nun die Anwendung mit den Modellen haben, können wir den Client-Code für das Frontend generieren. + +#### `openapi-typescript-codegen` installieren + +Sie können `openapi-typescript-codegen` in Ihrem Frontend-Code installieren mit: + +
+ +```console +$ npm install openapi-typescript-codegen --save-dev + +---> 100% +``` + +
+ +#### Client-Code generieren + +Um den Client-Code zu generieren, können Sie das Kommandozeilentool `openapi` verwenden, das soeben installiert wurde. + +Da es im lokalen Projekt installiert ist, könnten Sie diesen Befehl wahrscheinlich nicht direkt aufrufen, sondern würden ihn in Ihre Datei `package.json` einfügen. + +Diese könnte so aussehen: + +```JSON hl_lines="7" +{ + "name": "frontend-app", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "generate-client": "openapi --input http://localhost:8000/openapi.json --output ./src/client --client axios --useOptions --useUnionTypes" + }, + "author": "", + "license": "", + "devDependencies": { + "openapi-typescript-codegen": "^0.20.1", + "typescript": "^4.6.2" + } +} +``` + +Nachdem Sie das NPM-Skript `generate-client` dort stehen haben, können Sie es ausführen mit: + +
+ +```console +$ npm run generate-client + +frontend-app@1.0.0 generate-client /home/user/code/frontend-app +> openapi --input http://localhost:8000/openapi.json --output ./src/client --client axios --useOptions --useUnionTypes +``` + +
+ +Dieser Befehl generiert Code in `./src/client` und verwendet intern `axios` (die Frontend-HTTP-Bibliothek). + +### Den Client-Code ausprobieren + +Jetzt können Sie den Client-Code importieren und verwenden. Er könnte wie folgt aussehen, beachten Sie, dass Sie automatische Codevervollständigung für die Methoden erhalten: + + + +Sie erhalten außerdem automatische Vervollständigung für die zu sendende Payload: + + + +!!! tip "Tipp" + Beachten Sie die automatische Vervollständigung für `name` und `price`, welche in der FastAPI-Anwendung im `Item`-Modell definiert wurden. + +Sie erhalten Inline-Fehlerberichte für die von Ihnen gesendeten Daten: + + + +Das Response-Objekt hat auch automatische Vervollständigung: + + + +## FastAPI-Anwendung mit Tags + +In vielen Fällen wird Ihre FastAPI-Anwendung größer sein und Sie werden wahrscheinlich Tags verwenden, um verschiedene Gruppen von *Pfadoperationen* zu separieren. + +Beispielsweise könnten Sie einen Abschnitt für **Items (Artikel)** und einen weiteren Abschnitt für **Users (Benutzer)** haben, und diese könnten durch Tags getrennt sein: + +=== "Python 3.9+" + + ```Python hl_lines="21 26 34" + {!> ../../../docs_src/generate_clients/tutorial002_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="23 28 36" + {!> ../../../docs_src/generate_clients/tutorial002.py!} + ``` + +### Einen TypeScript-Client mit Tags generieren + +Wenn Sie unter Verwendung von Tags einen Client für eine FastAPI-Anwendung generieren, wird normalerweise auch der Client-Code anhand der Tags getrennt. + +Auf diese Weise können Sie die Dinge für den Client-Code richtig ordnen und gruppieren: + + + +In diesem Fall haben Sie: + +* `ItemsService` +* `UsersService` + +### Client-Methodennamen + +Im Moment sehen die generierten Methodennamen wie `createItemItemsPost` nicht sehr sauber aus: + +```TypeScript +ItemsService.createItemItemsPost({name: "Plumbus", price: 5}) +``` + +... das liegt daran, dass der Client-Generator für jede *Pfadoperation* die OpenAPI-interne **Operation-ID** verwendet. + +OpenAPI erfordert, dass jede Operation-ID innerhalb aller *Pfadoperationen* eindeutig ist. Daher verwendet FastAPI den **Funktionsnamen**, den **Pfad** und die **HTTP-Methode/-Operation**, um diese Operation-ID zu generieren. Denn so kann sichergestellt werden, dass die Operation-IDs eindeutig sind. + +Aber ich zeige Ihnen als nächstes, wie Sie das verbessern können. 🤓 + +## Benutzerdefinierte Operation-IDs und bessere Methodennamen + +Sie können die Art und Weise, wie diese Operation-IDs **generiert** werden, **ändern**, um sie einfacher zu machen und **einfachere Methodennamen** in den Clients zu haben. + +In diesem Fall müssen Sie auf andere Weise sicherstellen, dass jede Operation-ID **eindeutig** ist. + +Sie könnten beispielsweise sicherstellen, dass jede *Pfadoperation* einen Tag hat, und dann die Operation-ID basierend auf dem **Tag** und dem **Namen** der *Pfadoperation* (dem Funktionsnamen) generieren. + +### Funktion zum Generieren einer eindeutigen ID erstellen + +FastAPI verwendet eine **eindeutige ID** für jede *Pfadoperation*, diese wird für die **Operation-ID** und auch für die Namen aller benötigten benutzerdefinierten Modelle für Requests oder Responses verwendet. + +Sie können diese Funktion anpassen. Sie nimmt eine `APIRoute` und gibt einen String zurück. + +Hier verwendet sie beispielsweise den ersten Tag (Sie werden wahrscheinlich nur einen Tag haben) und den Namen der *Pfadoperation* (den Funktionsnamen). + +Anschließend können Sie diese benutzerdefinierte Funktion als Parameter `generate_unique_id_function` an **FastAPI** übergeben: + +=== "Python 3.9+" + + ```Python hl_lines="6-7 10" + {!> ../../../docs_src/generate_clients/tutorial003_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="8-9 12" + {!> ../../../docs_src/generate_clients/tutorial003.py!} + ``` + +### Einen TypeScript-Client mit benutzerdefinierten Operation-IDs generieren + +Wenn Sie nun den Client erneut generieren, werden Sie feststellen, dass er über die verbesserten Methodennamen verfügt: + + + +Wie Sie sehen, haben die Methodennamen jetzt den Tag und dann den Funktionsnamen, aber keine Informationen aus dem URL-Pfad und der HTTP-Operation. + +### Vorab-Modifikation der OpenAPI-Spezifikation für den Client-Generator + +Der generierte Code enthält immer noch etwas **verdoppelte Information**. + +Wir wissen bereits, dass diese Methode mit den **Items** zusammenhängt, da sich dieses Wort in `ItemsService` befindet (vom Tag übernommen), aber wir haben auch immer noch den Tagnamen im Methodennamen vorangestellt. 😕 + +Wir werden das wahrscheinlich weiterhin für OpenAPI im Allgemeinen beibehalten wollen, da dadurch sichergestellt wird, dass die Operation-IDs **eindeutig** sind. + +Aber für den generierten Client könnten wir die OpenAPI-Operation-IDs direkt vor der Generierung der Clients **modifizieren**, um diese Methodennamen schöner und **sauberer** zu machen. + +Wir könnten das OpenAPI-JSON in eine Datei `openapi.json` herunterladen und dann mit einem Skript wie dem folgenden **den vorangestellten Tag entfernen**: + +=== "Python" + + ```Python + {!> ../../../docs_src/generate_clients/tutorial004.py!} + ``` + +=== "Node.js" + + ```Javascript + {!> ../../../docs_src/generate_clients/tutorial004.js!} + ``` + +Damit würden die Operation-IDs von Dingen wie `items-get_items` in `get_items` umbenannt, sodass der Client-Generator einfachere Methodennamen generieren kann. + +### Einen TypeScript-Client mit der modifizierten OpenAPI generieren + +Da das Endergebnis nun in einer Datei `openapi.json` vorliegt, würden Sie die `package.json` ändern, um diese lokale Datei zu verwenden, zum Beispiel: + +```JSON hl_lines="7" +{ + "name": "frontend-app", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "generate-client": "openapi --input ./openapi.json --output ./src/client --client axios --useOptions --useUnionTypes" + }, + "author": "", + "license": "", + "devDependencies": { + "openapi-typescript-codegen": "^0.20.1", + "typescript": "^4.6.2" + } +} +``` + +Nach der Generierung des neuen Clients hätten Sie nun **saubere Methodennamen** mit allen **Autovervollständigungen**, **Inline-Fehlerberichten**, usw.: + + + +## Vorteile + +Wenn Sie die automatisch generierten Clients verwenden, erhalten Sie **automatische Codevervollständigung** für: + +* Methoden. +* Request-Payloads im Body, Query-Parameter, usw. +* Response-Payloads. + +Außerdem erhalten Sie für alles **Inline-Fehlerberichte**. + +Und wann immer Sie den Backend-Code aktualisieren und das Frontend **neu generieren**, stehen alle neuen *Pfadoperationen* als Methoden zur Verfügung, die alten werden entfernt und alle anderen Änderungen werden im generierten Code reflektiert. 🤓 + +Das bedeutet auch, dass, wenn sich etwas ändert, dies automatisch im Client-Code **reflektiert** wird. Und wenn Sie den Client **erstellen**, kommt es zu einer Fehlermeldung, wenn die verwendeten Daten **nicht übereinstimmen**. + +Sie würden also sehr früh im Entwicklungszyklus **viele Fehler erkennen**, anstatt darauf warten zu müssen, dass die Fehler Ihren Endbenutzern in der Produktion angezeigt werden, und dann zu versuchen, zu debuggen, wo das Problem liegt. ✨ diff --git a/docs/de/docs/advanced/index.md b/docs/de/docs/advanced/index.md new file mode 100644 index 0000000000000..048e31e061a11 --- /dev/null +++ b/docs/de/docs/advanced/index.md @@ -0,0 +1,33 @@ +# Handbuch für fortgeschrittene Benutzer + +## Zusatzfunktionen + +Das Haupt-[Tutorial – Benutzerhandbuch](../tutorial/index.md){.internal-link target=_blank} sollte ausreichen, um Ihnen einen Überblick über alle Hauptfunktionen von **FastAPI** zu geben. + +In den nächsten Abschnitten sehen Sie weitere Optionen, Konfigurationen und zusätzliche Funktionen. + +!!! tip "Tipp" + Die nächsten Abschnitte sind **nicht unbedingt „fortgeschritten“**. + + Und es ist möglich, dass für Ihren Anwendungsfall die Lösung in einem davon liegt. + +## Lesen Sie zuerst das Tutorial + +Sie können immer noch die meisten Funktionen in **FastAPI** mit den Kenntnissen aus dem Haupt-[Tutorial – Benutzerhandbuch](../tutorial/index.md){.internal-link target=_blank} nutzen. + +Und in den nächsten Abschnitten wird davon ausgegangen, dass Sie es bereits gelesen haben und dass Sie diese Haupt-Ideen kennen. + +## Externe Kurse + +Obwohl das [Tutorial – Benutzerhandbuch](../tutorial/index.md){.internal-link target=_blank} und dieses **Handbuch für fortgeschrittene Benutzer** als geführtes Tutorial (wie ein Buch) geschrieben sind und für Sie ausreichen sollten, um **FastAPI zu lernen**, möchten Sie sie vielleicht durch zusätzliche Kurse ergänzen. + +Oder Sie belegen einfach lieber andere Kurse, weil diese besser zu Ihrem Lernstil passen. + +Einige Kursanbieter ✨ [**sponsern FastAPI**](../help-fastapi.md#den-autor-sponsern){.internal-link target=_blank} ✨, dies gewährleistet die kontinuierliche und gesunde **Entwicklung** von FastAPI und seinem **Ökosystem**. + +Und es zeigt deren wahres Engagement für FastAPI und seine **Gemeinschaft** (Sie), da diese Ihnen nicht nur eine **gute Lernerfahrung** bieten möchten, sondern auch sicherstellen möchten, dass Sie über ein **gutes und gesundes Framework verfügen **, FastAPI. 🙇 + +Vielleicht möchten Sie ihre Kurse ausprobieren: + +* Talk Python Training +* Test-Driven Development diff --git a/docs/de/docs/advanced/middleware.md b/docs/de/docs/advanced/middleware.md new file mode 100644 index 0000000000000..2c4e8542aeebb --- /dev/null +++ b/docs/de/docs/advanced/middleware.md @@ -0,0 +1,99 @@ +# Fortgeschrittene Middleware + +Im Haupttutorial haben Sie gelesen, wie Sie Ihrer Anwendung [benutzerdefinierte Middleware](../tutorial/middleware.md){.internal-link target=_blank} hinzufügen können. + +Und dann auch, wie man [CORS mittels der `CORSMiddleware`](../tutorial/cors.md){.internal-link target=_blank} handhabt. + +In diesem Abschnitt werden wir sehen, wie man andere Middlewares verwendet. + +## ASGI-Middleware hinzufügen + +Da **FastAPI** auf Starlette basiert und die ASGI-Spezifikation implementiert, können Sie jede ASGI-Middleware verwenden. + +Eine Middleware muss nicht speziell für FastAPI oder Starlette gemacht sein, um zu funktionieren, solange sie der ASGI-Spezifikation genügt. + +Im Allgemeinen handelt es sich bei ASGI-Middleware um Klassen, die als erstes Argument eine ASGI-Anwendung erwarten. + +In der Dokumentation für ASGI-Middlewares von Drittanbietern wird Ihnen wahrscheinlich gesagt, etwa Folgendes zu tun: + +```Python +from unicorn import UnicornMiddleware + +app = SomeASGIApp() + +new_app = UnicornMiddleware(app, some_config="rainbow") +``` + +Aber FastAPI (eigentlich Starlette) bietet eine einfachere Möglichkeit, welche sicherstellt, dass die internen Middlewares zur Behandlung von Serverfehlern und benutzerdefinierten Exceptionhandlern ordnungsgemäß funktionieren. + +Dazu verwenden Sie `app.add_middleware()` (wie schon im Beispiel für CORS gesehen). + +```Python +from fastapi import FastAPI +from unicorn import UnicornMiddleware + +app = FastAPI() + +app.add_middleware(UnicornMiddleware, some_config="rainbow") +``` + +`app.add_middleware()` empfängt eine Middleware-Klasse als erstes Argument und dann alle weiteren Argumente, die an die Middleware übergeben werden sollen. + +## Integrierte Middleware + +**FastAPI** enthält mehrere Middlewares für gängige Anwendungsfälle. Wir werden als Nächstes sehen, wie man sie verwendet. + +!!! note "Technische Details" + Für die nächsten Beispiele könnten Sie auch `from starlette.middleware.something import SomethingMiddleware` verwenden. + + **FastAPI** bietet mehrere Middlewares via `fastapi.middleware` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Middlewares kommen aber direkt von Starlette. + +## `HTTPSRedirectMiddleware` + +Erzwingt, dass alle eingehenden Requests entweder `https` oder `wss` sein müssen. + +Alle eingehenden Requests an `http` oder `ws` werden stattdessen an das sichere Schema umgeleitet. + +```Python hl_lines="2 6" +{!../../../docs_src/advanced_middleware/tutorial001.py!} +``` + +## `TrustedHostMiddleware` + +Erzwingt, dass alle eingehenden Requests einen korrekt gesetzten `Host`-Header haben, um sich vor HTTP-Host-Header-Angriffen zu schützen. + +```Python hl_lines="2 6-8" +{!../../../docs_src/advanced_middleware/tutorial002.py!} +``` + +Die folgenden Argumente werden unterstützt: + +* `allowed_hosts` – Eine Liste von Domain-Namen, die als Hostnamen zulässig sein sollten. Wildcard-Domains wie `*.example.com` werden unterstützt, um Subdomains zu matchen. Um jeden Hostnamen zu erlauben, verwenden Sie entweder `allowed_hosts=["*"]` oder lassen Sie diese Middleware weg. + +Wenn ein eingehender Request nicht korrekt validiert wird, wird eine „400“-Response gesendet. + +## `GZipMiddleware` + +Verarbeitet GZip-Responses für alle Requests, die `"gzip"` im `Accept-Encoding`-Header enthalten. + +Diese Middleware verarbeitet sowohl Standard- als auch Streaming-Responses. + +```Python hl_lines="2 6" +{!../../../docs_src/advanced_middleware/tutorial003.py!} +``` + +Die folgenden Argumente werden unterstützt: + +* `minimum_size` – Antworten, die kleiner als diese Mindestgröße in Bytes sind, nicht per GZip komprimieren. Der Defaultwert ist `500`. + +## Andere Middlewares + +Es gibt viele andere ASGI-Middlewares. + +Zum Beispiel: + +* Sentry +* Uvicorns `ProxyHeadersMiddleware` +* MessagePack + +Um mehr über weitere verfügbare Middlewares herauszufinden, besuchen Sie Starlettes Middleware-Dokumentation und die ASGI Awesome List. diff --git a/docs/de/docs/advanced/openapi-callbacks.md b/docs/de/docs/advanced/openapi-callbacks.md new file mode 100644 index 0000000000000..026fdb4fe3df6 --- /dev/null +++ b/docs/de/docs/advanced/openapi-callbacks.md @@ -0,0 +1,179 @@ +# OpenAPI-Callbacks + +Sie könnten eine API mit einer *Pfadoperation* erstellen, die einen Request an eine *externe API* auslösen könnte, welche von jemand anderem erstellt wurde (wahrscheinlich derselbe Entwickler, der Ihre API *verwenden* würde). + +Der Vorgang, der stattfindet, wenn Ihre API-Anwendung die *externe API* aufruft, wird als „Callback“ („Rückruf“) bezeichnet. Denn die Software, die der externe Entwickler geschrieben hat, sendet einen Request an Ihre API und dann *ruft Ihre API zurück* (*calls back*) und sendet einen Request an eine *externe API* (die wahrscheinlich vom selben Entwickler erstellt wurde). + +In diesem Fall möchten Sie möglicherweise dokumentieren, wie diese externe API aussehen *sollte*. Welche *Pfadoperation* sie haben sollte, welchen Body sie erwarten sollte, welche Response sie zurückgeben sollte, usw. + +## Eine Anwendung mit Callbacks + +Sehen wir uns das alles anhand eines Beispiels an. + +Stellen Sie sich vor, Sie entwickeln eine Anwendung, mit der Sie Rechnungen erstellen können. + +Diese Rechnungen haben eine `id`, einen optionalen `title`, einen `customer` (Kunde) und ein `total` (Gesamtsumme). + +Der Benutzer Ihrer API (ein externer Entwickler) erstellt mit einem POST-Request eine Rechnung in Ihrer API. + +Dann wird Ihre API (beispielsweise): + +* die Rechnung an einen Kunden des externen Entwicklers senden. +* das Geld einsammeln. +* eine Benachrichtigung an den API-Benutzer (den externen Entwickler) zurücksenden. + * Dies erfolgt durch Senden eines POST-Requests (von *Ihrer API*) an eine *externe API*, die von diesem externen Entwickler bereitgestellt wird (das ist der „Callback“). + +## Die normale **FastAPI**-Anwendung + +Sehen wir uns zunächst an, wie die normale API-Anwendung aussehen würde, bevor wir den Callback hinzufügen. + +Sie verfügt über eine *Pfadoperation*, die einen `Invoice`-Body empfängt, und einen Query-Parameter `callback_url`, der die URL für den Callback enthält. + +Dieser Teil ist ziemlich normal, der größte Teil des Codes ist Ihnen wahrscheinlich bereits bekannt: + +```Python hl_lines="9-13 36-53" +{!../../../docs_src/openapi_callbacks/tutorial001.py!} +``` + +!!! tip "Tipp" + Der Query-Parameter `callback_url` verwendet einen Pydantic-Url-Typ. + +Das einzig Neue ist `callbacks=invoices_callback_router.routes` als Argument für den *Pfadoperation-Dekorator*. Wir werden als Nächstes sehen, was das ist. + +## Dokumentation des Callbacks + +Der tatsächliche Callback-Code hängt stark von Ihrer eigenen API-Anwendung ab. + +Und er wird wahrscheinlich von Anwendung zu Anwendung sehr unterschiedlich sein. + +Es könnten nur eine oder zwei Codezeilen sein, wie zum Beispiel: + +```Python +callback_url = "https://example.com/api/v1/invoices/events/" +httpx.post(callback_url, json={"description": "Invoice paid", "paid": True}) +``` + +Der möglicherweise wichtigste Teil des Callbacks besteht jedoch darin, sicherzustellen, dass Ihr API-Benutzer (der externe Entwickler) die *externe API* gemäß den Daten, die *Ihre API* im Requestbody des Callbacks senden wird, korrekt implementiert, usw. + +Als Nächstes fügen wir den Code hinzu, um zu dokumentieren, wie diese *externe API* aussehen sollte, um den Callback von *Ihrer API* zu empfangen. + +Diese Dokumentation wird in der Swagger-Oberfläche unter `/docs` in Ihrer API angezeigt und zeigt externen Entwicklern, wie diese die *externe API* erstellen sollten. + +In diesem Beispiel wird nicht der Callback selbst implementiert (das könnte nur eine Codezeile sein), sondern nur der Dokumentationsteil. + +!!! tip "Tipp" + Der eigentliche Callback ist nur ein HTTP-Request. + + Wenn Sie den Callback selbst implementieren, können Sie beispielsweise HTTPX oder Requests verwenden. + +## Schreiben des Codes, der den Callback dokumentiert + +Dieser Code wird nicht in Ihrer Anwendung ausgeführt, wir benötigen ihn nur, um zu *dokumentieren*, wie diese *externe API* aussehen soll. + +Sie wissen jedoch bereits, wie Sie mit **FastAPI** ganz einfach eine automatische Dokumentation für eine API erstellen. + +Daher werden wir dasselbe Wissen nutzen, um zu dokumentieren, wie die *externe API* aussehen sollte ... indem wir die *Pfadoperation(en)* erstellen, welche die externe API implementieren soll (die, welche Ihre API aufruft). + +!!! tip "Tipp" + Wenn Sie den Code zum Dokumentieren eines Callbacks schreiben, kann es hilfreich sein, sich vorzustellen, dass Sie dieser *externe Entwickler* sind. Und dass Sie derzeit die *externe API* implementieren, nicht *Ihre API*. + + Wenn Sie diese Sichtweise (des *externen Entwicklers*) vorübergehend übernehmen, wird es offensichtlicher, wo die Parameter, das Pydantic-Modell für den Body, die Response, usw. für diese *externe API* hingehören. + +### Einen Callback-`APIRouter` erstellen + +Erstellen Sie zunächst einen neuen `APIRouter`, der einen oder mehrere Callbacks enthält. + +```Python hl_lines="3 25" +{!../../../docs_src/openapi_callbacks/tutorial001.py!} +``` + +### Die Callback-*Pfadoperation* erstellen + +Um die Callback-*Pfadoperation* zu erstellen, verwenden Sie denselben `APIRouter`, den Sie oben erstellt haben. + +Sie sollte wie eine normale FastAPI-*Pfadoperation* aussehen: + +* Sie sollte wahrscheinlich eine Deklaration des Bodys enthalten, die sie erhalten soll, z. B. `body: InvoiceEvent`. +* Und sie könnte auch eine Deklaration der Response enthalten, die zurückgegeben werden soll, z. B. `response_model=InvoiceEventReceived`. + +```Python hl_lines="16-18 21-22 28-32" +{!../../../docs_src/openapi_callbacks/tutorial001.py!} +``` + +Es gibt zwei Hauptunterschiede zu einer normalen *Pfadoperation*: + +* Es muss kein tatsächlicher Code vorhanden sein, da Ihre Anwendung diesen Code niemals aufruft. Sie wird nur zur Dokumentation der *externen API* verwendet. Die Funktion könnte also einfach `pass` enthalten. +* Der *Pfad* kann einen OpenAPI-3-Ausdruck enthalten (mehr dazu weiter unten), wo er Variablen mit Parametern und Teilen des ursprünglichen Requests verwenden kann, der an *Ihre API* gesendet wurde. + +### Der Callback-Pfadausdruck + +Der Callback-*Pfad* kann einen OpenAPI-3-Ausdruck enthalten, welcher Teile des ursprünglichen Requests enthalten kann, der an *Ihre API* gesendet wurde. + +In diesem Fall ist es der `str`: + +```Python +"{$callback_url}/invoices/{$request.body.id}" +``` + +Wenn Ihr API-Benutzer (der externe Entwickler) also einen Request an *Ihre API* sendet, via: + +``` +https://yourapi.com/invoices/?callback_url=https://www.external.org/events +``` + +mit einem JSON-Körper: + +```JSON +{ + "id": "2expen51ve", + "customer": "Mr. Richie Rich", + "total": "9999" +} +``` + +dann verarbeitet *Ihre API* die Rechnung und sendet irgendwann später einen Callback-Request an die `callback_url` (die *externe API*): + +``` +https://www.external.org/events/invoices/2expen51ve +``` + +mit einem JSON-Body, der etwa Folgendes enthält: + +```JSON +{ + "description": "Payment celebration", + "paid": true +} +``` + +und sie würde eine Response von dieser *externen API* mit einem JSON-Body wie dem folgenden erwarten: + +```JSON +{ + "ok": true +} +``` + +!!! tip "Tipp" + Beachten Sie, dass die verwendete Callback-URL die URL enthält, die als Query-Parameter in `callback_url` (`https://www.external.org/events`) empfangen wurde, und auch die Rechnungs-`id` aus dem JSON-Body (`2expen51ve`). + +### Den Callback-Router hinzufügen + +An diesem Punkt haben Sie die benötigte(n) *Callback-Pfadoperation(en)* (diejenige(n), die der *externe Entwickler* in der *externen API* implementieren sollte) im Callback-Router, den Sie oben erstellt haben. + +Verwenden Sie nun den Parameter `callbacks` im *Pfadoperation-Dekorator Ihrer API*, um das Attribut `.routes` (das ist eigentlich nur eine `list`e von Routen/*Pfadoperationen*) dieses Callback-Routers zu übergeben: + +```Python hl_lines="35" +{!../../../docs_src/openapi_callbacks/tutorial001.py!} +``` + +!!! tip "Tipp" + Beachten Sie, dass Sie nicht den Router selbst (`invoices_callback_router`) an `callback=` übergeben, sondern das Attribut `.routes`, wie in `invoices_callback_router.routes`. + +### Es in der Dokumentation ansehen + +Jetzt können Sie Ihre Anwendung mit Uvicorn starten und auf http://127.0.0.1:8000/docs gehen. + +Sie sehen Ihre Dokumentation, einschließlich eines Abschnitts „Callbacks“ für Ihre *Pfadoperation*, der zeigt, wie die *externe API* aussehen sollte: + + diff --git a/docs/de/docs/advanced/openapi-webhooks.md b/docs/de/docs/advanced/openapi-webhooks.md new file mode 100644 index 0000000000000..339218080d9fb --- /dev/null +++ b/docs/de/docs/advanced/openapi-webhooks.md @@ -0,0 +1,51 @@ +# OpenAPI-Webhooks + +Es gibt Fälle, in denen Sie Ihren API-Benutzern mitteilen möchten, dass Ihre Anwendung mit einigen Daten *deren* Anwendung aufrufen (ein Request senden) könnte, normalerweise um über ein bestimmtes **Event** zu **benachrichtigen**. + +Das bedeutet, dass anstelle des normalen Prozesses, bei dem Benutzer Requests an Ihre API senden, **Ihre API** (oder Ihre Anwendung) **Requests an deren System** (an deren API, deren Anwendung) senden könnte. + +Das wird normalerweise als **Webhook** bezeichnet. + +## Webhooks-Schritte + +Der Prozess besteht normalerweise darin, dass **Sie in Ihrem Code definieren**, welche Nachricht Sie senden möchten, den **Body des Requests**. + +Sie definieren auch auf irgendeine Weise, zu welchen **Momenten** Ihre Anwendung diese Requests oder Events sendet. + +Und **Ihre Benutzer** definieren auf irgendeine Weise (zum Beispiel irgendwo in einem Web-Dashboard) die **URL**, an die Ihre Anwendung diese Requests senden soll. + +Die gesamte **Logik** zur Registrierung der URLs für Webhooks und der Code zum tatsächlichen Senden dieser Requests liegt bei Ihnen. Sie schreiben es so, wie Sie möchten, in **Ihrem eigenen Code**. + +## Webhooks mit **FastAPI** und OpenAPI dokumentieren + +Mit **FastAPI** können Sie mithilfe von OpenAPI die Namen dieser Webhooks, die Arten von HTTP-Operationen, die Ihre Anwendung senden kann (z. B. `POST`, `PUT`, usw.) und die Request**bodys** definieren, die Ihre Anwendung senden würde. + +Dies kann es Ihren Benutzern viel einfacher machen, **deren APIs zu implementieren**, um Ihre **Webhook**-Requests zu empfangen. Möglicherweise können diese sogar einen Teil des eigenem API-Codes automatisch generieren. + +!!! info + Webhooks sind in OpenAPI 3.1.0 und höher verfügbar und werden von FastAPI `0.99.0` und höher unterstützt. + +## Eine Anwendung mit Webhooks + +Wenn Sie eine **FastAPI**-Anwendung erstellen, gibt es ein `webhooks`-Attribut, mit dem Sie *Webhooks* definieren können, genauso wie Sie *Pfadoperationen* definieren würden, zum Beispiel mit `@app.webhooks.post()`. + +```Python hl_lines="9-13 36-53" +{!../../../docs_src/openapi_webhooks/tutorial001.py!} +``` + +Die von Ihnen definierten Webhooks landen im **OpenAPI**-Schema und der automatischen **Dokumentations-Oberfläche**. + +!!! info + Das `app.webhooks`-Objekt ist eigentlich nur ein `APIRouter`, derselbe Typ, den Sie verwenden würden, wenn Sie Ihre Anwendung mit mehreren Dateien strukturieren. + +Beachten Sie, dass Sie bei Webhooks tatsächlich keinen *Pfad* (wie `/items/`) deklarieren, sondern dass der Text, den Sie dort übergeben, lediglich eine **Kennzeichnung** des Webhooks (der Name des Events) ist. Zum Beispiel ist in `@app.webhooks.post("new-subscription")` der Webhook-Name `new-subscription`. + +Das liegt daran, dass erwartet wird, dass **Ihre Benutzer** den tatsächlichen **URL-Pfad**, an dem diese den Webhook-Request empfangen möchten, auf andere Weise definieren (z. B. über ein Web-Dashboard). + +### Es in der Dokumentation ansehen + +Jetzt können Sie Ihre Anwendung mit Uvicorn starten und auf http://127.0.0.1:8000/docs gehen. + +Sie werden sehen, dass Ihre Dokumentation die normalen *Pfadoperationen* und jetzt auch einige **Webhooks** enthält: + + diff --git a/docs/de/docs/advanced/path-operation-advanced-configuration.md b/docs/de/docs/advanced/path-operation-advanced-configuration.md new file mode 100644 index 0000000000000..406a08e9eadb0 --- /dev/null +++ b/docs/de/docs/advanced/path-operation-advanced-configuration.md @@ -0,0 +1,192 @@ +# Fortgeschrittene Konfiguration der Pfadoperation + +## OpenAPI operationId + +!!! warning "Achtung" + Wenn Sie kein „Experte“ für OpenAPI sind, brauchen Sie dies wahrscheinlich nicht. + +Mit dem Parameter `operation_id` können Sie die OpenAPI `operationId` festlegen, die in Ihrer *Pfadoperation* verwendet werden soll. + +Sie müssten sicherstellen, dass sie für jede Operation eindeutig ist. + +```Python hl_lines="6" +{!../../../docs_src/path_operation_advanced_configuration/tutorial001.py!} +``` + +### Verwendung des Namens der *Pfadoperation-Funktion* als operationId + +Wenn Sie die Funktionsnamen Ihrer API als `operationId`s verwenden möchten, können Sie über alle iterieren und die `operation_id` jeder *Pfadoperation* mit deren `APIRoute.name` überschreiben. + +Sie sollten dies tun, nachdem Sie alle Ihre *Pfadoperationen* hinzugefügt haben. + +```Python hl_lines="2 12-21 24" +{!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!} +``` + +!!! tip "Tipp" + Wenn Sie `app.openapi()` manuell aufrufen, sollten Sie vorher die `operationId`s aktualisiert haben. + +!!! warning "Achtung" + Wenn Sie dies tun, müssen Sie sicherstellen, dass jede Ihrer *Pfadoperation-Funktionen* einen eindeutigen Namen hat. + + Auch wenn diese sich in unterschiedlichen Modulen (Python-Dateien) befinden. + +## Von OpenAPI ausschließen + +Um eine *Pfadoperation* aus dem generierten OpenAPI-Schema (und damit aus den automatischen Dokumentationssystemen) auszuschließen, verwenden Sie den Parameter `include_in_schema` und setzen Sie ihn auf `False`: + +```Python hl_lines="6" +{!../../../docs_src/path_operation_advanced_configuration/tutorial003.py!} +``` + +## Fortgeschrittene Beschreibung mittels Docstring + +Sie können die verwendeten Zeilen aus dem Docstring einer *Pfadoperation-Funktion* einschränken, die für OpenAPI verwendet werden. + +Das Hinzufügen eines `\f` (ein maskiertes „Form Feed“-Zeichen) führt dazu, dass **FastAPI** die für OpenAPI verwendete Ausgabe an dieser Stelle abschneidet. + +Sie wird nicht in der Dokumentation angezeigt, aber andere Tools (z. B. Sphinx) können den Rest verwenden. + +```Python hl_lines="19-29" +{!../../../docs_src/path_operation_advanced_configuration/tutorial004.py!} +``` + +## Zusätzliche Responses + +Sie haben wahrscheinlich gesehen, wie man das `response_model` und den `status_code` für eine *Pfadoperation* deklariert. + +Das definiert die Metadaten der Haupt-Response einer *Pfadoperation*. + +Sie können auch zusätzliche Responses mit deren Modellen, Statuscodes usw. deklarieren. + +Es gibt hier in der Dokumentation ein ganzes Kapitel darüber, Sie können es unter [Zusätzliche Responses in OpenAPI](additional-responses.md){.internal-link target=_blank} lesen. + +## OpenAPI-Extra + +Wenn Sie in Ihrer Anwendung eine *Pfadoperation* deklarieren, generiert **FastAPI** automatisch die relevanten Metadaten dieser *Pfadoperation*, die in das OpenAPI-Schema aufgenommen werden sollen. + +!!! note "Technische Details" + In der OpenAPI-Spezifikation wird das Operationsobjekt genannt. + +Es hat alle Informationen zur *Pfadoperation* und wird zur Erstellung der automatischen Dokumentation verwendet. + +Es enthält `tags`, `parameters`, `requestBody`, `responses`, usw. + +Dieses *Pfadoperation*-spezifische OpenAPI-Schema wird normalerweise automatisch von **FastAPI** generiert, Sie können es aber auch erweitern. + +!!! tip "Tipp" + Dies ist ein Low-Level Erweiterungspunkt. + + Wenn Sie nur zusätzliche Responses deklarieren müssen, können Sie dies bequemer mit [Zusätzliche Responses in OpenAPI](additional-responses.md){.internal-link target=_blank} tun. + +Sie können das OpenAPI-Schema für eine *Pfadoperation* erweitern, indem Sie den Parameter `openapi_extra` verwenden. + +### OpenAPI-Erweiterungen + +Dieses `openapi_extra` kann beispielsweise hilfreich sein, um OpenAPI-Erweiterungen zu deklarieren: + +```Python hl_lines="6" +{!../../../docs_src/path_operation_advanced_configuration/tutorial005.py!} +``` + +Wenn Sie die automatische API-Dokumentation öffnen, wird Ihre Erweiterung am Ende der spezifischen *Pfadoperation* angezeigt. + + + +Und wenn Sie die resultierende OpenAPI sehen (unter `/openapi.json` in Ihrer API), sehen Sie Ihre Erweiterung auch als Teil der spezifischen *Pfadoperation*: + +```JSON hl_lines="22" +{ + "openapi": "3.1.0", + "info": { + "title": "FastAPI", + "version": "0.1.0" + }, + "paths": { + "/items/": { + "get": { + "summary": "Read Items", + "operationId": "read_items_items__get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + } + }, + "x-aperture-labs-portal": "blue" + } + } + } +} +``` + +### Benutzerdefiniertes OpenAPI-*Pfadoperation*-Schema + +Das Dictionary in `openapi_extra` wird mit dem automatisch generierten OpenAPI-Schema für die *Pfadoperation* zusammengeführt (mittels Deep Merge). + +Sie können dem automatisch generierten Schema also zusätzliche Daten hinzufügen. + +Sie könnten sich beispielsweise dafür entscheiden, den Request mit Ihrem eigenen Code zu lesen und zu validieren, ohne die automatischen Funktionen von FastAPI mit Pydantic zu verwenden, aber Sie könnten den Request trotzdem im OpenAPI-Schema definieren wollen. + +Das könnte man mit `openapi_extra` machen: + +```Python hl_lines="20-37 39-40" +{!../../../docs_src/path_operation_advanced_configuration/tutorial006.py!} +``` + +In diesem Beispiel haben wir kein Pydantic-Modell deklariert. Tatsächlich wird der Requestbody nicht einmal als JSON geparst, sondern direkt als `bytes` gelesen und die Funktion `magic_data_reader ()` wäre dafür verantwortlich, ihn in irgendeiner Weise zu parsen. + +Dennoch können wir das zu erwartende Schema für den Requestbody deklarieren. + +### Benutzerdefinierter OpenAPI-Content-Type + +Mit demselben Trick könnten Sie ein Pydantic-Modell verwenden, um das JSON-Schema zu definieren, das dann im benutzerdefinierten Abschnitt des OpenAPI-Schemas für die *Pfadoperation* enthalten ist. + +Und Sie könnten dies auch tun, wenn der Datentyp in der Anfrage nicht JSON ist. + +In der folgenden Anwendung verwenden wir beispielsweise weder die integrierte Funktionalität von FastAPI zum Extrahieren des JSON-Schemas aus Pydantic-Modellen noch die automatische Validierung für JSON. Tatsächlich deklarieren wir den Request-Content-Type als YAML und nicht als JSON: + +=== "Pydantic v2" + + ```Python hl_lines="17-22 24" + {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} + ``` + +=== "Pydantic v1" + + ```Python hl_lines="17-22 24" + {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} + ``` + +!!! info + In Pydantic Version 1 hieß die Methode zum Abrufen des JSON-Schemas für ein Modell `Item.schema()`, in Pydantic Version 2 heißt die Methode `Item.model_json_schema()`. + +Obwohl wir nicht die standardmäßig integrierte Funktionalität verwenden, verwenden wir dennoch ein Pydantic-Modell, um das JSON-Schema für die Daten, die wir in YAML empfangen möchten, manuell zu generieren. + +Dann verwenden wir den Request direkt und extrahieren den Body als `bytes`. Das bedeutet, dass FastAPI nicht einmal versucht, den Request-Payload als JSON zu parsen. + +Und dann parsen wir in unserem Code diesen YAML-Inhalt direkt und verwenden dann wieder dasselbe Pydantic-Modell, um den YAML-Inhalt zu validieren: + +=== "Pydantic v2" + + ```Python hl_lines="26-33" + {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} + ``` + +=== "Pydantic v1" + + ```Python hl_lines="26-33" + {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} + ``` + +!!! info + In Pydantic Version 1 war die Methode zum Parsen und Validieren eines Objekts `Item.parse_obj()`, in Pydantic Version 2 heißt die Methode `Item.model_validate()`. + +!!! tip "Tipp" + Hier verwenden wir dasselbe Pydantic-Modell wieder. + + Aber genauso hätten wir es auch auf andere Weise validieren können. diff --git a/docs/de/docs/advanced/response-change-status-code.md b/docs/de/docs/advanced/response-change-status-code.md new file mode 100644 index 0000000000000..bba908a3eef6e --- /dev/null +++ b/docs/de/docs/advanced/response-change-status-code.md @@ -0,0 +1,33 @@ +# Response – Statuscode ändern + +Sie haben wahrscheinlich schon vorher gelesen, dass Sie einen Standard-[Response-Statuscode](../tutorial/response-status-code.md){.internal-link target=_blank} festlegen können. + +In manchen Fällen müssen Sie jedoch einen anderen als den Standard-Statuscode zurückgeben. + +## Anwendungsfall + +Stellen Sie sich zum Beispiel vor, Sie möchten standardmäßig den HTTP-Statuscode „OK“ `200` zurückgeben. + +Wenn die Daten jedoch nicht vorhanden waren, möchten Sie diese erstellen und den HTTP-Statuscode „CREATED“ `201` zurückgeben. + +Sie möchten aber dennoch in der Lage sein, die von Ihnen zurückgegebenen Daten mit einem `response_model` zu filtern und zu konvertieren. + +In diesen Fällen können Sie einen `Response`-Parameter verwenden. + +## Einen `Response`-Parameter verwenden + +Sie können einen Parameter vom Typ `Response` in Ihrer *Pfadoperation-Funktion* deklarieren (wie Sie es auch für Cookies und Header tun können). + +Anschließend können Sie den `status_code` in diesem *vorübergehenden* Response-Objekt festlegen. + +```Python hl_lines="1 9 12" +{!../../../docs_src/response_change_status_code/tutorial001.py!} +``` + +Und dann können Sie wie gewohnt jedes benötigte Objekt zurückgeben (ein `dict`, ein Datenbankmodell usw.). + +Und wenn Sie ein `response_model` deklariert haben, wird es weiterhin zum Filtern und Konvertieren des von Ihnen zurückgegebenen Objekts verwendet. + +**FastAPI** verwendet diese *vorübergehende* Response, um den Statuscode (auch Cookies und Header) zu extrahieren und fügt diese in die endgültige Response ein, die den von Ihnen zurückgegebenen Wert enthält, gefiltert nach einem beliebigen `response_model`. + +Sie können den Parameter `Response` auch in Abhängigkeiten deklarieren und den Statuscode darin festlegen. Bedenken Sie jedoch, dass der gewinnt, welcher zuletzt gesetzt wird. diff --git a/docs/de/docs/advanced/response-cookies.md b/docs/de/docs/advanced/response-cookies.md new file mode 100644 index 0000000000000..0f09bd4441197 --- /dev/null +++ b/docs/de/docs/advanced/response-cookies.md @@ -0,0 +1,49 @@ +# Response-Cookies + +## Einen `Response`-Parameter verwenden + +Sie können einen Parameter vom Typ `Response` in Ihrer *Pfadoperation-Funktion* deklarieren. + +Und dann können Sie Cookies in diesem *vorübergehenden* Response-Objekt setzen. + +```Python hl_lines="1 8-9" +{!../../../docs_src/response_cookies/tutorial002.py!} +``` + +Anschließend können Sie wie gewohnt jedes gewünschte Objekt zurückgeben (ein `dict`, ein Datenbankmodell, usw.). + +Und wenn Sie ein `response_model` deklariert haben, wird es weiterhin zum Filtern und Konvertieren des von Ihnen zurückgegebenen Objekts verwendet. + +**FastAPI** verwendet diese *vorübergehende* Response, um die Cookies (auch Header und Statuscode) zu extrahieren und fügt diese in die endgültige Response ein, die den von Ihnen zurückgegebenen Wert enthält, gefiltert nach einem beliebigen `response_model`. + +Sie können den `Response`-Parameter auch in Abhängigkeiten deklarieren und darin Cookies (und Header) setzen. + +## Eine `Response` direkt zurückgeben + +Sie können Cookies auch erstellen, wenn Sie eine `Response` direkt in Ihrem Code zurückgeben. + +Dazu können Sie eine Response erstellen, wie unter [Eine Response direkt zurückgeben](response-directly.md){.internal-link target=_blank} beschrieben. + +Setzen Sie dann Cookies darin und geben Sie sie dann zurück: + +```Python hl_lines="10-12" +{!../../../docs_src/response_cookies/tutorial001.py!} +``` + +!!! tip "Tipp" + Beachten Sie, dass, wenn Sie eine Response direkt zurückgeben, anstatt den `Response`-Parameter zu verwenden, FastAPI diese direkt zurückgibt. + + Sie müssen also sicherstellen, dass Ihre Daten vom richtigen Typ sind. Z. B. sollten diese mit JSON kompatibel sein, wenn Sie eine `JSONResponse` zurückgeben. + + Und auch, dass Sie keine Daten senden, die durch ein `response_model` hätten gefiltert werden sollen. + +### Mehr Informationen + +!!! note "Technische Details" + Sie können auch `from starlette.responses import Response` oder `from starlette.responses import JSONResponse` verwenden. + + **FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. + + Und da die `Response` häufig zum Setzen von Headern und Cookies verwendet wird, stellt **FastAPI** diese auch unter `fastapi.Response` bereit. + +Um alle verfügbaren Parameter und Optionen anzuzeigen, sehen Sie sich deren Dokumentation in Starlette an. diff --git a/docs/de/docs/advanced/response-directly.md b/docs/de/docs/advanced/response-directly.md new file mode 100644 index 0000000000000..13bca7825c815 --- /dev/null +++ b/docs/de/docs/advanced/response-directly.md @@ -0,0 +1,63 @@ +# Eine Response direkt zurückgeben + +Wenn Sie eine **FastAPI** *Pfadoperation* erstellen, können Sie normalerweise beliebige Daten davon zurückgeben: ein `dict`, eine `list`e, ein Pydantic-Modell, ein Datenbankmodell, usw. + +Standardmäßig konvertiert **FastAPI** diesen Rückgabewert automatisch nach JSON, mithilfe des `jsonable_encoder`, der in [JSON-kompatibler Encoder](../tutorial/encoder.md){.internal-link target=_blank} erläutert wird. + +Dann würde es hinter den Kulissen diese JSON-kompatiblen Daten (z. B. ein `dict`) in eine `JSONResponse` einfügen, die zum Senden der Response an den Client verwendet würde. + +Sie können jedoch direkt eine `JSONResponse` von Ihren *Pfadoperationen* zurückgeben. + +Das kann beispielsweise nützlich sein, um benutzerdefinierte Header oder Cookies zurückzugeben. + +## Eine `Response` zurückgeben + +Tatsächlich können Sie jede `Response` oder jede Unterklasse davon zurückgeben. + +!!! tip "Tipp" + `JSONResponse` selbst ist eine Unterklasse von `Response`. + +Und wenn Sie eine `Response` zurückgeben, wird **FastAPI** diese direkt weiterleiten. + +Es wird keine Datenkonvertierung mit Pydantic-Modellen durchführen, es wird den Inhalt nicht in irgendeinen Typ konvertieren, usw. + +Dadurch haben Sie viel Flexibilität. Sie können jeden Datentyp zurückgeben, jede Datendeklaration oder -validierung überschreiben, usw. + +## Verwendung des `jsonable_encoder` in einer `Response` + +Da **FastAPI** keine Änderungen an einer von Ihnen zurückgegebenen `Response` vornimmt, müssen Sie sicherstellen, dass deren Inhalt dafür bereit ist. + +Sie können beispielsweise kein Pydantic-Modell in eine `JSONResponse` einfügen, ohne es zuvor in ein `dict` zu konvertieren, bei dem alle Datentypen (wie `datetime`, `UUID`, usw.) in JSON-kompatible Typen konvertiert wurden. + +In diesen Fällen können Sie den `jsonable_encoder` verwenden, um Ihre Daten zu konvertieren, bevor Sie sie an eine Response übergeben: + +```Python hl_lines="6-7 21-22" +{!../../../docs_src/response_directly/tutorial001.py!} +``` + +!!! note "Technische Details" + Sie können auch `from starlette.responses import JSONResponse` verwenden. + + **FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. + +## Eine benutzerdefinierte `Response` zurückgeben + +Das obige Beispiel zeigt alle Teile, die Sie benötigen, ist aber noch nicht sehr nützlich, da Sie das `item` einfach direkt hätten zurückgeben können, und **FastAPI** würde es für Sie in eine `JSONResponse` einfügen, es in ein `dict` konvertieren, usw. All das standardmäßig. + +Sehen wir uns nun an, wie Sie damit eine benutzerdefinierte Response zurückgeben können. + +Nehmen wir an, Sie möchten eine XML-Response zurückgeben. + +Sie könnten Ihren XML-Inhalt als String in eine `Response` einfügen und sie zurückgeben: + +```Python hl_lines="1 18" +{!../../../docs_src/response_directly/tutorial002.py!} +``` + +## Anmerkungen + +Wenn Sie eine `Response` direkt zurücksenden, werden deren Daten weder validiert, konvertiert (serialisiert), noch automatisch dokumentiert. + +Sie können sie aber trotzdem wie unter [Zusätzliche Responses in OpenAPI](additional-responses.md){.internal-link target=_blank} beschrieben dokumentieren. + +In späteren Abschnitten erfahren Sie, wie Sie diese benutzerdefinierten `Response`s verwenden/deklarieren und gleichzeitig über automatische Datenkonvertierung, Dokumentation, usw. verfügen. diff --git a/docs/de/docs/advanced/response-headers.md b/docs/de/docs/advanced/response-headers.md new file mode 100644 index 0000000000000..6f4760e7fd2c4 --- /dev/null +++ b/docs/de/docs/advanced/response-headers.md @@ -0,0 +1,42 @@ +# Response-Header + +## Verwenden Sie einen `Response`-Parameter + +Sie können einen Parameter vom Typ `Response` in Ihrer *Pfadoperation-Funktion* deklarieren (wie Sie es auch für Cookies tun können). + +Und dann können Sie Header in diesem *vorübergehenden* Response-Objekt festlegen. + +```Python hl_lines="1 7-8" +{!../../../docs_src/response_headers/tutorial002.py!} +``` + +Anschließend können Sie wie gewohnt jedes gewünschte Objekt zurückgeben (ein `dict`, ein Datenbankmodell, usw.). + +Und wenn Sie ein `response_model` deklariert haben, wird es weiterhin zum Filtern und Konvertieren des von Ihnen zurückgegebenen Objekts verwendet. + +**FastAPI** verwendet diese *vorübergehende* Response, um die Header (auch Cookies und Statuscode) zu extrahieren und fügt diese in die endgültige Response ein, die den von Ihnen zurückgegebenen Wert enthält, gefiltert nach einem beliebigen `response_model`. + +Sie können den Parameter `Response` auch in Abhängigkeiten deklarieren und darin Header (und Cookies) festlegen. + +## Eine `Response` direkt zurückgeben + +Sie können auch Header hinzufügen, wenn Sie eine `Response` direkt zurückgeben. + +Erstellen Sie eine Response wie in [Eine Response direkt zurückgeben](response-directly.md){.internal-link target=_blank} beschrieben und übergeben Sie die Header als zusätzlichen Parameter: + +```Python hl_lines="10-12" +{!../../../docs_src/response_headers/tutorial001.py!} +``` + +!!! note "Technische Details" + Sie können auch `from starlette.responses import Response` oder `from starlette.responses import JSONResponse` verwenden. + + **FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. + + Und da die `Response` häufig zum Setzen von Headern und Cookies verwendet wird, stellt **FastAPI** diese auch unter `fastapi.Response` bereit. + +## Benutzerdefinierte Header + +Beachten Sie, dass benutzerdefinierte proprietäre Header mittels des Präfix 'X-' hinzugefügt werden können. + +Wenn Sie jedoch benutzerdefinierte Header haben, die ein Client in einem Browser sehen können soll, müssen Sie diese zu Ihren CORS-Konfigurationen hinzufügen (weitere Informationen finden Sie unter [CORS (Cross-Origin Resource Sharing)](../tutorial/cors.md){.internal-link target=_blank}), unter Verwendung des Parameters `expose_headers`, dokumentiert in Starlettes CORS-Dokumentation. diff --git a/docs/de/docs/advanced/security/http-basic-auth.md b/docs/de/docs/advanced/security/http-basic-auth.md new file mode 100644 index 0000000000000..9f9c0cf7d6704 --- /dev/null +++ b/docs/de/docs/advanced/security/http-basic-auth.md @@ -0,0 +1,164 @@ +# HTTP Basic Auth + +Für die einfachsten Fälle können Sie HTTP Basic Auth verwenden. + +Bei HTTP Basic Auth erwartet die Anwendung einen Header, der einen Benutzernamen und ein Passwort enthält. + +Wenn sie diesen nicht empfängt, gibt sie den HTTP-Error 401 „Unauthorized“ zurück. + +Und gibt einen Header `WWW-Authenticate` mit dem Wert `Basic` und einem optionalen `realm`-Parameter („Bereich“) zurück. + +Dadurch wird der Browser angewiesen, die integrierte Eingabeaufforderung für einen Benutzernamen und ein Passwort anzuzeigen. + +Wenn Sie dann den Benutzernamen und das Passwort eingeben, sendet der Browser diese automatisch im Header. + +## Einfaches HTTP Basic Auth + +* Importieren Sie `HTTPBasic` und `HTTPBasicCredentials`. +* Erstellen Sie mit `HTTPBasic` ein „`security`-Schema“. +* Verwenden Sie dieses `security` mit einer Abhängigkeit in Ihrer *Pfadoperation*. +* Diese gibt ein Objekt vom Typ `HTTPBasicCredentials` zurück: + * Es enthält den gesendeten `username` und das gesendete `password`. + +=== "Python 3.9+" + + ```Python hl_lines="4 8 12" + {!> ../../../docs_src/security/tutorial006_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="2 7 11" + {!> ../../../docs_src/security/tutorial006_an.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="2 6 10" + {!> ../../../docs_src/security/tutorial006.py!} + ``` + +Wenn Sie versuchen, die URL zum ersten Mal zu öffnen (oder in der Dokumentation auf den Button „Execute“ zu klicken), wird der Browser Sie nach Ihrem Benutzernamen und Passwort fragen: + + + +## Den Benutzernamen überprüfen + +Hier ist ein vollständigeres Beispiel. + +Verwenden Sie eine Abhängigkeit, um zu überprüfen, ob Benutzername und Passwort korrekt sind. + +Verwenden Sie dazu das Python-Standardmodul `secrets`, um den Benutzernamen und das Passwort zu überprüfen. + +`secrets.compare_digest()` benötigt `bytes` oder einen `str`, welcher nur ASCII-Zeichen (solche der englischen Sprache) enthalten darf, das bedeutet, dass es nicht mit Zeichen wie `á`, wie in `Sebastián`, funktionieren würde. + +Um dies zu lösen, konvertieren wir zunächst den `username` und das `password` in UTF-8-codierte `bytes`. + +Dann können wir `secrets.compare_digest()` verwenden, um sicherzustellen, dass `credentials.username` `"stanleyjobson"` und `credentials.password` `"swordfish"` ist. + +=== "Python 3.9+" + + ```Python hl_lines="1 12-24" + {!> ../../../docs_src/security/tutorial007_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="1 12-24" + {!> ../../../docs_src/security/tutorial007_an.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="1 11-21" + {!> ../../../docs_src/security/tutorial007.py!} + ``` + +Dies wäre das gleiche wie: + +```Python +if not (credentials.username == "stanleyjobson") or not (credentials.password == "swordfish"): + # Einen Error zurückgeben + ... +``` + +Aber durch die Verwendung von `secrets.compare_digest()` ist dieser Code sicher vor einer Art von Angriffen, die „Timing-Angriffe“ genannt werden. + +### Timing-Angriffe + +Aber was ist ein „Timing-Angriff“? + +Stellen wir uns vor, dass einige Angreifer versuchen, den Benutzernamen und das Passwort zu erraten. + +Und sie senden eine Anfrage mit dem Benutzernamen `johndoe` und dem Passwort `love123`. + +Dann würde der Python-Code in Ihrer Anwendung etwa so aussehen: + +```Python +if "johndoe" == "stanleyjobson" and "love123" == "swordfish": + ... +``` + +Aber genau in dem Moment, in dem Python das erste `j` in `johndoe` mit dem ersten `s` in `stanleyjobson` vergleicht, gibt es `False` zurück, da es bereits weiß, dass diese beiden Strings nicht identisch sind, und denkt, „Es besteht keine Notwendigkeit, weitere Berechnungen mit dem Vergleich der restlichen Buchstaben zu verschwenden“. Und Ihre Anwendung wird zurückgeben „Incorrect username or password“. + +Doch dann versuchen es die Angreifer mit dem Benutzernamen `stanleyjobsox` und dem Passwort `love123`. + +Und Ihr Anwendungscode macht etwa Folgendes: + +```Python +if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish": + ... +``` + +Python muss das gesamte `stanleyjobso` in `stanleyjobsox` und `stanleyjobson` vergleichen, bevor es erkennt, dass beide Zeichenfolgen nicht gleich sind. Daher wird es einige zusätzliche Mikrosekunden dauern, bis die Antwort „Incorrect username or password“ erfolgt. + +#### Die Zeit zum Antworten hilft den Angreifern + +Wenn die Angreifer zu diesem Zeitpunkt feststellen, dass der Server einige Mikrosekunden länger braucht, um die Antwort „Incorrect username or password“ zu senden, wissen sie, dass sie _etwas_ richtig gemacht haben, einige der Anfangsbuchstaben waren richtig. + +Und dann können sie es noch einmal versuchen, wohl wissend, dass es wahrscheinlich eher etwas mit `stanleyjobsox` als mit `johndoe` zu tun hat. + +#### Ein „professioneller“ Angriff + +Natürlich würden die Angreifer das alles nicht von Hand versuchen, sondern ein Programm dafür schreiben, möglicherweise mit Tausenden oder Millionen Tests pro Sekunde. Und würden jeweils nur einen zusätzlichen richtigen Buchstaben erhalten. + +Aber so hätten die Angreifer in wenigen Minuten oder Stunden mit der „Hilfe“ unserer Anwendung den richtigen Benutzernamen und das richtige Passwort erraten, indem sie die Zeitspanne zur Hilfe nehmen, die diese zur Beantwortung benötigt. + +#### Das Problem beheben mittels `secrets.compare_digest()` + +Aber in unserem Code verwenden wir tatsächlich `secrets.compare_digest()`. + +Damit wird, kurz gesagt, der Vergleich von `stanleyjobsox` mit `stanleyjobson` genauso lange dauern wie der Vergleich von `johndoe` mit `stanleyjobson`. Und das Gleiche gilt für das Passwort. + +So ist Ihr Anwendungscode, dank der Verwendung von `secrets.compare_digest()`, vor dieser ganzen Klasse von Sicherheitsangriffen geschützt. + +### Den Error zurückgeben + +Nachdem Sie festgestellt haben, dass die Anmeldeinformationen falsch sind, geben Sie eine `HTTPException` mit dem Statuscode 401 zurück (derselbe, der auch zurückgegeben wird, wenn keine Anmeldeinformationen angegeben werden) und fügen den Header `WWW-Authenticate` hinzu, damit der Browser die Anmeldeaufforderung erneut anzeigt: + +=== "Python 3.9+" + + ```Python hl_lines="26-30" + {!> ../../../docs_src/security/tutorial007_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="26-30" + {!> ../../../docs_src/security/tutorial007_an.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="23-27" + {!> ../../../docs_src/security/tutorial007.py!} + ``` diff --git a/docs/de/docs/advanced/security/index.md b/docs/de/docs/advanced/security/index.md new file mode 100644 index 0000000000000..a3c975bed580b --- /dev/null +++ b/docs/de/docs/advanced/security/index.md @@ -0,0 +1,16 @@ +# Fortgeschrittene Sicherheit + +## Zusatzfunktionen + +Neben den in [Tutorial – Benutzerhandbuch: Sicherheit](../../tutorial/security/index.md){.internal-link target=_blank} behandelten Funktionen gibt es noch einige zusätzliche Funktionen zur Handhabung der Sicherheit. + +!!! tip "Tipp" + Die nächsten Abschnitte sind **nicht unbedingt „fortgeschritten“**. + + Und es ist möglich, dass für Ihren Anwendungsfall die Lösung in einem davon liegt. + +## Lesen Sie zuerst das Tutorial + +In den nächsten Abschnitten wird davon ausgegangen, dass Sie das Haupt-[Tutorial – Benutzerhandbuch: Sicherheit](../../tutorial/security/index.md){.internal-link target=_blank} bereits gelesen haben. + +Sie basieren alle auf den gleichen Konzepten, ermöglichen jedoch einige zusätzliche Funktionalitäten. diff --git a/docs/de/docs/advanced/security/oauth2-scopes.md b/docs/de/docs/advanced/security/oauth2-scopes.md new file mode 100644 index 0000000000000..ffd34d65f068a --- /dev/null +++ b/docs/de/docs/advanced/security/oauth2-scopes.md @@ -0,0 +1,598 @@ +# OAuth2-Scopes + +Sie können OAuth2-Scopes direkt in **FastAPI** verwenden, sie sind nahtlos integriert. + +Das ermöglicht es Ihnen, ein feingranuliertes Berechtigungssystem nach dem OAuth2-Standard in Ihre OpenAPI-Anwendung (und deren API-Dokumentation) zu integrieren. + +OAuth2 mit Scopes ist der Mechanismus, der von vielen großen Authentifizierungsanbietern wie Facebook, Google, GitHub, Microsoft, Twitter usw. verwendet wird. Sie verwenden ihn, um Benutzern und Anwendungen spezifische Berechtigungen zu erteilen. + +Jedes Mal, wenn Sie sich mit Facebook, Google, GitHub, Microsoft oder Twitter anmelden („log in with“), verwendet die entsprechende Anwendung OAuth2 mit Scopes. + +In diesem Abschnitt erfahren Sie, wie Sie Authentifizierung und Autorisierung mit demselben OAuth2, mit Scopes in Ihrer **FastAPI**-Anwendung verwalten. + +!!! warning "Achtung" + Dies ist ein mehr oder weniger fortgeschrittener Abschnitt. Wenn Sie gerade erst anfangen, können Sie ihn überspringen. + + Sie benötigen nicht unbedingt OAuth2-Scopes, und Sie können die Authentifizierung und Autorisierung handhaben wie Sie möchten. + + Aber OAuth2 mit Scopes kann bequem in Ihre API (mit OpenAPI) und deren API-Dokumentation integriert werden. + + Dennoch, verwenden Sie solche Scopes oder andere Sicherheits-/Autorisierungsanforderungen in Ihrem Code so wie Sie es möchten. + + In vielen Fällen kann OAuth2 mit Scopes ein Overkill sein. + + Aber wenn Sie wissen, dass Sie es brauchen oder neugierig sind, lesen Sie weiter. + +## OAuth2-Scopes und OpenAPI + +Die OAuth2-Spezifikation definiert „Scopes“ als eine Liste von durch Leerzeichen getrennten Strings. + +Der Inhalt jedes dieser Strings kann ein beliebiges Format haben, sollte jedoch keine Leerzeichen enthalten. + +Diese Scopes stellen „Berechtigungen“ dar. + +In OpenAPI (z. B. der API-Dokumentation) können Sie „Sicherheitsschemas“ definieren. + +Wenn eines dieser Sicherheitsschemas OAuth2 verwendet, können Sie auch Scopes deklarieren und verwenden. + +Jeder „Scope“ ist nur ein String (ohne Leerzeichen). + +Er wird normalerweise verwendet, um bestimmte Sicherheitsberechtigungen zu deklarieren, zum Beispiel: + +* `users:read` oder `users:write` sind gängige Beispiele. +* `instagram_basic` wird von Facebook / Instagram verwendet. +* `https://www.googleapis.com/auth/drive` wird von Google verwendet. + +!!! info + In OAuth2 ist ein „Scope“ nur ein String, der eine bestimmte erforderliche Berechtigung deklariert. + + Es spielt keine Rolle, ob er andere Zeichen wie `:` enthält oder ob es eine URL ist. + + Diese Details sind implementierungsspezifisch. + + Für OAuth2 sind es einfach nur Strings. + +## Gesamtübersicht + +Sehen wir uns zunächst kurz die Teile an, die sich gegenüber den Beispielen im Haupt-**Tutorial – Benutzerhandbuch** für [OAuth2 mit Password (und Hashing), Bearer mit JWT-Tokens](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank} ändern. Diesmal verwenden wir OAuth2-Scopes: + +=== "Python 3.10+" + + ```Python hl_lines="4 8 12 46 64 105 107-115 121-124 128-134 139 155" + {!> ../../../docs_src/security/tutorial005_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" + {!> ../../../docs_src/security/tutorial005_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```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+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="3 7 11 45 63 104 106-114 120-123 127-133 138 154" + {!> ../../../docs_src/security/tutorial005_py310.py!} + ``` + +=== "Python 3.9+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" + {!> ../../../docs_src/security/tutorial005_py39.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" + {!> ../../../docs_src/security/tutorial005.py!} + ``` + +Sehen wir uns diese Änderungen nun Schritt für Schritt an. + +## OAuth2-Sicherheitsschema + +Die erste Änderung ist, dass wir jetzt das OAuth2-Sicherheitsschema mit zwei verfügbaren Scopes deklarieren: `me` und `items`. + +Der `scopes`-Parameter erhält ein `dict` mit jedem Scope als Schlüssel und dessen Beschreibung als Wert: + +=== "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.8+" + + ```Python hl_lines="63-66" + {!> ../../../docs_src/security/tutorial005_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="61-64" + {!> ../../../docs_src/security/tutorial005_py310.py!} + ``` + + +=== "Python 3.9+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="62-65" + {!> ../../../docs_src/security/tutorial005_py39.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="62-65" + {!> ../../../docs_src/security/tutorial005.py!} + ``` + +Da wir diese Scopes jetzt deklarieren, werden sie in der API-Dokumentation angezeigt, wenn Sie sich einloggen/autorisieren. + +Und Sie können auswählen, auf welche Scopes Sie Zugriff haben möchten: `me` und `items`. + +Das ist derselbe Mechanismus, der verwendet wird, wenn Sie beim Anmelden mit Facebook, Google, GitHub, usw. Berechtigungen erteilen: + + + +## JWT-Token mit Scopes + +Ändern Sie nun die Token-*Pfadoperation*, um die angeforderten Scopes zurückzugeben. + +Wir verwenden immer noch dasselbe `OAuth2PasswordRequestForm`. Es enthält eine Eigenschaft `scopes` mit einer `list`e von `str`s für jeden Scope, den es im Request erhalten hat. + +Und wir geben die Scopes als Teil des JWT-Tokens zurück. + +!!! danger "Gefahr" + Der Einfachheit halber fügen wir hier die empfangenen Scopes direkt zum Token hinzu. + + Aus Sicherheitsgründen sollten Sie jedoch sicherstellen, dass Sie in Ihrer Anwendung nur die Scopes hinzufügen, die der Benutzer tatsächlich haben kann, oder die Sie vordefiniert haben. + +=== "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.8+" + + ```Python hl_lines="156" + {!> ../../../docs_src/security/tutorial005_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="154" + {!> ../../../docs_src/security/tutorial005_py310.py!} + ``` + +=== "Python 3.9+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="155" + {!> ../../../docs_src/security/tutorial005_py39.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="155" + {!> ../../../docs_src/security/tutorial005.py!} + ``` + +## Scopes in *Pfadoperationen* und Abhängigkeiten deklarieren + +Jetzt deklarieren wir, dass die *Pfadoperation* für `/users/me/items/` den Scope `items` erfordert. + +Dazu importieren und verwenden wir `Security` von `fastapi`. + +Sie können `Security` verwenden, um Abhängigkeiten zu deklarieren (genau wie `Depends`), aber `Security` erhält auch einen Parameter `scopes` mit einer Liste von Scopes (Strings). + +In diesem Fall übergeben wir eine Abhängigkeitsfunktion `get_current_active_user` an `Security` (genauso wie wir es mit `Depends` tun würden). + +Wir übergeben aber auch eine `list`e von Scopes, in diesem Fall mit nur einem Scope: `items` (es könnten mehrere sein). + +Und die Abhängigkeitsfunktion `get_current_active_user` kann auch Unterabhängigkeiten deklarieren, nicht nur mit `Depends`, sondern auch mit `Security`. Ihre eigene Unterabhängigkeitsfunktion (`get_current_user`) und weitere Scope-Anforderungen deklarierend. + +In diesem Fall erfordert sie den Scope `me` (sie könnte mehr als einen Scope erfordern). + +!!! note "Hinweis" + Sie müssen nicht unbedingt an verschiedenen Stellen verschiedene Scopes hinzufügen. + + Wir tun dies hier, um zu demonstrieren, wie **FastAPI** auf verschiedenen Ebenen deklarierte Scopes verarbeitet. + +=== "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.8+" + + ```Python hl_lines="4 140 171" + {!> ../../../docs_src/security/tutorial005_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="3 138 167" + {!> ../../../docs_src/security/tutorial005_py310.py!} + ``` + +=== "Python 3.9+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="4 139 168" + {!> ../../../docs_src/security/tutorial005_py39.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="4 139 168" + {!> ../../../docs_src/security/tutorial005.py!} + ``` + +!!! info "Technische Details" + `Security` ist tatsächlich eine Unterklasse von `Depends` und hat nur noch einen zusätzlichen Parameter, den wir später kennenlernen werden. + + Durch die Verwendung von `Security` anstelle von `Depends` weiß **FastAPI** jedoch, dass es Sicherheits-Scopes deklarieren, intern verwenden und die API mit OpenAPI dokumentieren kann. + + Wenn Sie jedoch `Query`, `Path`, `Depends`, `Security` und andere von `fastapi` importieren, handelt es sich tatsächlich um Funktionen, die spezielle Klassen zurückgeben. + +## `SecurityScopes` verwenden + +Aktualisieren Sie nun die Abhängigkeit `get_current_user`. + +Das ist diejenige, die von den oben genannten Abhängigkeiten verwendet wird. + +Hier verwenden wir dasselbe OAuth2-Schema, das wir zuvor erstellt haben, und deklarieren es als Abhängigkeit: `oauth2_scheme`. + +Da diese Abhängigkeitsfunktion selbst keine Scope-Anforderungen hat, können wir `Depends` mit `oauth2_scheme` verwenden. Wir müssen `Security` nicht verwenden, wenn wir keine Sicherheits-Scopes angeben müssen. + +Wir deklarieren auch einen speziellen Parameter vom Typ `SecurityScopes`, der aus `fastapi.security` importiert wird. + +Diese `SecurityScopes`-Klasse ähnelt `Request` (`Request` wurde verwendet, um das Request-Objekt direkt zu erhalten). + +=== "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.8+" + + ```Python hl_lines="8 106" + {!> ../../../docs_src/security/tutorial005_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="7 104" + {!> ../../../docs_src/security/tutorial005_py310.py!} + ``` + +=== "Python 3.9+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="8 105" + {!> ../../../docs_src/security/tutorial005_py39.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="8 105" + {!> ../../../docs_src/security/tutorial005.py!} + ``` + +## Die `scopes` verwenden + +Der Parameter `security_scopes` wird vom Typ `SecurityScopes` sein. + +Dieses verfügt über ein Attribut `scopes` mit einer Liste, die alle von ihm selbst benötigten Scopes enthält und ferner alle Abhängigkeiten, die dieses als Unterabhängigkeit verwenden. Sprich, alle „Dependanten“ ... das mag verwirrend klingen, wird aber später noch einmal erklärt. + +Das `security_scopes`-Objekt (der Klasse `SecurityScopes`) stellt außerdem ein `scope_str`-Attribut mit einem einzelnen String bereit, der die durch Leerzeichen getrennten Scopes enthält (den werden wir verwenden). + +Wir erstellen eine `HTTPException`, die wir später an mehreren Stellen wiederverwenden (`raise`n) können. + +In diese Exception fügen wir (falls vorhanden) die erforderlichen Scopes als durch Leerzeichen getrennten String ein (unter Verwendung von `scope_str`). Wir fügen diesen String mit den Scopes in den Header `WWW-Authenticate` ein (das ist Teil der Spezifikation). + +=== "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.8+" + + ```Python hl_lines="106 108-116" + {!> ../../../docs_src/security/tutorial005_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="104 106-114" + {!> ../../../docs_src/security/tutorial005_py310.py!} + ``` + +=== "Python 3.9+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="105 107-115" + {!> ../../../docs_src/security/tutorial005_py39.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="105 107-115" + {!> ../../../docs_src/security/tutorial005.py!} + ``` + +## Den `username` und das Format der Daten überprüfen + +Wir verifizieren, dass wir einen `username` erhalten, und extrahieren die Scopes. + +Und dann validieren wir diese Daten mit dem Pydantic-Modell (wobei wir die `ValidationError`-Exception abfangen), und wenn wir beim Lesen des JWT-Tokens oder beim Validieren der Daten mit Pydantic einen Fehler erhalten, lösen wir die zuvor erstellte `HTTPException` aus. + +Dazu aktualisieren wir das Pydantic-Modell `TokenData` mit einem neuen Attribut `scopes`. + +Durch die Validierung der Daten mit Pydantic können wir sicherstellen, dass wir beispielsweise präzise eine `list`e von `str`s mit den Scopes und einen `str` mit dem `username` haben. + +Anstelle beispielsweise eines `dict`s oder etwas anderem, was später in der Anwendung zu Fehlern führen könnte und darum ein Sicherheitsrisiko darstellt. + +Wir verifizieren auch, dass wir einen Benutzer mit diesem Benutzernamen haben, und wenn nicht, lösen wir dieselbe Exception aus, die wir zuvor erstellt haben. + +=== "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.8+" + + ```Python hl_lines="47 117-128" + {!> ../../../docs_src/security/tutorial005_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="45 115-126" + {!> ../../../docs_src/security/tutorial005_py310.py!} + ``` + +=== "Python 3.9+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="46 116-127" + {!> ../../../docs_src/security/tutorial005_py39.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="46 116-127" + {!> ../../../docs_src/security/tutorial005.py!} + ``` + +## Die `scopes` verifizieren + +Wir überprüfen nun, ob das empfangenen Token alle Scopes enthält, die von dieser Abhängigkeit und deren Verwendern (einschließlich *Pfadoperationen*) gefordert werden. Andernfalls lösen wir eine `HTTPException` aus. + +Hierzu verwenden wir `security_scopes.scopes`, das eine `list`e mit allen diesen Scopes als `str` enthält. + +=== "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.8+" + + ```Python hl_lines="129-135" + {!> ../../../docs_src/security/tutorial005_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="127-133" + {!> ../../../docs_src/security/tutorial005_py310.py!} + ``` + +=== "Python 3.9+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="128-134" + {!> ../../../docs_src/security/tutorial005_py39.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="128-134" + {!> ../../../docs_src/security/tutorial005.py!} + ``` + +## Abhängigkeitsbaum und Scopes + +Sehen wir uns diesen Abhängigkeitsbaum und die Scopes noch einmal an. + +Da die Abhängigkeit `get_current_active_user` von `get_current_user` abhängt, wird der bei `get_current_active_user` deklarierte Scope `"me"` in die Liste der erforderlichen Scopes in `security_scopes.scopes` aufgenommen, das an `get_current_user` übergeben wird. + +Die *Pfadoperation* selbst deklariert auch einen Scope, `"items"`, sodass dieser auch in der Liste der `security_scopes.scopes` enthalten ist, die an `get_current_user` übergeben wird. + +So sieht die Hierarchie der Abhängigkeiten und Scopes aus: + +* Die *Pfadoperation* `read_own_items` hat: + * Erforderliche Scopes `["items"]` mit der Abhängigkeit: + * `get_current_active_user`: + * Die Abhängigkeitsfunktion `get_current_active_user` hat: + * Erforderliche Scopes `["me"]` mit der Abhängigkeit: + * `get_current_user`: + * Die Abhängigkeitsfunktion `get_current_user` hat: + * Selbst keine erforderlichen Scopes. + * Eine Abhängigkeit, die `oauth2_scheme` verwendet. + * Einen `security_scopes`-Parameter vom Typ `SecurityScopes`: + * Dieser `security_scopes`-Parameter hat ein Attribut `scopes` mit einer `list`e, die alle oben deklarierten Scopes enthält, sprich: + * `security_scopes.scopes` enthält `["me", "items"]` für die *Pfadoperation* `read_own_items`. + * `security_scopes.scopes` enthält `["me"]` für die *Pfadoperation* `read_users_me`, da das in der Abhängigkeit `get_current_active_user` deklariert ist. + * `security_scopes.scopes` wird `[]` (nichts) für die *Pfadoperation* `read_system_status` enthalten, da diese keine `Security` mit `scopes` deklariert hat, und deren Abhängigkeit `get_current_user` ebenfalls keinerlei `scopes` deklariert. + +!!! tip "Tipp" + Das Wichtige und „Magische“ hier ist, dass `get_current_user` für jede *Pfadoperation* eine andere Liste von `scopes` hat, die überprüft werden. + + Alles hängt von den „Scopes“ ab, die in jeder *Pfadoperation* und jeder Abhängigkeit im Abhängigkeitsbaum für diese bestimmte *Pfadoperation* deklariert wurden. + +## Weitere Details zu `SecurityScopes`. + +Sie können `SecurityScopes` an jeder Stelle und an mehreren Stellen verwenden, es muss sich nicht in der „Wurzel“-Abhängigkeit befinden. + +Es wird immer die Sicherheits-Scopes enthalten, die in den aktuellen `Security`-Abhängigkeiten deklariert sind und in allen Abhängigkeiten für **diese spezifische** *Pfadoperation* und **diesen spezifischen** Abhängigkeitsbaum. + +Da die `SecurityScopes` alle von den Verwendern der Abhängigkeiten deklarierten Scopes enthalten, können Sie damit überprüfen, ob ein Token in einer zentralen Abhängigkeitsfunktion über die erforderlichen Scopes verfügt, und dann unterschiedliche Scope-Anforderungen in unterschiedlichen *Pfadoperationen* deklarieren. + +Diese werden für jede *Pfadoperation* unabhängig überprüft. + +## Testen Sie es + +Wenn Sie die API-Dokumentation öffnen, können Sie sich authentisieren und angeben, welche Scopes Sie autorisieren möchten. + + + +Wenn Sie keinen Scope auswählen, werden Sie „authentifiziert“, aber wenn Sie versuchen, auf `/users/me/` oder `/users/me/items/` zuzugreifen, wird eine Fehlermeldung angezeigt, die sagt, dass Sie nicht über genügend Berechtigungen verfügen. Sie können aber auf `/status/` zugreifen. + +Und wenn Sie den Scope `me`, aber nicht den Scope `items` auswählen, können Sie auf `/users/me/` zugreifen, aber nicht auf `/users/me/items/`. + +Das würde einer Drittanbieteranwendung passieren, die versucht, auf eine dieser *Pfadoperationen* mit einem Token zuzugreifen, das von einem Benutzer bereitgestellt wurde, abhängig davon, wie viele Berechtigungen der Benutzer dieser Anwendung erteilt hat. + +## Über Integrationen von Drittanbietern + +In diesem Beispiel verwenden wir den OAuth2-Flow „Password“. + +Das ist angemessen, wenn wir uns bei unserer eigenen Anwendung anmelden, wahrscheinlich mit unserem eigenen Frontend. + +Weil wir darauf vertrauen können, dass es den `username` und das `password` erhält, welche wir kontrollieren. + +Wenn Sie jedoch eine OAuth2-Anwendung erstellen, mit der andere eine Verbindung herstellen würden (d.h. wenn Sie einen Authentifizierungsanbieter erstellen, der Facebook, Google, GitHub usw. entspricht), sollten Sie einen der anderen Flows verwenden. + +Am häufigsten ist der „Implicit“-Flow. + +Am sichersten ist der „Code“-Flow, die Implementierung ist jedoch komplexer, da mehr Schritte erforderlich sind. Da er komplexer ist, schlagen viele Anbieter letztendlich den „Implicit“-Flow vor. + +!!! note "Hinweis" + Es ist üblich, dass jeder Authentifizierungsanbieter seine Flows anders benennt, um sie zu einem Teil seiner Marke zu machen. + + Aber am Ende implementieren sie denselben OAuth2-Standard. + +**FastAPI** enthält Werkzeuge für alle diese OAuth2-Authentifizierungs-Flows in `fastapi.security.oauth2`. + +## `Security` in Dekorator-`dependencies` + +Auf die gleiche Weise können Sie eine `list`e von `Depends` im Parameter `dependencies` des Dekorators definieren (wie in [Abhängigkeiten in Pfadoperation-Dekoratoren](../../tutorial/dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank} erläutert), Sie könnten auch dort `Security` mit `scopes` verwenden. diff --git a/docs/de/docs/advanced/settings.md b/docs/de/docs/advanced/settings.md new file mode 100644 index 0000000000000..fe01d8e1fb215 --- /dev/null +++ b/docs/de/docs/advanced/settings.md @@ -0,0 +1,485 @@ +# Einstellungen und Umgebungsvariablen + +In vielen Fällen benötigt Ihre Anwendung möglicherweise einige externe Einstellungen oder Konfigurationen, zum Beispiel geheime Schlüssel, Datenbank-Anmeldeinformationen, Anmeldeinformationen für E-Mail-Dienste, usw. + +Die meisten dieser Einstellungen sind variabel (können sich ändern), wie z. B. Datenbank-URLs. Und vieles könnten schützenswerte, geheime Daten sein. + +Aus diesem Grund werden diese üblicherweise in Umgebungsvariablen bereitgestellt, die von der Anwendung gelesen werden. + +## Umgebungsvariablen + +!!! tip "Tipp" + Wenn Sie bereits wissen, was „Umgebungsvariablen“ sind und wie man sie verwendet, können Sie gerne mit dem nächsten Abschnitt weiter unten fortfahren. + +Eine Umgebungsvariable (auch bekannt als „env var“) ist eine Variable, die sich außerhalb des Python-Codes im Betriebssystem befindet und von Ihrem Python-Code (oder auch von anderen Programmen) gelesen werden kann. + +Sie können Umgebungsvariablen in der Shell erstellen und verwenden, ohne Python zu benötigen: + +=== "Linux, macOS, Windows Bash" + +
+ + ```console + // Sie könnten eine Umgebungsvariable MY_NAME erstellen mittels + $ export MY_NAME="Wade Wilson" + + // Dann könnten Sie diese mit anderen Programmen verwenden, etwa + $ echo "Hello $MY_NAME" + + Hello Wade Wilson + ``` + +
+ +=== "Windows PowerShell" + +
+ + ```console + // Erstelle eine Umgebungsvariable MY_NAME + $ $Env:MY_NAME = "Wade Wilson" + + // Verwende sie mit anderen Programmen, etwa + $ echo "Hello $Env:MY_NAME" + + Hello Wade Wilson + ``` + +
+ +### Umgebungsvariablen mit Python auslesen + +Sie können Umgebungsvariablen auch außerhalb von Python im Terminal (oder mit einer anderen Methode) erstellen und diese dann mit Python auslesen. + +Sie könnten zum Beispiel eine Datei `main.py` haben mit: + +```Python hl_lines="3" +import os + +name = os.getenv("MY_NAME", "World") +print(f"Hello {name} from Python") +``` + +!!! tip "Tipp" + Das zweite Argument für `os.getenv()` ist der zurückzugebende Defaultwert. + + Wenn nicht angegeben, ist er standardmäßig `None`. Hier übergeben wir `"World"` als Defaultwert. + +Dann könnten Sie dieses Python-Programm aufrufen: + +
+ +```console +// Hier legen wir die Umgebungsvariable noch nicht fest +$ python main.py + +// Da wir die Umgebungsvariable nicht festgelegt haben, erhalten wir den Standardwert + +Hello World from Python + +// Aber wenn wir zuerst eine Umgebungsvariable erstellen +$ export MY_NAME="Wade Wilson" + +// Und dann das Programm erneut aufrufen +$ python main.py + +// Kann es jetzt die Umgebungsvariable lesen + +Hello Wade Wilson from Python +``` + +
+ +Da Umgebungsvariablen außerhalb des Codes festgelegt, aber vom Code gelesen werden können und nicht zusammen mit den übrigen Dateien gespeichert (an `git` committet) werden müssen, werden sie häufig für Konfigurationen oder Einstellungen verwendet. + +Sie können eine Umgebungsvariable auch nur für einen bestimmten Programmaufruf erstellen, die nur für dieses Programm und nur für dessen Dauer verfügbar ist. + +Erstellen Sie diese dazu direkt vor dem Programm selbst, in derselben Zeile: + +
+ +```console +// Erstelle eine Umgebungsvariable MY_NAME inline für diesen Programmaufruf +$ MY_NAME="Wade Wilson" python main.py + +// main.py kann jetzt diese Umgebungsvariable lesen + +Hello Wade Wilson from Python + +// Die Umgebungsvariable existiert danach nicht mehr +$ python main.py + +Hello World from Python +``` + +
+ +!!! tip "Tipp" + Weitere Informationen dazu finden Sie unter The Twelve-Factor App: Config. + +### Typen und Validierung + +Diese Umgebungsvariablen können nur Text-Zeichenketten verarbeiten, da sie außerhalb von Python liegen und mit anderen Programmen und dem Rest des Systems (und sogar mit verschiedenen Betriebssystemen wie Linux, Windows, macOS) kompatibel sein müssen. + +Das bedeutet, dass jeder in Python aus einer Umgebungsvariablen gelesene Wert ein `str` ist und jede Konvertierung in einen anderen Typ oder jede Validierung im Code erfolgen muss. + +## Pydantic `Settings` + +Glücklicherweise bietet Pydantic ein großartiges Werkzeug zur Verarbeitung dieser Einstellungen, die von Umgebungsvariablen stammen, mit Pydantic: Settings Management. + +### `pydantic-settings` installieren + +Installieren Sie zunächst das Package `pydantic-settings`: + +
+ +```console +$ pip install pydantic-settings +---> 100% +``` + +
+ +Es ist bereits enthalten, wenn Sie die `all`-Extras installiert haben, mit: + +
+ +```console +$ pip install "fastapi[all]" +---> 100% +``` + +
+ +!!! info + In Pydantic v1 war das im Hauptpackage enthalten. Jetzt wird es als unabhängiges Package verteilt, sodass Sie wählen können, ob Sie es installieren möchten oder nicht, falls Sie die Funktionalität nicht benötigen. + +### Das `Settings`-Objekt erstellen + +Importieren Sie `BaseSettings` aus Pydantic und erstellen Sie eine Unterklasse, ganz ähnlich wie bei einem Pydantic-Modell. + +Auf die gleiche Weise wie bei Pydantic-Modellen deklarieren Sie Klassenattribute mit Typannotationen und möglicherweise Defaultwerten. + +Sie können dieselben Validierungs-Funktionen und -Tools verwenden, die Sie für Pydantic-Modelle verwenden, z. B. verschiedene Datentypen und zusätzliche Validierungen mit `Field()`. + +=== "Pydantic v2" + + ```Python hl_lines="2 5-8 11" + {!> ../../../docs_src/settings/tutorial001.py!} + ``` + +=== "Pydantic v1" + + !!! info + In Pydantic v1 würden Sie `BaseSettings` direkt von `pydantic` statt von `pydantic_settings` importieren. + + ```Python hl_lines="2 5-8 11" + {!> ../../../docs_src/settings/tutorial001_pv1.py!} + ``` + +!!! tip "Tipp" + Für ein schnelles Copy-and-paste verwenden Sie nicht dieses Beispiel, sondern das letzte unten. + +Wenn Sie dann eine Instanz dieser `Settings`-Klasse erstellen (in diesem Fall als `settings`-Objekt), liest Pydantic die Umgebungsvariablen ohne Berücksichtigung der Groß- und Kleinschreibung. Eine Variable `APP_NAME` in Großbuchstaben wird also als Attribut `app_name` gelesen. + +Als Nächstes werden die Daten konvertiert und validiert. Wenn Sie also dieses `settings`-Objekt verwenden, verfügen Sie über Daten mit den von Ihnen deklarierten Typen (z. B. ist `items_per_user` ein `int`). + +### `settings` verwenden + +Dann können Sie das neue `settings`-Objekt in Ihrer Anwendung verwenden: + +```Python hl_lines="18-20" +{!../../../docs_src/settings/tutorial001.py!} +``` + +### Den Server ausführen + +Als Nächstes würden Sie den Server ausführen und die Konfigurationen als Umgebungsvariablen übergeben. Sie könnten beispielsweise `ADMIN_EMAIL` und `APP_NAME` festlegen mit: + +
+ +```console +$ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uvicorn main:app + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +!!! tip "Tipp" + Um mehrere Umgebungsvariablen für einen einzelnen Befehl festzulegen, trennen Sie diese einfach durch ein Leerzeichen und fügen Sie alle vor dem Befehl ein. + +Und dann würde die Einstellung `admin_email` auf `"deadpool@example.com"` gesetzt. + +Der `app_name` wäre `"ChimichangApp"`. + +Und `items_per_user` würde seinen Standardwert von `50` behalten. + +## Einstellungen in einem anderen Modul + +Sie könnten diese Einstellungen in eine andere Moduldatei einfügen, wie Sie in [Größere Anwendungen – mehrere Dateien](../tutorial/bigger-applications.md){.internal-link target=_blank} gesehen haben. + +Sie könnten beispielsweise eine Datei `config.py` haben mit: + +```Python +{!../../../docs_src/settings/app01/config.py!} +``` + +Und dann verwenden Sie diese in einer Datei `main.py`: + +```Python hl_lines="3 11-13" +{!../../../docs_src/settings/app01/main.py!} +``` + +!!! tip "Tipp" + Sie benötigen außerdem eine Datei `__init__.py`, wie in [Größere Anwendungen – mehrere Dateien](../tutorial/bigger-applications.md){.internal-link target=_blank} gesehen. + +## Einstellungen in einer Abhängigkeit + +In manchen Fällen kann es nützlich sein, die Einstellungen mit einer Abhängigkeit bereitzustellen, anstatt ein globales Objekt `settings` zu haben, das überall verwendet wird. + +Dies könnte besonders beim Testen nützlich sein, da es sehr einfach ist, eine Abhängigkeit mit Ihren eigenen benutzerdefinierten Einstellungen zu überschreiben. + +### Die Konfigurationsdatei + +Ausgehend vom vorherigen Beispiel könnte Ihre Datei `config.py` so aussehen: + +```Python hl_lines="10" +{!../../../docs_src/settings/app02/config.py!} +``` + +Beachten Sie, dass wir jetzt keine Standardinstanz `settings = Settings()` erstellen. + +### Die Haupt-Anwendungsdatei + +Jetzt erstellen wir eine Abhängigkeit, die ein neues `config.Settings()` zurückgibt. + +=== "Python 3.9+" + + ```Python hl_lines="6 12-13" + {!> ../../../docs_src/settings/app02_an_py39/main.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="6 12-13" + {!> ../../../docs_src/settings/app02_an/main.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="5 11-12" + {!> ../../../docs_src/settings/app02/main.py!} + ``` + +!!! tip "Tipp" + Wir werden das `@lru_cache` in Kürze besprechen. + + Im Moment nehmen Sie an, dass `get_settings()` eine normale Funktion ist. + +Und dann können wir das von der *Pfadoperation-Funktion* als Abhängigkeit einfordern und es überall dort verwenden, wo wir es brauchen. + +=== "Python 3.9+" + + ```Python hl_lines="17 19-21" + {!> ../../../docs_src/settings/app02_an_py39/main.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="17 19-21" + {!> ../../../docs_src/settings/app02_an/main.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="16 18-20" + {!> ../../../docs_src/settings/app02/main.py!} + ``` + +### Einstellungen und Tests + +Dann wäre es sehr einfach, beim Testen ein anderes Einstellungsobjekt bereitzustellen, indem man eine Abhängigkeitsüberschreibung für `get_settings` erstellt: + +```Python hl_lines="9-10 13 21" +{!../../../docs_src/settings/app02/test_main.py!} +``` + +Bei der Abhängigkeitsüberschreibung legen wir einen neuen Wert für `admin_email` fest, wenn wir das neue `Settings`-Objekt erstellen, und geben dann dieses neue Objekt zurück. + +Dann können wir testen, ob das verwendet wird. + +## Lesen einer `.env`-Datei + +Wenn Sie viele Einstellungen haben, die sich möglicherweise oft ändern, vielleicht in verschiedenen Umgebungen, kann es nützlich sein, diese in eine Datei zu schreiben und sie dann daraus zu lesen, als wären sie Umgebungsvariablen. + +Diese Praxis ist so weit verbreitet, dass sie einen Namen hat. Diese Umgebungsvariablen werden üblicherweise in einer Datei `.env` abgelegt und die Datei wird „dotenv“ genannt. + +!!! tip "Tipp" + Eine Datei, die mit einem Punkt (`.`) beginnt, ist eine versteckte Datei in Unix-ähnlichen Systemen wie Linux und macOS. + + Aber eine dotenv-Datei muss nicht unbedingt genau diesen Dateinamen haben. + +Pydantic unterstützt das Lesen dieser Dateitypen mithilfe einer externen Bibliothek. Weitere Informationen finden Sie unter Pydantic Settings: Dotenv (.env) support. + +!!! tip "Tipp" + Damit das funktioniert, müssen Sie `pip install python-dotenv` ausführen. + +### Die `.env`-Datei + +Sie könnten eine `.env`-Datei haben, mit: + +```bash +ADMIN_EMAIL="deadpool@example.com" +APP_NAME="ChimichangApp" +``` + +### Einstellungen aus `.env` lesen + +Und dann aktualisieren Sie Ihre `config.py` mit: + +=== "Pydantic v2" + + ```Python hl_lines="9" + {!> ../../../docs_src/settings/app03_an/config.py!} + ``` + + !!! tip "Tipp" + Das Attribut `model_config` wird nur für die Pydantic-Konfiguration verwendet. Weitere Informationen finden Sie unter Pydantic: Configuration. + +=== "Pydantic v1" + + ```Python hl_lines="9-10" + {!> ../../../docs_src/settings/app03_an/config_pv1.py!} + ``` + + !!! tip "Tipp" + Die Klasse `Config` wird nur für die Pydantic-Konfiguration verwendet. Weitere Informationen finden Sie unter Pydantic Model Config. + +!!! info + In Pydantic Version 1 erfolgte die Konfiguration in einer internen Klasse `Config`, in Pydantic Version 2 erfolgt sie in einem Attribut `model_config`. Dieses Attribut akzeptiert ein `dict`. Um automatische Codevervollständigung und Inline-Fehlerberichte zu erhalten, können Sie `SettingsConfigDict` importieren und verwenden, um dieses `dict` zu definieren. + +Hier definieren wir die Konfiguration `env_file` innerhalb Ihrer Pydantic-`Settings`-Klasse und setzen den Wert auf den Dateinamen mit der dotenv-Datei, die wir verwenden möchten. + +### Die `Settings` nur einmal laden mittels `lru_cache` + +Das Lesen einer Datei von der Festplatte ist normalerweise ein kostspieliger (langsamer) Vorgang, daher möchten Sie ihn wahrscheinlich nur einmal ausführen und dann dasselbe Einstellungsobjekt erneut verwenden, anstatt es für jeden Request zu lesen. + +Aber jedes Mal, wenn wir ausführen: + +```Python +Settings() +``` + +würde ein neues `Settings`-Objekt erstellt und bei der Erstellung würde die `.env`-Datei erneut ausgelesen. + +Wenn die Abhängigkeitsfunktion wie folgt wäre: + +```Python +def get_settings(): + return Settings() +``` + +würden wir dieses Objekt für jeden Request erstellen und die `.env`-Datei für jeden Request lesen. ⚠️ + +Da wir jedoch den `@lru_cache`-Dekorator oben verwenden, wird das `Settings`-Objekt nur einmal erstellt, nämlich beim ersten Aufruf. ✔️ + +=== "Python 3.9+" + + ```Python hl_lines="1 11" + {!> ../../../docs_src/settings/app03_an_py39/main.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="1 11" + {!> ../../../docs_src/settings/app03_an/main.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="1 10" + {!> ../../../docs_src/settings/app03/main.py!} + ``` + +Dann wird bei allen nachfolgenden Aufrufen von `get_settings()`, in den Abhängigkeiten für darauffolgende Requests, dasselbe Objekt zurückgegeben, das beim ersten Aufruf zurückgegeben wurde, anstatt den Code von `get_settings()` erneut auszuführen und ein neues `Settings`-Objekt zu erstellen. + +#### Technische Details zu `lru_cache` + +`@lru_cache` ändert die Funktion, die es dekoriert, dahingehend, denselben Wert zurückzugeben, der beim ersten Mal zurückgegeben wurde, anstatt ihn erneut zu berechnen und den Code der Funktion jedes Mal auszuführen. + +Die darunter liegende Funktion wird also für jede Argumentkombination einmal ausgeführt. Und dann werden die von jeder dieser Argumentkombinationen zurückgegebenen Werte immer wieder verwendet, wenn die Funktion mit genau derselben Argumentkombination aufgerufen wird. + +Wenn Sie beispielsweise eine Funktion haben: + +```Python +@lru_cache +def say_hi(name: str, salutation: str = "Ms."): + return f"Hello {salutation} {name}" +``` + +könnte Ihr Programm so ausgeführt werden: + +```mermaid +sequenceDiagram + +participant code as Code +participant function as say_hi() +participant execute as Funktion ausgeführt + + rect rgba(0, 255, 0, .1) + code ->> function: say_hi(name="Camila") + function ->> execute: führe Code der Funktion aus + execute ->> code: gib das Resultat zurück + end + + rect rgba(0, 255, 255, .1) + code ->> function: say_hi(name="Camila") + function ->> code: gib das gespeicherte Resultat zurück + end + + rect rgba(0, 255, 0, .1) + code ->> function: say_hi(name="Rick") + function ->> execute: führe Code der Funktion aus + execute ->> code: gib das Resultat zurück + end + + rect rgba(0, 255, 0, .1) + code ->> function: say_hi(name="Rick", salutation="Mr.") + function ->> execute: führe Code der Funktion aus + execute ->> code: gib das Resultat zurück + end + + rect rgba(0, 255, 255, .1) + code ->> function: say_hi(name="Rick") + function ->> code: gib das gespeicherte Resultat zurück + end + + rect rgba(0, 255, 255, .1) + code ->> function: say_hi(name="Camila") + function ->> code: gib das gespeicherte Resultat zurück + end +``` + +Im Fall unserer Abhängigkeit `get_settings()` akzeptiert die Funktion nicht einmal Argumente, sodass sie immer den gleichen Wert zurückgibt. + +Auf diese Weise verhält es sich fast so, als wäre es nur eine globale Variable. Da es jedoch eine Abhängigkeitsfunktion verwendet, können wir diese zu Testzwecken problemlos überschreiben. + +`@lru_cache` ist Teil von `functools`, welches Teil von Pythons Standardbibliothek ist. Weitere Informationen dazu finden Sie in der Python Dokumentation für `@lru_cache`. + +## Zusammenfassung + +Mit Pydantic Settings können Sie die Einstellungen oder Konfigurationen für Ihre Anwendung verwalten und dabei die gesamte Leistungsfähigkeit der Pydantic-Modelle nutzen. + +* Durch die Verwendung einer Abhängigkeit können Sie das Testen vereinfachen. +* Sie können `.env`-Dateien damit verwenden. +* Durch die Verwendung von `@lru_cache` können Sie vermeiden, die dotenv-Datei bei jedem Request erneut zu lesen, während Sie sie während des Testens überschreiben können. diff --git a/docs/de/docs/advanced/sub-applications.md b/docs/de/docs/advanced/sub-applications.md new file mode 100644 index 0000000000000..7dfaaa0cde0f5 --- /dev/null +++ b/docs/de/docs/advanced/sub-applications.md @@ -0,0 +1,73 @@ +# Unteranwendungen – Mounts + +Wenn Sie zwei unabhängige FastAPI-Anwendungen mit deren eigenen unabhängigen OpenAPI und deren eigenen Dokumentationsoberflächen benötigen, können Sie eine Hauptanwendung haben und dann eine (oder mehrere) Unteranwendung(en) „mounten“. + +## Mounten einer **FastAPI**-Anwendung + +„Mounten“ („Einhängen“) bedeutet das Hinzufügen einer völlig „unabhängigen“ Anwendung an einem bestimmten Pfad, die sich dann um die Handhabung aller unter diesem Pfad liegenden _Pfadoperationen_ kümmert, welche in dieser Unteranwendung deklariert sind. + +### Hauptanwendung + +Erstellen Sie zunächst die Hauptanwendung **FastAPI** und deren *Pfadoperationen*: + +```Python hl_lines="3 6-8" +{!../../../docs_src/sub_applications/tutorial001.py!} +``` + +### Unteranwendung + +Erstellen Sie dann Ihre Unteranwendung und deren *Pfadoperationen*. + +Diese Unteranwendung ist nur eine weitere Standard-FastAPI-Anwendung, aber diese wird „gemountet“: + +```Python hl_lines="11 14-16" +{!../../../docs_src/sub_applications/tutorial001.py!} +``` + +### Die Unteranwendung mounten + +Mounten Sie in Ihrer Top-Level-Anwendung `app` die Unteranwendung `subapi`. + +In diesem Fall wird sie im Pfad `/subapi` gemountet: + +```Python hl_lines="11 19" +{!../../../docs_src/sub_applications/tutorial001.py!} +``` + +### Es in der automatischen API-Dokumentation betrachten + +Führen Sie nun `uvicorn` mit der Hauptanwendung aus. Wenn Ihre Datei `main.py` lautet, wäre das: + +
+ +```console +$ uvicorn main:app --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Und öffnen Sie die Dokumentation unter http://127.0.0.1:8000/docs. + +Sie sehen die automatische API-Dokumentation für die Hauptanwendung, welche nur deren eigene _Pfadoperationen_ anzeigt: + + + +Öffnen Sie dann die Dokumentation für die Unteranwendung unter http://127.0.0.1:8000/subapi/docs. + +Sie sehen die automatische API-Dokumentation für die Unteranwendung, welche nur deren eigene _Pfadoperationen_ anzeigt, alle unter dem korrekten Unterpfad-Präfix `/subapi`: + + + +Wenn Sie versuchen, mit einer der beiden Benutzeroberflächen zu interagieren, funktionieren diese ordnungsgemäß, da der Browser mit jeder spezifischen Anwendung oder Unteranwendung kommunizieren kann. + +### Technische Details: `root_path` + +Wenn Sie eine Unteranwendung wie oben beschrieben mounten, kümmert sich FastAPI darum, den Mount-Pfad für die Unteranwendung zu kommunizieren, mithilfe eines Mechanismus aus der ASGI-Spezifikation namens `root_path`. + +Auf diese Weise weiß die Unteranwendung, dass sie dieses Pfadpräfix für die Benutzeroberfläche der Dokumentation verwenden soll. + +Und die Unteranwendung könnte auch ihre eigenen gemounteten Unteranwendungen haben und alles würde korrekt funktionieren, da FastAPI sich um alle diese `root_path`s automatisch kümmert. + +Mehr über den `root_path` und dessen explizite Verwendung erfahren Sie im Abschnitt [Hinter einem Proxy](behind-a-proxy.md){.internal-link target=_blank}. diff --git a/docs/de/docs/advanced/templates.md b/docs/de/docs/advanced/templates.md new file mode 100644 index 0000000000000..17d821e613f5e --- /dev/null +++ b/docs/de/docs/advanced/templates.md @@ -0,0 +1,119 @@ +# Templates + +Sie können jede gewünschte Template-Engine mit **FastAPI** verwenden. + +Eine häufige Wahl ist Jinja2, dasselbe, was auch von Flask und anderen Tools verwendet wird. + +Es gibt Werkzeuge zur einfachen Konfiguration, die Sie direkt in Ihrer **FastAPI**-Anwendung verwenden können (bereitgestellt von Starlette). + +## Abhängigkeiten installieren + +Installieren Sie `jinja2`: + +
+ +```console +$ pip install jinja2 + +---> 100% +``` + +
+ +## Verwendung von `Jinja2Templates` + +* Importieren Sie `Jinja2Templates`. +* Erstellen Sie ein `templates`-Objekt, das Sie später wiederverwenden können. +* Deklarieren Sie einen `Request`-Parameter in der *Pfadoperation*, welcher ein Template zurückgibt. +* Verwenden Sie die von Ihnen erstellten `templates`, um eine `TemplateResponse` zu rendern und zurückzugeben, übergeben Sie den Namen des Templates, das Requestobjekt und ein „Kontext“-Dictionary mit Schlüssel-Wert-Paaren, die innerhalb des Jinja2-Templates verwendet werden sollen. + +```Python hl_lines="4 11 15-18" +{!../../../docs_src/templates/tutorial001.py!} +``` + +!!! note "Hinweis" + Vor FastAPI 0.108.0 und Starlette 0.29.0 war `name` der erste Parameter. + + Außerdem wurde in früheren Versionen das `request`-Objekt als Teil der Schlüssel-Wert-Paare im Kontext für Jinja2 übergeben. + +!!! tip "Tipp" + Durch die Deklaration von `response_class=HTMLResponse` kann die Dokumentationsoberfläche erkennen, dass die Response HTML sein wird. + +!!! note "Technische Details" + Sie können auch `from starlette.templating import Jinja2Templates` verwenden. + + **FastAPI** bietet dasselbe `starlette.templating` auch via `fastapi.templating` an, als Annehmlichkeit für Sie, den Entwickler. Es kommt aber direkt von Starlette. Das Gleiche gilt für `Request` und `StaticFiles`. + +## Templates erstellen + +Dann können Sie unter `templates/item.html` ein Template erstellen, mit z. B. folgendem Inhalt: + +```jinja hl_lines="7" +{!../../../docs_src/templates/templates/item.html!} +``` + +### Template-Kontextwerte + +Im HTML, welches enthält: + +{% raw %} + +```jinja +Item ID: {{ id }} +``` + +{% endraw %} + +... wird die `id` angezeigt, welche dem „Kontext“-`dict` entnommen wird, welches Sie übergeben haben: + +```Python +{"id": id} +``` + +Mit beispielsweise einer ID `42` würde das wie folgt gerendert werden: + +```html +Item ID: 42 +``` + +### Template-`url_for`-Argumente + +Sie können `url_for()` auch innerhalb des Templates verwenden, es nimmt als Argumente dieselben Argumente, die von Ihrer *Pfadoperation-Funktion* verwendet werden. + +Der Abschnitt mit: + +{% raw %} + +```jinja + +``` + +{% endraw %} + +... generiert also einen Link zu derselben URL, welche von der *Pfadoperation-Funktion* `read_item(id=id)` gehandhabt werden würde. + +Mit beispielsweise der ID `42` würde dies Folgendes ergeben: + +```html + +``` + +## Templates und statische Dateien + +Sie können `url_for()` innerhalb des Templates auch beispielsweise mit den `StaticFiles` verwenden, die Sie mit `name="static"` gemountet haben. + +```jinja hl_lines="4" +{!../../../docs_src/templates/templates/item.html!} +``` + +In diesem Beispiel würde das zu einer CSS-Datei unter `static/styles.css` verlinken, mit folgendem Inhalt: + +```CSS hl_lines="4" +{!../../../docs_src/templates/static/styles.css!} +``` + +Und da Sie `StaticFiles` verwenden, wird diese CSS-Datei automatisch von Ihrer **FastAPI**-Anwendung unter der URL `/static/styles.css` bereitgestellt. + +## Mehr Details + +Weitere Informationen, einschließlich, wie man Templates testet, finden Sie in der Starlette Dokumentation zu Templates. diff --git a/docs/de/docs/advanced/testing-dependencies.md b/docs/de/docs/advanced/testing-dependencies.md new file mode 100644 index 0000000000000..e7841b5f56e89 --- /dev/null +++ b/docs/de/docs/advanced/testing-dependencies.md @@ -0,0 +1,81 @@ +# Testen mit Ersatz für Abhängigkeiten + +## Abhängigkeiten beim Testen überschreiben + +Es gibt einige Szenarien, in denen Sie beim Testen möglicherweise eine Abhängigkeit überschreiben möchten. + +Sie möchten nicht, dass die ursprüngliche Abhängigkeit ausgeführt wird (und auch keine der möglicherweise vorhandenen Unterabhängigkeiten). + +Stattdessen möchten Sie eine andere Abhängigkeit bereitstellen, die nur während Tests (möglicherweise nur bei einigen bestimmten Tests) verwendet wird und einen Wert bereitstellt, der dort verwendet werden kann, wo der Wert der ursprünglichen Abhängigkeit verwendet wurde. + +### Anwendungsfälle: Externer Service + +Ein Beispiel könnte sein, dass Sie einen externen Authentifizierungsanbieter haben, mit dem Sie sich verbinden müssen. + +Sie senden ihm ein Token und er gibt einen authentifizierten Benutzer zurück. + +Dieser Anbieter berechnet Ihnen möglicherweise Gebühren pro Anfrage, und der Aufruf könnte etwas länger dauern, als wenn Sie einen vordefinierten Scheinbenutzer für Tests hätten. + +Sie möchten den externen Anbieter wahrscheinlich einmal testen, ihn aber nicht unbedingt bei jedem weiteren ausgeführten Test aufrufen. + +In diesem Fall können Sie die Abhängigkeit, die diesen Anbieter aufruft, überschreiben und eine benutzerdefinierte Abhängigkeit verwenden, die einen Scheinbenutzer zurückgibt, nur für Ihre Tests. + +### Verwenden Sie das Attribut `app.dependency_overrides`. + +Für diese Fälle verfügt Ihre **FastAPI**-Anwendung über das Attribut `app.dependency_overrides`, bei diesem handelt sich um ein einfaches `dict`. + +Um eine Abhängigkeit für das Testen zu überschreiben, geben Sie als Schlüssel die ursprüngliche Abhängigkeit (eine Funktion) und als Wert Ihre Überschreibung der Abhängigkeit (eine andere Funktion) ein. + +Und dann ruft **FastAPI** diese Überschreibung anstelle der ursprünglichen Abhängigkeit auf. + +=== "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.8+" + + ```Python hl_lines="29-30 33" + {!> ../../../docs_src/dependency_testing/tutorial001_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="24-25 28" + {!> ../../../docs_src/dependency_testing/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="28-29 32" + {!> ../../../docs_src/dependency_testing/tutorial001.py!} + ``` + +!!! tip "Tipp" + Sie können eine Überschreibung für eine Abhängigkeit festlegen, die an einer beliebigen Stelle in Ihrer **FastAPI**-Anwendung verwendet wird. + + Die ursprüngliche Abhängigkeit könnte in einer *Pfadoperation-Funktion*, einem *Pfadoperation-Dekorator* (wenn Sie den Rückgabewert nicht verwenden), einem `.include_router()`-Aufruf, usw. verwendet werden. + + FastAPI kann sie in jedem Fall überschreiben. + +Anschließend können Sie Ihre Überschreibungen zurücksetzen (entfernen), indem Sie `app.dependency_overrides` auf ein leeres `dict` setzen: + +```Python +app.dependency_overrides = {} +``` + +!!! tip "Tipp" + Wenn Sie eine Abhängigkeit nur während einiger Tests überschreiben möchten, können Sie die Überschreibung zu Beginn des Tests (innerhalb der Testfunktion) festlegen und am Ende (am Ende der Testfunktion) zurücksetzen. diff --git a/docs/de/docs/advanced/testing-events.md b/docs/de/docs/advanced/testing-events.md new file mode 100644 index 0000000000000..f500935485474 --- /dev/null +++ b/docs/de/docs/advanced/testing-events.md @@ -0,0 +1,7 @@ +# Events testen: Hochfahren – Herunterfahren + +Wenn Sie in Ihren Tests Ihre Event-Handler (`startup` und `shutdown`) ausführen wollen, können Sie den `TestClient` mit einer `with`-Anweisung verwenden: + +```Python hl_lines="9-12 20-24" +{!../../../docs_src/app_testing/tutorial003.py!} +``` diff --git a/docs/de/docs/advanced/testing-websockets.md b/docs/de/docs/advanced/testing-websockets.md new file mode 100644 index 0000000000000..53de72f155a5f --- /dev/null +++ b/docs/de/docs/advanced/testing-websockets.md @@ -0,0 +1,12 @@ +# WebSockets testen + +Sie können den schon bekannten `TestClient` zum Testen von WebSockets verwenden. + +Dazu verwenden Sie den `TestClient` in einer `with`-Anweisung, eine Verbindung zum WebSocket herstellend: + +```Python hl_lines="27-31" +{!../../../docs_src/app_testing/tutorial002.py!} +``` + +!!! note "Hinweis" + Weitere Informationen finden Sie in der Starlette-Dokumentation zum Testen von WebSockets. diff --git a/docs/de/docs/advanced/using-request-directly.md b/docs/de/docs/advanced/using-request-directly.md new file mode 100644 index 0000000000000..f40f5d4be0169 --- /dev/null +++ b/docs/de/docs/advanced/using-request-directly.md @@ -0,0 +1,52 @@ +# Den Request direkt verwenden + +Bisher haben Sie die Teile des Requests, die Sie benötigen, mithilfe von deren Typen deklariert. + +Daten nehmend von: + +* Dem Pfad als Parameter. +* Headern. +* Cookies. +* usw. + +Und indem Sie das tun, validiert **FastAPI** diese Daten, konvertiert sie und generiert automatisch Dokumentation für Ihre API. + +Es gibt jedoch Situationen, in denen Sie möglicherweise direkt auf das `Request`-Objekt zugreifen müssen. + +## Details zum `Request`-Objekt + +Da **FastAPI** unter der Haube eigentlich **Starlette** ist, mit einer Ebene von mehreren Tools darüber, können Sie Starlette's `Request`-Objekt direkt verwenden, wenn Sie es benötigen. + +Das bedeutet allerdings auch, dass, wenn Sie Daten direkt vom `Request`-Objekt nehmen (z. B. dessen Body lesen), diese von FastAPI nicht validiert, konvertiert oder dokumentiert werden (mit OpenAPI, für die automatische API-Benutzeroberfläche). + +Obwohl jeder andere normal deklarierte Parameter (z. B. der Body, mit einem Pydantic-Modell) dennoch validiert, konvertiert, annotiert, usw. werden würde. + +Es gibt jedoch bestimmte Fälle, in denen es nützlich ist, auf das `Request`-Objekt zuzugreifen. + +## Das `Request`-Objekt direkt verwenden + +Angenommen, Sie möchten auf die IP-Adresse/den Host des Clients in Ihrer *Pfadoperation-Funktion* zugreifen. + +Dazu müssen Sie direkt auf den Request zugreifen. + +```Python hl_lines="1 7-8" +{!../../../docs_src/using_request_directly/tutorial001.py!} +``` + +Durch die Deklaration eines *Pfadoperation-Funktionsparameters*, dessen Typ der `Request` ist, weiß **FastAPI**, dass es den `Request` diesem Parameter übergeben soll. + +!!! tip "Tipp" + Beachten Sie, dass wir in diesem Fall einen Pfad-Parameter zusätzlich zum Request-Parameter deklarieren. + + Der Pfad-Parameter wird also extrahiert, validiert, in den spezifizierten Typ konvertiert und mit OpenAPI annotiert. + + Auf die gleiche Weise können Sie wie gewohnt jeden anderen Parameter deklarieren und zusätzlich auch den `Request` erhalten. + +## `Request`-Dokumentation + +Weitere Details zum `Request`-Objekt finden Sie in der offiziellen Starlette-Dokumentation. + +!!! note "Technische Details" + Sie können auch `from starlette.requests import Request` verwenden. + + **FastAPI** stellt es direkt zur Verfügung, als Komfort für Sie, den Entwickler. Es kommt aber direkt von Starlette. diff --git a/docs/de/docs/advanced/websockets.md b/docs/de/docs/advanced/websockets.md new file mode 100644 index 0000000000000..e5e6a9d01c3eb --- /dev/null +++ b/docs/de/docs/advanced/websockets.md @@ -0,0 +1,224 @@ +# WebSockets + +Sie können WebSockets mit **FastAPI** verwenden. + +## `WebSockets` installieren + +Zuerst müssen Sie `WebSockets` installieren: + +
+ +```console +$ pip install websockets + +---> 100% +``` + +
+ +## WebSockets-Client + +### In Produktion + +In Ihrem Produktionssystem haben Sie wahrscheinlich ein Frontend, das mit einem modernen Framework wie React, Vue.js oder Angular erstellt wurde. + +Und um über WebSockets mit Ihrem Backend zu kommunizieren, würden Sie wahrscheinlich die Werkzeuge Ihres Frontends verwenden. + +Oder Sie verfügen möglicherweise über eine native Mobile-Anwendung, die direkt in nativem Code mit Ihrem WebSocket-Backend kommuniziert. + +Oder Sie haben andere Möglichkeiten, mit dem WebSocket-Endpunkt zu kommunizieren. + +--- + +Für dieses Beispiel verwenden wir jedoch ein sehr einfaches HTML-Dokument mit etwas JavaScript, alles in einem langen String. + +Das ist natürlich nicht optimal und man würde das nicht in der Produktion machen. + +In der Produktion hätten Sie eine der oben genannten Optionen. + +Aber es ist die einfachste Möglichkeit, sich auf die Serverseite von WebSockets zu konzentrieren und ein funktionierendes Beispiel zu haben: + +```Python hl_lines="2 6-38 41-43" +{!../../../docs_src/websockets/tutorial001.py!} +``` + +## Einen `websocket` erstellen + +Erstellen Sie in Ihrer **FastAPI**-Anwendung einen `websocket`: + +```Python hl_lines="1 46-47" +{!../../../docs_src/websockets/tutorial001.py!} +``` + +!!! note "Technische Details" + Sie können auch `from starlette.websockets import WebSocket` verwenden. + + **FastAPI** stellt den gleichen `WebSocket` direkt zur Verfügung, als Annehmlichkeit für Sie, den Entwickler. Er kommt aber direkt von Starlette. + +## Nachrichten erwarten und Nachrichten senden + +In Ihrer WebSocket-Route können Sie Nachrichten `await`en und Nachrichten senden. + +```Python hl_lines="48-52" +{!../../../docs_src/websockets/tutorial001.py!} +``` + +Sie können Binär-, Text- und JSON-Daten empfangen und senden. + +## Es ausprobieren + +Wenn Ihre Datei `main.py` heißt, führen Sie Ihre Anwendung so aus: + +
+ +```console +$ uvicorn main:app --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Öffnen Sie Ihren Browser unter http://127.0.0.1:8000. + +Sie sehen eine einfache Seite wie: + + + +Sie können Nachrichten in das Eingabefeld tippen und absenden: + + + +Und Ihre **FastAPI**-Anwendung mit WebSockets antwortet: + + + +Sie können viele Nachrichten senden (und empfangen): + + + +Und alle verwenden dieselbe WebSocket-Verbindung. + +## Verwendung von `Depends` und anderen + +In WebSocket-Endpunkten können Sie Folgendes aus `fastapi` importieren und verwenden: + +* `Depends` +* `Security` +* `Cookie` +* `Header` +* `Path` +* `Query` + +Diese funktionieren auf die gleiche Weise wie für andere FastAPI-Endpunkte/*Pfadoperationen*: + +=== "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.8+" + + ```Python hl_lines="69-70 83" + {!> ../../../docs_src/websockets/tutorial002_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="66-67 79" + {!> ../../../docs_src/websockets/tutorial002_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="68-69 81" + {!> ../../../docs_src/websockets/tutorial002.py!} + ``` + +!!! info + Da es sich um einen WebSocket handelt, macht es keinen Sinn, eine `HTTPException` auszulösen, stattdessen lösen wir eine `WebSocketException` aus. + + Sie können einen „Closing“-Code verwenden, aus den gültigen Codes, die in der Spezifikation definiert sind. + +### WebSockets mit Abhängigkeiten ausprobieren + +Wenn Ihre Datei `main.py` heißt, führen Sie Ihre Anwendung mit Folgendem aus: + +
+ +```console +$ uvicorn main:app --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Öffnen Sie Ihren Browser unter http://127.0.0.1:8000. + +Dort können Sie einstellen: + +* Die „Item ID“, die im Pfad verwendet wird. +* Das „Token“, das als Query-Parameter verwendet wird. + +!!! tip "Tipp" + Beachten Sie, dass der Query-„Token“ von einer Abhängigkeit verarbeitet wird. + +Damit können Sie den WebSocket verbinden und dann Nachrichten senden und empfangen: + + + +## Verbindungsabbrüche und mehreren Clients handhaben + +Wenn eine WebSocket-Verbindung geschlossen wird, löst `await websocket.receive_text()` eine `WebSocketDisconnect`-Exception aus, die Sie dann wie in folgendem Beispiel abfangen und behandeln können. + +=== "Python 3.9+" + + ```Python hl_lines="79-81" + {!> ../../../docs_src/websockets/tutorial003_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="81-83" + {!> ../../../docs_src/websockets/tutorial003.py!} + ``` + +Zum Ausprobieren: + +* Öffnen Sie die Anwendung mit mehreren Browser-Tabs. +* Schreiben Sie Nachrichten in den Tabs. +* Schließen Sie dann einen der Tabs. + +Das wird die Ausnahme `WebSocketDisconnect` auslösen und alle anderen Clients erhalten eine Nachricht wie: + +``` +Client #1596980209979 left the chat +``` + +!!! tip "Tipp" + Die obige Anwendung ist ein minimales und einfaches Beispiel, das zeigt, wie Nachrichten verarbeitet und an mehrere WebSocket-Verbindungen gesendet werden. + + Beachten Sie jedoch, dass, da alles nur im Speicher in einer einzigen Liste verwaltet wird, es nur funktioniert, während der Prozess ausgeführt wird, und nur mit einem einzelnen Prozess. + + Wenn Sie etwas benötigen, das sich leicht in FastAPI integrieren lässt, aber robuster ist und von Redis, PostgreSQL und anderen unterstützt wird, sehen Sie sich encode/broadcaster an. + +## Mehr Informationen + +Weitere Informationen zu Optionen finden Sie in der Dokumentation von Starlette: + +* Die `WebSocket`-Klasse. +* Klassen-basierte Handhabung von WebSockets. diff --git a/docs/de/docs/advanced/wsgi.md b/docs/de/docs/advanced/wsgi.md new file mode 100644 index 0000000000000..19ff90a9011cb --- /dev/null +++ b/docs/de/docs/advanced/wsgi.md @@ -0,0 +1,37 @@ +# WSGI inkludieren – Flask, Django und andere + +Sie können WSGI-Anwendungen mounten, wie Sie es in [Unteranwendungen – Mounts](sub-applications.md){.internal-link target=_blank}, [Hinter einem Proxy](behind-a-proxy.md){.internal-link target=_blank} gesehen haben. + +Dazu können Sie die `WSGIMiddleware` verwenden und damit Ihre WSGI-Anwendung wrappen, zum Beispiel Flask, Django usw. + +## `WSGIMiddleware` verwenden + +Sie müssen `WSGIMiddleware` importieren. + +Wrappen Sie dann die WSGI-Anwendung (z. B. Flask) mit der Middleware. + +Und dann mounten Sie das auf einem Pfad. + +```Python hl_lines="2-3 23" +{!../../../docs_src/wsgi/tutorial001.py!} +``` + +## Es ansehen + +Jetzt wird jede Anfrage unter dem Pfad `/v1/` von der Flask-Anwendung verarbeitet. + +Und der Rest wird von **FastAPI** gehandhabt. + +Wenn Sie das mit Uvicorn ausführen und auf http://localhost:8000/v1/ gehen, sehen Sie die Response von Flask: + +```txt +Hello, World from Flask! +``` + +Und wenn Sie auf http://localhost:8000/v2 gehen, sehen Sie die Response von FastAPI: + +```JSON +{ + "message": "Hello World" +} +``` diff --git a/docs/de/docs/alternatives.md b/docs/de/docs/alternatives.md new file mode 100644 index 0000000000000..ea624ff3a3061 --- /dev/null +++ b/docs/de/docs/alternatives.md @@ -0,0 +1,414 @@ +# Alternativen, Inspiration und Vergleiche + +Was hat **FastAPI** inspiriert, ein Vergleich zu Alternativen, und was FastAPI von diesen gelernt hat. + +## Einführung + +**FastAPI** würde ohne die frühere Arbeit anderer nicht existieren. + +Es wurden zuvor viele Tools entwickelt, die als Inspiration für seine Entwicklung dienten. + +Ich habe die Schaffung eines neuen Frameworks viele Jahre lang vermieden. Zuerst habe ich versucht, alle von **FastAPI** abgedeckten Funktionen mithilfe vieler verschiedener Frameworks, Plugins und Tools zu lösen. + +Aber irgendwann gab es keine andere Möglichkeit, als etwas zu schaffen, das all diese Funktionen bereitstellte, die besten Ideen früherer Tools aufnahm und diese auf die bestmögliche Weise kombinierte, wobei Sprachfunktionen verwendet wurden, die vorher noch nicht einmal verfügbar waren (Python 3.6+ Typhinweise). + +## Vorherige Tools + +### Django + +Es ist das beliebteste Python-Framework und genießt großes Vertrauen. Es wird zum Aufbau von Systemen wie Instagram verwendet. + +Ist relativ eng mit relationalen Datenbanken (wie MySQL oder PostgreSQL) gekoppelt, daher ist es nicht sehr einfach, eine NoSQL-Datenbank (wie Couchbase, MongoDB, Cassandra, usw.) als Hauptspeicherengine zu verwenden. + +Es wurde erstellt, um den HTML-Code im Backend zu generieren, nicht um APIs zu erstellen, die von einem modernen Frontend (wie React, Vue.js und Angular) oder von anderen Systemen (wie IoT-Geräten) verwendet werden, um mit ihm zu kommunizieren. + +### Django REST Framework + +Das Django REST Framework wurde als flexibles Toolkit zum Erstellen von Web-APIs unter Verwendung von Django entwickelt, um dessen API-Möglichkeiten zu verbessern. + +Es wird von vielen Unternehmen verwendet, darunter Mozilla, Red Hat und Eventbrite. + +Es war eines der ersten Beispiele für **automatische API-Dokumentation**, und dies war insbesondere eine der ersten Ideen, welche „die Suche nach“ **FastAPI** inspirierten. + +!!! note "Hinweis" + Das Django REST Framework wurde von Tom Christie erstellt. Derselbe Schöpfer von Starlette und Uvicorn, auf denen **FastAPI** basiert. + + +!!! check "Inspirierte **FastAPI**" + Eine automatische API-Dokumentationsoberfläche zu haben. + +### Flask + +Flask ist ein „Mikroframework“, es enthält weder Datenbankintegration noch viele der Dinge, die standardmäßig in Django enthalten sind. + +Diese Einfachheit und Flexibilität ermöglichen beispielsweise die Verwendung von NoSQL-Datenbanken als Hauptdatenspeichersystem. + +Da es sehr einfach ist, ist es relativ intuitiv zu erlernen, obwohl die Dokumentation an einigen Stellen etwas technisch wird. + +Es wird auch häufig für andere Anwendungen verwendet, die nicht unbedingt eine Datenbank, Benutzerverwaltung oder eine der vielen in Django enthaltenen Funktionen benötigen. Obwohl viele dieser Funktionen mit Plugins hinzugefügt werden können. + +Diese Entkopplung der Teile und die Tatsache, dass es sich um ein „Mikroframework“ handelt, welches so erweitert werden kann, dass es genau das abdeckt, was benötigt wird, war ein Schlüsselmerkmal, das ich beibehalten wollte. + +Angesichts der Einfachheit von Flask schien es eine gute Ergänzung zum Erstellen von APIs zu sein. Als Nächstes musste ein „Django REST Framework“ für Flask gefunden werden. + +!!! check "Inspirierte **FastAPI**" + Ein Mikroframework zu sein. Es einfach zu machen, die benötigten Tools und Teile zu kombinieren. + + Über ein einfaches und benutzerfreundliches Routingsystem zu verfügen. + + +### Requests + +**FastAPI** ist eigentlich keine Alternative zu **Requests**. Der Umfang der beiden ist sehr unterschiedlich. + +Es wäre tatsächlich üblich, Requests *innerhalb* einer FastAPI-Anwendung zu verwenden. + +Dennoch erhielt FastAPI von Requests einiges an Inspiration. + +**Requests** ist eine Bibliothek zur *Interaktion* mit APIs (als Client), während **FastAPI** eine Bibliothek zum *Erstellen* von APIs (als Server) ist. + +Die beiden stehen mehr oder weniger an entgegengesetzten Enden und ergänzen sich. + +Requests hat ein sehr einfaches und intuitives Design, ist sehr einfach zu bedienen und verfügt über sinnvolle Standardeinstellungen. Aber gleichzeitig ist es sehr leistungsstark und anpassbar. + +Aus diesem Grund heißt es auf der offiziellen Website: + +> Requests ist eines der am häufigsten heruntergeladenen Python-Packages aller Zeiten + +Die Art und Weise, wie Sie es verwenden, ist sehr einfach. Um beispielsweise einen `GET`-Request zu machen, würden Sie schreiben: + +```Python +response = requests.get("http://example.com/some/url") +``` + +Die entsprechende *Pfadoperation* der FastAPI-API könnte wie folgt aussehen: + +```Python hl_lines="1" +@app.get("/some/url") +def read_url(): + return {"message": "Hello World"} +``` + +Sehen Sie sich die Ähnlichkeiten in `requests.get(...)` und `@app.get(...)` an. + +!!! check "Inspirierte **FastAPI**" + * Über eine einfache und intuitive API zu verfügen. + * HTTP-Methodennamen (Operationen) direkt, auf einfache und intuitive Weise zu verwenden. + * Vernünftige Standardeinstellungen zu haben, aber auch mächtige Einstellungsmöglichkeiten. + + +### Swagger / OpenAPI + +Die Hauptfunktion, die ich vom Django REST Framework haben wollte, war die automatische API-Dokumentation. + +Dann fand ich heraus, dass es einen Standard namens Swagger gab, zur Dokumentation von APIs unter Verwendung von JSON (oder YAML, einer Erweiterung von JSON). + +Und es gab bereits eine Web-Oberfläche für Swagger-APIs. Die Möglichkeit, Swagger-Dokumentation für eine API zu generieren, würde die automatische Nutzung dieser Web-Oberfläche ermöglichen. + +Irgendwann wurde Swagger an die Linux Foundation übergeben und in OpenAPI umbenannt. + +Aus diesem Grund spricht man bei Version 2.0 häufig von „Swagger“ und ab Version 3 von „OpenAPI“. + +!!! check "Inspirierte **FastAPI**" + Einen offenen Standard für API-Spezifikationen zu übernehmen und zu verwenden, anstelle eines benutzerdefinierten Schemas. + + Und Standard-basierte Tools für die Oberfläche zu integrieren: + + * Swagger UI + * ReDoc + + Diese beiden wurden ausgewählt, weil sie ziemlich beliebt und stabil sind, aber bei einer schnellen Suche könnten Sie Dutzende alternativer Benutzeroberflächen für OpenAPI finden (welche Sie mit **FastAPI** verwenden können). + +### Flask REST Frameworks + +Es gibt mehrere Flask REST Frameworks, aber nachdem ich die Zeit und Arbeit investiert habe, sie zu untersuchen, habe ich festgestellt, dass viele nicht mehr unterstützt werden oder abgebrochen wurden und dass mehrere fortbestehende Probleme sie unpassend machten. + +### Marshmallow + +Eine der von API-Systemen benötigen Hauptfunktionen ist die Daten-„Serialisierung“, welche Daten aus dem Code (Python) entnimmt und in etwas umwandelt, was durch das Netzwerk gesendet werden kann. Beispielsweise das Konvertieren eines Objekts, welches Daten aus einer Datenbank enthält, in ein JSON-Objekt. Konvertieren von `datetime`-Objekten in Strings, usw. + +Eine weitere wichtige Funktion, benötigt von APIs, ist die Datenvalidierung, welche sicherstellt, dass die Daten unter gegebenen Umständen gültig sind. Zum Beispiel, dass ein Feld ein `int` ist und kein zufälliger String. Das ist besonders nützlich für hereinkommende Daten. + +Ohne ein Datenvalidierungssystem müssten Sie alle Prüfungen manuell im Code durchführen. + +Für diese Funktionen wurde Marshmallow entwickelt. Es ist eine großartige Bibliothek und ich habe sie schon oft genutzt. + +Aber sie wurde erstellt, bevor Typhinweise in Python existierten. Um also ein Schema zu definieren, müssen Sie bestimmte Werkzeuge und Klassen verwenden, die von Marshmallow bereitgestellt werden. + +!!! check "Inspirierte **FastAPI**" + Code zu verwenden, um „Schemas“ zu definieren, welche Datentypen und Validierung automatisch bereitstellen. + +### Webargs + +Eine weitere wichtige Funktion, die von APIs benötigt wird, ist das Parsen von Daten aus eingehenden Requests. + +Webargs wurde entwickelt, um dieses für mehrere Frameworks, einschließlich Flask, bereitzustellen. + +Es verwendet unter der Haube Marshmallow, um die Datenvalidierung durchzuführen. Und es wurde von denselben Entwicklern erstellt. + +Es ist ein großartiges Tool und ich habe es auch oft verwendet, bevor ich **FastAPI** hatte. + +!!! info + Webargs wurde von denselben Marshmallow-Entwicklern erstellt. + +!!! check "Inspirierte **FastAPI**" + Eingehende Requestdaten automatisch zu validieren. + +### APISpec + +Marshmallow und Webargs bieten Validierung, Parsen und Serialisierung als Plugins. + +Es fehlt jedoch noch die Dokumentation. Dann wurde APISpec erstellt. + +Es ist ein Plugin für viele Frameworks (und es gibt auch ein Plugin für Starlette). + +Die Funktionsweise besteht darin, dass Sie die Definition des Schemas im YAML-Format im Docstring jeder Funktion schreiben, die eine Route verarbeitet. + +Und es generiert OpenAPI-Schemas. + +So funktioniert es in Flask, Starlette, Responder, usw. + +Aber dann haben wir wieder das Problem einer Mikrosyntax innerhalb eines Python-Strings (eines großen YAML). + +Der Texteditor kann dabei nicht viel helfen. Und wenn wir Parameter oder Marshmallow-Schemas ändern und vergessen, auch den YAML-Docstring zu ändern, wäre das generierte Schema veraltet. + +!!! info + APISpec wurde von denselben Marshmallow-Entwicklern erstellt. + + +!!! check "Inspirierte **FastAPI**" + Den offenen Standard für APIs, OpenAPI, zu unterstützen. + +### Flask-apispec + +Hierbei handelt es sich um ein Flask-Plugin, welches Webargs, Marshmallow und APISpec miteinander verbindet. + +Es nutzt die Informationen von Webargs und Marshmallow, um mithilfe von APISpec automatisch OpenAPI-Schemas zu generieren. + +Ein großartiges Tool, sehr unterbewertet. Es sollte weitaus populärer als viele andere Flask-Plugins sein. Möglicherweise liegt es daran, dass die Dokumentation zu kompakt und abstrakt ist. + +Das löste das Problem, YAML (eine andere Syntax) in Python-Docstrings schreiben zu müssen. + +Diese Kombination aus Flask, Flask-apispec mit Marshmallow und Webargs war bis zur Entwicklung von **FastAPI** mein Lieblings-Backend-Stack. + +Die Verwendung führte zur Entwicklung mehrerer Flask-Full-Stack-Generatoren. Dies sind die Hauptstacks, die ich (und mehrere externe Teams) bisher verwendet haben: + +* https://github.com/tiangolo/full-stack +* https://github.com/tiangolo/full-stack-flask-couchbase +* https://github.com/tiangolo/full-stack-flask-couchdb + +Und dieselben Full-Stack-Generatoren bildeten die Basis der [**FastAPI**-Projektgeneratoren](project-generation.md){.internal-link target=_blank}. + +!!! info + Flask-apispec wurde von denselben Marshmallow-Entwicklern erstellt. + +!!! check "Inspirierte **FastAPI**" + Das OpenAPI-Schema automatisch zu generieren, aus demselben Code, welcher die Serialisierung und Validierung definiert. + +### NestJS (und Angular) + +Dies ist nicht einmal Python, NestJS ist ein von Angular inspiriertes JavaScript (TypeScript) NodeJS Framework. + +Es erreicht etwas Ähnliches wie Flask-apispec. + +Es verfügt über ein integriertes Dependency Injection System, welches von Angular 2 inspiriert ist. Erfordert ein Vorab-Registrieren der „Injectables“ (wie alle anderen Dependency Injection Systeme, welche ich kenne), sodass der Code ausschweifender wird und es mehr Codeverdoppelung gibt. + +Da die Parameter mit TypeScript-Typen beschrieben werden (ähnlich den Python-Typhinweisen), ist die Editorunterstützung ziemlich gut. + +Da TypeScript-Daten jedoch nach der Kompilierung nach JavaScript nicht erhalten bleiben, können die Typen nicht gleichzeitig die Validierung, Serialisierung und Dokumentation definieren. Aus diesem Grund und aufgrund einiger Designentscheidungen ist es für die Validierung, Serialisierung und automatische Schemagenerierung erforderlich, an vielen Stellen Dekoratoren hinzuzufügen. Es wird also ziemlich ausführlich. + +Es kann nicht sehr gut mit verschachtelten Modellen umgehen. Wenn es sich beim JSON-Body in der Anfrage also um ein JSON-Objekt mit inneren Feldern handelt, die wiederum verschachtelte JSON-Objekte sind, kann er nicht richtig dokumentiert und validiert werden. + +!!! check "Inspirierte **FastAPI**" + Python-Typen zu verwenden, um eine hervorragende Editorunterstützung zu erhalten. + + Über ein leistungsstarkes Dependency Injection System zu verfügen. Eine Möglichkeit zu finden, Codeverdoppelung zu minimieren. + +### Sanic + +Es war eines der ersten extrem schnellen Python-Frameworks, welches auf `asyncio` basierte. Es wurde so gestaltet, dass es Flask sehr ähnlich ist. + +!!! note "Technische Details" + Es verwendete `uvloop` anstelle der standardmäßigen Python-`asyncio`-Schleife. Das hat es so schnell gemacht. + + Hat eindeutig Uvicorn und Starlette inspiriert, welche derzeit in offenen Benchmarks schneller als Sanic sind. + +!!! check "Inspirierte **FastAPI**" + Einen Weg zu finden, eine hervorragende Performanz zu haben. + + Aus diesem Grund basiert **FastAPI** auf Starlette, da dieses das schnellste verfügbare Framework ist (getestet in Benchmarks von Dritten). + +### Falcon + +Falcon ist ein weiteres leistungsstarkes Python-Framework. Es ist minimalistisch konzipiert und dient als Grundlage für andere Frameworks wie Hug. + +Es ist so konzipiert, dass es über Funktionen verfügt, welche zwei Parameter empfangen, einen „Request“ und eine „Response“. Dann „lesen“ Sie Teile des Requests und „schreiben“ Teile der Response. Aufgrund dieses Designs ist es nicht möglich, Request-Parameter und -Bodys mit Standard-Python-Typhinweisen als Funktionsparameter zu deklarieren. + +Daher müssen Datenvalidierung, Serialisierung und Dokumentation im Code und nicht automatisch erfolgen. Oder sie müssen als Framework oberhalb von Falcon implementiert werden, so wie Hug. Dieselbe Unterscheidung findet auch in anderen Frameworks statt, die vom Design von Falcon inspiriert sind und ein Requestobjekt und ein Responseobjekt als Parameter haben. + +!!! check "Inspirierte **FastAPI**" + Wege zu finden, eine großartige Performanz zu erzielen. + + Zusammen mit Hug (da Hug auf Falcon basiert), einen `response`-Parameter in Funktionen zu deklarieren. + + Obwohl er in FastAPI optional ist und hauptsächlich zum Festlegen von Headern, Cookies und alternativen Statuscodes verwendet wird. + +### Molten + +Ich habe Molten in den ersten Phasen der Entwicklung von **FastAPI** entdeckt. Und es hat ganz ähnliche Ideen: + +* Basierend auf Python-Typhinweisen. +* Validierung und Dokumentation aus diesen Typen. +* Dependency Injection System. + +Es verwendet keine Datenvalidierungs-, Serialisierungs- und Dokumentationsbibliothek eines Dritten wie Pydantic, sondern verfügt über eine eigene. Daher wären diese Datentyp-Definitionen nicht so einfach wiederverwendbar. + +Es erfordert eine etwas ausführlichere Konfiguration. Und da es auf WSGI (anstelle von ASGI) basiert, ist es nicht darauf ausgelegt, die hohe Leistung von Tools wie Uvicorn, Starlette und Sanic zu nutzen. + +Das Dependency Injection System erfordert eine Vorab-Registrierung der Abhängigkeiten und die Abhängigkeiten werden basierend auf den deklarierten Typen aufgelöst. Daher ist es nicht möglich, mehr als eine „Komponente“ zu deklarieren, welche einen bestimmten Typ bereitstellt. + +Routen werden an einer einzigen Stelle deklariert, indem Funktionen verwendet werden, die an anderen Stellen deklariert wurden (anstatt Dekoratoren zu verwenden, welche direkt über der Funktion platziert werden können, welche den Endpunkt verarbeitet). Dies ähnelt eher der Vorgehensweise von Django als der Vorgehensweise von Flask (und Starlette). Es trennt im Code Dinge, die relativ eng miteinander gekoppelt sind. + +!!! check "Inspirierte **FastAPI**" + Zusätzliche Validierungen für Datentypen zu definieren, mithilfe des „Default“-Werts von Modellattributen. Dies verbessert die Editorunterstützung und war zuvor in Pydantic nicht verfügbar. + + Das hat tatsächlich dazu geführt, dass Teile von Pydantic aktualisiert wurden, um denselben Validierungsdeklarationsstil zu unterstützen (diese gesamte Funktionalität ist jetzt bereits in Pydantic verfügbar). + +### Hug + +Hug war eines der ersten Frameworks, welches die Deklaration von API-Parametertypen mithilfe von Python-Typhinweisen implementierte. Das war eine großartige Idee, die andere Tools dazu inspirierte, dasselbe zu tun. + +Es verwendete benutzerdefinierte Typen in seinen Deklarationen anstelle von Standard-Python-Typen, es war aber dennoch ein großer Fortschritt. + +Außerdem war es eines der ersten Frameworks, welches ein benutzerdefiniertes Schema generierte, welches die gesamte API in JSON deklarierte. + +Es basierte nicht auf einem Standard wie OpenAPI und JSON Schema. Daher wäre es nicht einfach, es in andere Tools wie Swagger UI zu integrieren. Aber, nochmal, es war eine sehr innovative Idee. + +Es verfügt über eine interessante, ungewöhnliche Funktion: Mit demselben Framework ist es möglich, APIs und auch CLIs zu erstellen. + +Da es auf dem bisherigen Standard für synchrone Python-Webframeworks (WSGI) basiert, kann es nicht mit Websockets und anderen Dingen umgehen, verfügt aber dennoch über eine hohe Performanz. + +!!! info + Hug wurde von Timothy Crosley erstellt, dem gleichen Schöpfer von `isort`, einem großartigen Tool zum automatischen Sortieren von Importen in Python-Dateien. + +!!! check "Ideen, die **FastAPI** inspiriert haben" + Hug inspirierte Teile von APIStar und war eines der Tools, die ich am vielversprechendsten fand, neben APIStar. + + Hug hat dazu beigetragen, **FastAPI** dazu zu inspirieren, Python-Typhinweise zum Deklarieren von Parametern zu verwenden und ein Schema zu generieren, das die API automatisch definiert. + + Hug inspirierte **FastAPI** dazu, einen `response`-Parameter in Funktionen zu deklarieren, um Header und Cookies zu setzen. + +### APIStar (≦ 0.5) + +Kurz bevor ich mich entschied, **FastAPI** zu erstellen, fand ich den **APIStar**-Server. Er hatte fast alles, was ich suchte, und ein tolles Design. + +Er war eine der ersten Implementierungen eines Frameworks, die ich je gesehen hatte (vor NestJS und Molten), welches Python-Typhinweise zur Deklaration von Parametern und Requests verwendeten. Ich habe ihn mehr oder weniger zeitgleich mit Hug gefunden. Aber APIStar nutzte den OpenAPI-Standard. + +Er verfügte an mehreren Stellen über automatische Datenvalidierung, Datenserialisierung und OpenAPI-Schemagenerierung, basierend auf denselben Typhinweisen. + +Body-Schemadefinitionen verwendeten nicht die gleichen Python-Typhinweise wie Pydantic, er war Marshmallow etwas ähnlicher, sodass die Editorunterstützung nicht so gut war, aber dennoch war APIStar die beste verfügbare Option. + +Er hatte zu dieser Zeit die besten Leistungsbenchmarks (nur übertroffen von Starlette). + +Anfangs gab es keine Web-Oberfläche für die automatische API-Dokumentation, aber ich wusste, dass ich Swagger UI hinzufügen konnte. + +Er verfügte über ein Dependency Injection System. Es erforderte eine Vorab-Registrierung der Komponenten, wie auch bei anderen oben besprochenen Tools. Aber dennoch, es war ein tolles Feature. + +Ich konnte ihn nie in einem vollständigen Projekt verwenden, da er keine Sicherheitsintegration hatte, sodass ich nicht alle Funktionen, die ich hatte, durch die auf Flask-apispec basierenden Full-Stack-Generatoren ersetzen konnte. Ich hatte in meinem Projekte-Backlog den Eintrag, einen Pull Request zu erstellen, welcher diese Funktionalität hinzufügte. + +Doch dann verlagerte sich der Schwerpunkt des Projekts. + +Es handelte sich nicht länger um ein API-Webframework, da sich der Entwickler auf Starlette konzentrieren musste. + +Jetzt handelt es sich bei APIStar um eine Reihe von Tools zur Validierung von OpenAPI-Spezifikationen, nicht um ein Webframework. + +!!! info + APIStar wurde von Tom Christie erstellt. Derselbe, welcher Folgendes erstellt hat: + + * Django REST Framework + * Starlette (auf welchem **FastAPI** basiert) + * Uvicorn (verwendet von Starlette und **FastAPI**) + +!!! check "Inspirierte **FastAPI**" + Zu existieren. + + Die Idee, mehrere Dinge (Datenvalidierung, Serialisierung und Dokumentation) mit denselben Python-Typen zu deklarieren, welche gleichzeitig eine hervorragende Editorunterstützung bieten, hielt ich für eine brillante Idee. + + Und nach einer langen Suche nach einem ähnlichen Framework und dem Testen vieler verschiedener Alternativen, war APIStar die beste verfügbare Option. + + Dann hörte APIStar auf, als Server zu existieren, und Starlette wurde geschaffen, welches eine neue, bessere Grundlage für ein solches System bildete. Das war die finale Inspiration für die Entwicklung von **FastAPI**. + + Ich betrachte **FastAPI** als einen „spirituellen Nachfolger“ von APIStar, welcher die Funktionen, das Typsystem und andere Teile verbessert und erweitert, basierend auf den Erkenntnissen aus all diesen früheren Tools. + +## Verwendet von **FastAPI** + +### Pydantic + +Pydantic ist eine Bibliothek zum Definieren von Datenvalidierung, Serialisierung und Dokumentation (unter Verwendung von JSON Schema) basierend auf Python-Typhinweisen. + +Das macht es äußerst intuitiv. + +Es ist vergleichbar mit Marshmallow. Obwohl es in Benchmarks schneller als Marshmallow ist. Und da es auf den gleichen Python-Typhinweisen basiert, ist die Editorunterstützung großartig. + +!!! check "**FastAPI** verwendet es, um" + Die gesamte Datenvalidierung, Datenserialisierung und automatische Modelldokumentation (basierend auf JSON Schema) zu erledigen. + + **FastAPI** nimmt dann, abgesehen von all den anderen Dingen, die es tut, dieses JSON-Schema und fügt es in OpenAPI ein. + +### Starlette + +Starlette ist ein leichtgewichtiges ASGI-Framework/Toolkit, welches sich ideal für die Erstellung hochperformanter asynchroner Dienste eignet. + +Es ist sehr einfach und intuitiv. Es ist so konzipiert, dass es leicht erweiterbar ist und über modulare Komponenten verfügt. + +Es bietet: + +* Eine sehr beeindruckende Leistung. +* WebSocket-Unterstützung. +* Hintergrundtasks im selben Prozess. +* Events für das Hoch- und Herunterfahren. +* Testclient basierend auf HTTPX. +* CORS, GZip, statische Dateien, Streamende Responses. +* Session- und Cookie-Unterstützung. +* 100 % Testabdeckung. +* 100 % Typannotierte Codebasis. +* Wenige starke Abhängigkeiten. + +Starlette ist derzeit das schnellste getestete Python-Framework. Nur übertroffen von Uvicorn, welches kein Framework, sondern ein Server ist. + +Starlette bietet alle grundlegenden Funktionen eines Web-Microframeworks. + +Es bietet jedoch keine automatische Datenvalidierung, Serialisierung oder Dokumentation. + +Das ist eines der wichtigsten Dinge, welche **FastAPI** hinzufügt, alles basierend auf Python-Typhinweisen (mit Pydantic). Das, plus, das Dependency Injection System, Sicherheitswerkzeuge, OpenAPI-Schemagenerierung, usw. + +!!! note "Technische Details" + ASGI ist ein neuer „Standard“, welcher von Mitgliedern des Django-Kernteams entwickelt wird. Es handelt sich immer noch nicht um einen „Python-Standard“ (ein PEP), obwohl sie gerade dabei sind, das zu tun. + + Dennoch wird es bereits von mehreren Tools als „Standard“ verwendet. Das verbessert die Interoperabilität erheblich, da Sie Uvicorn mit jeden anderen ASGI-Server (wie Daphne oder Hypercorn) tauschen oder ASGI-kompatible Tools wie `python-socketio` hinzufügen können. + +!!! check "**FastAPI** verwendet es, um" + Alle Kern-Webaspekte zu handhaben. Und fügt Funktionen obenauf. + + Die Klasse `FastAPI` selbst erbt direkt von der Klasse `Starlette`. + + Alles, was Sie also mit Starlette machen können, können Sie direkt mit **FastAPI** machen, da es sich im Grunde um Starlette auf Steroiden handelt. + +### Uvicorn + +Uvicorn ist ein blitzschneller ASGI-Server, der auf uvloop und httptools basiert. + +Es handelt sich nicht um ein Webframework, sondern um einen Server. Beispielsweise werden keine Tools für das Routing von Pfaden bereitgestellt. Das ist etwas, was ein Framework wie Starlette (oder **FastAPI**) zusätzlich bieten würde. + +Es ist der empfohlene Server für Starlette und **FastAPI**. + +!!! check "**FastAPI** empfiehlt es als" + Hauptwebserver zum Ausführen von **FastAPI**-Anwendungen. + + Sie können ihn mit Gunicorn kombinieren, um einen asynchronen Multiprozess-Server zu erhalten. + + Weitere Details finden Sie im Abschnitt [Deployment](deployment/index.md){.internal-link target=_blank}. + +## Benchmarks und Geschwindigkeit + +Um den Unterschied zwischen Uvicorn, Starlette und FastAPI zu verstehen, zu vergleichen und zu sehen, lesen Sie den Abschnitt über [Benchmarks](benchmarks.md){.internal-link target=_blank}. diff --git a/docs/de/docs/async.md b/docs/de/docs/async.md new file mode 100644 index 0000000000000..c2a43ac668a9c --- /dev/null +++ b/docs/de/docs/async.md @@ -0,0 +1,430 @@ +# Nebenläufigkeit und async / await + +Details zur `async def`-Syntax für *Pfadoperation-Funktionen* und Hintergrundinformationen zu asynchronem Code, Nebenläufigkeit und Parallelität. + +## In Eile? + +TL;DR: + +Wenn Sie Bibliotheken von Dritten verwenden, die mit `await` aufgerufen werden müssen, wie zum Beispiel: + +```Python +results = await some_library() +``` + +Dann deklarieren Sie Ihre *Pfadoperation-Funktionen* mit `async def` wie in: + +```Python hl_lines="2" +@app.get('/') +async def read_results(): + results = await some_library() + return results +``` + +!!! note + Sie können `await` nur innerhalb von Funktionen verwenden, die mit `async def` erstellt wurden. + +--- + +Wenn Sie eine Bibliothek eines Dritten verwenden, die mit etwas kommuniziert (einer Datenbank, einer API, dem Dateisystem, usw.) und welche die Verwendung von `await` nicht unterstützt (dies ist derzeit bei den meisten Datenbankbibliotheken der Fall), dann deklarieren Sie Ihre *Pfadoperation-Funktionen* ganz normal nur mit `def`, etwa: + +```Python hl_lines="2" +@app.get('/') +def results(): + results = some_library() + return results +``` + +--- + +Wenn Ihre Anwendung (irgendwie) mit nichts anderem kommunizieren und auf dessen Antwort warten muss, verwenden Sie `async def`. + +--- + +Wenn Sie sich unsicher sind, verwenden Sie einfach `def`. + +--- + +**Hinweis**: Sie können `def` und `async def` in Ihren *Pfadoperation-Funktionen* beliebig mischen, so wie Sie es benötigen, und jede einzelne Funktion in der für Sie besten Variante erstellen. FastAPI wird damit das Richtige tun. + +Wie dem auch sei, in jedem der oben genannten Fälle wird FastAPI immer noch asynchron arbeiten und extrem schnell sein. + +Wenn Sie jedoch den oben genannten Schritten folgen, können einige Performance-Optimierungen vorgenommen werden. + +## Technische Details + +Moderne Versionen von Python unterstützen **„asynchronen Code“** unter Verwendung sogenannter **„Coroutinen“** mithilfe der Syntax **`async`** und **`await`**. + +Nehmen wir obigen Satz in den folgenden Abschnitten Schritt für Schritt unter die Lupe: + +* **Asynchroner Code** +* **`async` und `await`** +* **Coroutinen** + +## Asynchroner Code + +Asynchroner Code bedeutet lediglich, dass die Sprache 💬 eine Möglichkeit hat, dem Computersystem / Programm 🤖 mitzuteilen, dass es 🤖 an einem bestimmten Punkt im Code darauf warten muss, dass *etwas anderes* irgendwo anders fertig wird. Nehmen wir an, *etwas anderes* ist hier „Langsam-Datei“ 📝. + +Während der Zeit, die „Langsam-Datei“ 📝 benötigt, kann das System also andere Aufgaben erledigen. + +Dann kommt das System / Programm 🤖 bei jeder Gelegenheit zurück, wenn es entweder wieder wartet, oder wann immer es 🤖 die ganze Arbeit erledigt hat, die zu diesem Zeitpunkt zu tun war. Und es 🤖 wird nachschauen, ob eine der Aufgaben, auf die es gewartet hat, fertig damit ist, zu tun, was sie tun sollte. + +Dann nimmt es 🤖 die erste erledigte Aufgabe (sagen wir, unsere „Langsam-Datei“ 📝) und bearbeitet sie weiter. + +Das „Warten auf etwas anderes“ bezieht sich normalerweise auf I/O-Operationen, die relativ „langsam“ sind (im Vergleich zur Geschwindigkeit des Prozessors und des Arbeitsspeichers), wie etwa das Warten darauf, dass: + +* die Daten des Clients über das Netzwerk empfangen wurden +* die von Ihrem Programm gesendeten Daten vom Client über das Netzwerk empfangen wurden +* der Inhalt einer Datei vom System von der Festplatte gelesen und an Ihr Programm übergeben wurde +* der Inhalt, den Ihr Programm dem System übergeben hat, auf die Festplatte geschrieben wurde +* eine Remote-API-Operation beendet wurde +* Eine Datenbankoperation abgeschlossen wurde +* eine Datenbankabfrage die Ergebnisse zurückgegeben hat +* usw. + +Da die Ausführungszeit hier hauptsächlich durch das Warten auf I/O-Operationen verbraucht wird, nennt man dies auch „I/O-lastige“ („I/O bound“) Operationen. + +„Asynchron“, sagt man, weil das Computersystem / Programm nicht mit einer langsamen Aufgabe „synchronisiert“ werden muss und nicht auf den genauen Moment warten muss, in dem die Aufgabe beendet ist, ohne dabei etwas zu tun, um schließlich das Ergebnis der Aufgabe zu übernehmen und die Arbeit fortsetzen zu können. + +Da es sich stattdessen um ein „asynchrones“ System handelt, kann die Aufgabe nach Abschluss ein wenig (einige Mikrosekunden) in der Schlange warten, bis das System / Programm seine anderen Dinge erledigt hat und zurückkommt, um die Ergebnisse entgegenzunehmen und mit ihnen weiterzuarbeiten. + +Für „synchron“ (im Gegensatz zu „asynchron“) wird auch oft der Begriff „sequentiell“ verwendet, da das System / Programm alle Schritte in einer Sequenz („der Reihe nach“) ausführt, bevor es zu einer anderen Aufgabe wechselt, auch wenn diese Schritte mit Warten verbunden sind. + +### Nebenläufigkeit und Hamburger + +Diese oben beschriebene Idee von **asynchronem** Code wird manchmal auch **„Nebenläufigkeit“** genannt. Sie unterscheidet sich von **„Parallelität“**. + +**Nebenläufigkeit** und **Parallelität** beziehen sich beide auf „verschiedene Dinge, die mehr oder weniger gleichzeitig passieren“. + +Aber die Details zwischen *Nebenläufigkeit* und *Parallelität* sind ziemlich unterschiedlich. + +Um den Unterschied zu erkennen, stellen Sie sich die folgende Geschichte über Hamburger vor: + +### Nebenläufige Hamburger + +Sie gehen mit Ihrem Schwarm Fastfood holen, stehen in der Schlange, während der Kassierer die Bestellungen der Leute vor Ihnen entgegennimmt. 😍 + + + +Dann sind Sie an der Reihe und Sie bestellen zwei sehr schmackhafte Burger für Ihren Schwarm und Sie. 🍔🍔 + + + +Der Kassierer sagt etwas zum Koch in der Küche, damit dieser weiß, dass er Ihre Burger zubereiten muss (obwohl er gerade die für die vorherigen Kunden zubereitet). + + + +Sie bezahlen. 💸 + +Der Kassierer gibt Ihnen die Nummer Ihrer Bestellung. + + + +Während Sie warten, suchen Sie sich mit Ihrem Schwarm einen Tisch aus, Sie sitzen da und reden lange mit Ihrem Schwarm (da Ihre Burger sehr aufwändig sind und die Zubereitung einige Zeit dauert). + +Während Sie mit Ihrem Schwarm am Tisch sitzen und auf die Burger warten, können Sie die Zeit damit verbringen, zu bewundern, wie großartig, süß und klug Ihr Schwarm ist ✨😍✨. + + + +Während Sie warten und mit Ihrem Schwarm sprechen, überprüfen Sie von Zeit zu Zeit die auf dem Zähler angezeigte Nummer, um zu sehen, ob Sie bereits an der Reihe sind. + +Dann, irgendwann, sind Sie endlich an der Reihe. Sie gehen zur Theke, holen sich die Burger und kommen zurück an den Tisch. + + + +Sie und Ihr Schwarm essen die Burger und haben eine schöne Zeit. ✨ + + + +!!! info + Die wunderschönen Illustrationen stammen von Ketrina Thompson. 🎨 + +--- + +Stellen Sie sich vor, Sie wären das Computersystem / Programm 🤖 in dieser Geschichte. + +Während Sie an der Schlange stehen, sind Sie einfach untätig 😴, warten darauf, dass Sie an die Reihe kommen, und tun nichts sehr „Produktives“. Aber die Schlange ist schnell abgearbeitet, weil der Kassierer nur die Bestellungen entgegennimmt (und nicht zubereitet), also ist das vertretbar. + +Wenn Sie dann an der Reihe sind, erledigen Sie tatsächliche „produktive“ Arbeit, Sie gehen das Menü durch, entscheiden sich, was Sie möchten, bekunden Ihre und die Wahl Ihres Schwarms, bezahlen, prüfen, ob Sie die richtige Menge Geld oder die richtige Karte geben, prüfen, ob die Rechnung korrekt ist, prüfen, dass die Bestellung die richtigen Artikel enthält, usw. + +Aber dann, auch wenn Sie Ihre Burger noch nicht haben, ist Ihre Interaktion mit dem Kassierer erst mal „auf Pause“ ⏸, weil Sie warten müssen 🕙, bis Ihre Burger fertig sind. + +Aber wenn Sie sich von der Theke entfernt haben und mit der Nummer für die Bestellung an einem Tisch sitzen, können Sie Ihre Aufmerksamkeit auf Ihren Schwarm lenken und an dieser Aufgabe „arbeiten“ ⏯ 🤓. Sie machen wieder etwas sehr „Produktives“ und flirten mit Ihrem Schwarm 😍. + +Dann sagt der Kassierer 💁 „Ich bin mit dem Burger fertig“, indem er Ihre Nummer auf dem Display über der Theke anzeigt, aber Sie springen nicht sofort wie verrückt auf, wenn das Display auf Ihre Nummer springt. Sie wissen, dass niemand Ihnen Ihre Burger wegnimmt, denn Sie haben die Nummer Ihrer Bestellung, und andere Leute haben andere Nummern. + +Also warten Sie darauf, dass Ihr Schwarm ihre Geschichte zu Ende erzählt (die aktuelle Arbeit ⏯ / bearbeitete Aufgabe beendet 🤓), lächeln sanft und sagen, dass Sie die Burger holen ⏸. + +Dann gehen Sie zur Theke 🔀, zur ursprünglichen Aufgabe, die nun erledigt ist ⏯, nehmen die Burger auf, sagen Danke, und bringen sie zum Tisch. Damit ist dieser Schritt / diese Aufgabe der Interaktion mit der Theke abgeschlossen ⏹. Das wiederum schafft eine neue Aufgabe, „Burger essen“ 🔀 ⏯, aber die vorherige Aufgabe „Burger holen“ ist erledigt ⏹. + +### Parallele Hamburger + +Stellen wir uns jetzt vor, dass es sich hierbei nicht um „nebenläufige Hamburger“, sondern um „parallele Hamburger“ handelt. + +Sie gehen los mit Ihrem Schwarm, um paralleles Fast Food zu bekommen. + +Sie stehen in der Schlange, während mehrere (sagen wir acht) Kassierer, die gleichzeitig Köche sind, die Bestellungen der Leute vor Ihnen entgegennehmen. + +Alle vor Ihnen warten darauf, dass ihre Burger fertig sind, bevor sie die Theke verlassen, denn jeder der 8 Kassierer geht los und bereitet den Burger sofort zu, bevor er die nächste Bestellung entgegennimmt. + + + +Dann sind Sie endlich an der Reihe und bestellen zwei sehr leckere Burger für Ihren Schwarm und Sie. + +Sie zahlen 💸. + + + +Der Kassierer geht in die Küche. + +Sie warten, vor der Theke stehend 🕙, damit niemand außer Ihnen Ihre Burger entgegennimmt, da es keine Nummern für die Reihenfolge gibt. + + + +Da Sie und Ihr Schwarm damit beschäftigt sind, niemanden vor sich zu lassen, der Ihre Burger nimmt, wenn sie ankommen, können Sie Ihrem Schwarm keine Aufmerksamkeit schenken. 😞 + +Das ist „synchrone“ Arbeit, Sie sind mit dem Kassierer/Koch „synchronisiert“ 👨‍🍳. Sie müssen warten 🕙 und genau in dem Moment da sein, in dem der Kassierer/Koch 👨‍🍳 die Burger zubereitet hat und Ihnen gibt, sonst könnte jemand anderes sie nehmen. + + + +Dann kommt Ihr Kassierer/Koch 👨‍🍳 endlich mit Ihren Burgern zurück, nachdem Sie lange vor der Theke gewartet 🕙 haben. + + + +Sie nehmen Ihre Burger und gehen mit Ihrem Schwarm an den Tisch. + +Sie essen sie und sind fertig. ⏹ + + + +Es wurde nicht viel geredet oder geflirtet, da die meiste Zeit mit Warten 🕙 vor der Theke verbracht wurde. 😞 + +!!! info + Die wunderschönen Illustrationen stammen von Ketrina Thompson. 🎨 + +--- + +In diesem Szenario der parallelen Hamburger sind Sie ein Computersystem / Programm 🤖 mit zwei Prozessoren (Sie und Ihr Schwarm), die beide warten 🕙 und ihre Aufmerksamkeit darauf verwenden, „lange Zeit vor der Theke zu warten“ 🕙. + +Der Fast-Food-Laden verfügt über 8 Prozessoren (Kassierer/Köche). Während der nebenläufige Burger-Laden nur zwei hatte (einen Kassierer und einen Koch). + +Dennoch ist das schlussendliche Benutzererlebnis nicht das Beste. 😞 + +--- + +Dies wäre die parallele äquivalente Geschichte für Hamburger. 🍔 + +Für ein „realeres“ Beispiel hierfür, stellen Sie sich eine Bank vor. + +Bis vor kurzem hatten die meisten Banken mehrere Kassierer 👨‍💼👨‍💼👨‍💼👨‍💼 und eine große Warteschlange 🕙🕙🕙🕙🕙🕙🕙🕙. + +Alle Kassierer erledigen die ganze Arbeit mit einem Kunden nach dem anderen 👨‍💼⏯. + +Und man muss lange in der Schlange warten 🕙 sonst kommt man nicht an die Reihe. + +Sie würden Ihren Schwarm 😍 wahrscheinlich nicht mitnehmen wollen, um Besorgungen bei der Bank zu erledigen 🏦. + +### Hamburger Schlussfolgerung + +In diesem Szenario „Fast Food Burger mit Ihrem Schwarm“ ist es viel sinnvoller, ein nebenläufiges System zu haben ⏸🔀⏯, da viel gewartet wird 🕙. + +Das ist auch bei den meisten Webanwendungen der Fall. + +Viele, viele Benutzer, aber Ihr Server wartet 🕙 darauf, dass deren nicht so gute Internetverbindungen die Requests übermitteln. + +Und dann warten 🕙, bis die Responses zurückkommen. + +Dieses „Warten“ 🕙 wird in Mikrosekunden gemessen, aber zusammenfassend lässt sich sagen, dass am Ende eine Menge gewartet wird. + +Deshalb ist es sehr sinnvoll, asynchronen ⏸🔀⏯ Code für Web-APIs zu verwenden. + +Diese Art der Asynchronität hat NodeJS populär gemacht (auch wenn NodeJS nicht parallel ist) und darin liegt die Stärke von Go als Programmiersprache. + +Und das ist das gleiche Leistungsniveau, das Sie mit **FastAPI** erhalten. + +Und da Sie Parallelität und Asynchronität gleichzeitig haben können, erzielen Sie eine höhere Performanz als die meisten getesteten NodeJS-Frameworks und sind mit Go auf Augenhöhe, einer kompilierten Sprache, die näher an C liegt (alles dank Starlette). + +### Ist Nebenläufigkeit besser als Parallelität? + +Nein! Das ist nicht die Moral der Geschichte. + +Nebenläufigkeit unterscheidet sich von Parallelität. Und sie ist besser bei **bestimmten** Szenarien, die viel Warten erfordern. Aus diesem Grund ist sie im Allgemeinen viel besser als Parallelität für die Entwicklung von Webanwendungen. Aber das stimmt nicht für alle Anwendungen. + +Um die Dinge auszugleichen, stellen Sie sich die folgende Kurzgeschichte vor: + +> Sie müssen ein großes, schmutziges Haus aufräumen. + +*Yup, das ist die ganze Geschichte*. + +--- + +Es gibt kein Warten 🕙, nur viel Arbeit an mehreren Stellen im Haus. + +Sie könnten wie im Hamburger-Beispiel hin- und herspringen, zuerst das Wohnzimmer, dann die Küche, aber da Sie auf nichts warten 🕙, sondern nur putzen und putzen, hätte das Hin- und Herspringen keine Auswirkungen. + +Es würde mit oder ohne Hin- und Herspringen (Nebenläufigkeit) die gleiche Zeit in Anspruch nehmen, um fertig zu werden, und Sie hätten die gleiche Menge an Arbeit erledigt. + +Aber wenn Sie in diesem Fall die acht Ex-Kassierer/Köche/jetzt Reinigungskräfte mitbringen würden und jeder von ihnen (plus Sie) würde einen Bereich des Hauses reinigen, könnten Sie die ganze Arbeit **parallel** erledigen, und würden mit dieser zusätzlichen Hilfe viel schneller fertig werden. + +In diesem Szenario wäre jede einzelne Reinigungskraft (einschließlich Ihnen) ein Prozessor, der seinen Teil der Arbeit erledigt. + +Und da die meiste Ausführungszeit durch tatsächliche Arbeit (anstatt durch Warten) in Anspruch genommen wird und die Arbeit in einem Computer von einer CPU erledigt wird, werden diese Probleme als „CPU-lastig“ („CPU bound“) bezeichnet. + +--- + +Typische Beispiele für CPU-lastige Vorgänge sind Dinge, die komplexe mathematische Berechnungen erfordern. + +Zum Beispiel: + +* **Audio-** oder **Bildbearbeitung**. +* **Computer Vision**: Ein Bild besteht aus Millionen von Pixeln, jedes Pixel hat 3 Werte / Farben, die Verarbeitung erfordert normalerweise, Berechnungen mit diesen Pixeln durchzuführen, alles zur gleichen Zeit. +* **Maschinelles Lernen**: Normalerweise sind viele „Matrix“- und „Vektor“-Multiplikationen erforderlich. Stellen Sie sich eine riesige Tabelle mit Zahlen vor, in der Sie alle Zahlen gleichzeitig multiplizieren. +* **Deep Learning**: Dies ist ein Teilgebiet des maschinellen Lernens, daher gilt das Gleiche. Es ist nur so, dass es nicht eine einzige Tabelle mit Zahlen zum Multiplizieren gibt, sondern eine riesige Menge davon, und in vielen Fällen verwendet man einen speziellen Prozessor, um diese Modelle zu erstellen und / oder zu verwenden. + +### Nebenläufigkeit + Parallelität: Web + maschinelles Lernen + +Mit **FastAPI** können Sie die Vorteile der Nebenläufigkeit nutzen, die in der Webentwicklung weit verbreitet ist (derselbe Hauptvorteil von NodeJS). + +Sie können aber auch die Vorteile von Parallelität und Multiprocessing (Mehrere Prozesse werden parallel ausgeführt) für **CPU-lastige** Workloads wie in Systemen für maschinelles Lernen nutzen. + +Dies und die einfache Tatsache, dass Python die Hauptsprache für **Data Science**, maschinelles Lernen und insbesondere Deep Learning ist, machen FastAPI zu einem sehr passenden Werkzeug für Web-APIs und Anwendungen für Data Science / maschinelles Lernen (neben vielen anderen). + +Wie Sie diese Parallelität in der Produktion erreichen, erfahren Sie im Abschnitt über [Deployment](deployment/index.md){.internal-link target=_blank}. + +## `async` und `await`. + +Moderne Versionen von Python verfügen über eine sehr intuitive Möglichkeit, asynchronen Code zu schreiben. Dadurch sieht es wie normaler „sequentieller“ Code aus und übernimmt im richtigen Moment das „Warten“ für Sie. + +Wenn es einen Vorgang gibt, der erfordert, dass gewartet wird, bevor die Ergebnisse zurückgegeben werden, und der diese neue Python-Funktionalität unterstützt, können Sie ihn wie folgt schreiben: + +```Python +burgers = await get_burgers(2) +``` + +Der Schlüssel hier ist das `await`. Es teilt Python mit, dass es warten ⏸ muss, bis `get_burgers(2)` seine Aufgabe erledigt hat 🕙, bevor die Ergebnisse in `burgers` gespeichert werden. Damit weiß Python, dass es in der Zwischenzeit etwas anderes tun kann 🔀 ⏯ (z. B. einen weiteren Request empfangen). + +Damit `await` funktioniert, muss es sich in einer Funktion befinden, die diese Asynchronität unterstützt. Dazu deklarieren Sie sie einfach mit `async def`: + +```Python hl_lines="1" +async def get_burgers(number: int): + # Mach Sie hier etwas Asynchrones, um die Burger zu erstellen + return burgers +``` + +... statt mit `def`: + +```Python hl_lines="2" +# Die ist nicht asynchron +def get_sequential_burgers(number: int): + # Mach Sie hier etwas Sequentielles, um die Burger zu erstellen + return burgers +``` + +Mit `async def` weiß Python, dass es innerhalb dieser Funktion auf `await`-Ausdrücke achten muss und dass es die Ausführung dieser Funktion „anhalten“ ⏸ und etwas anderes tun kann 🔀, bevor es zurückkommt. + +Wenn Sie eine `async def`-Funktion aufrufen möchten, müssen Sie sie „erwarten“ („await“). Das folgende wird also nicht funktionieren: + +```Python +# Das funktioniert nicht, weil get_burgers definiert wurde mit: async def +burgers = get_burgers(2) +``` + +--- + +Wenn Sie also eine Bibliothek verwenden, die Ihnen sagt, dass Sie sie mit `await` aufrufen können, müssen Sie die *Pfadoperation-Funktionen*, die diese Bibliothek verwenden, mittels `async def` erstellen, wie in: + +```Python hl_lines="2-3" +@app.get('/burgers') +async def read_burgers(): + burgers = await get_burgers(2) + return burgers +``` + +### Weitere technische Details + +Ihnen ist wahrscheinlich aufgefallen, dass `await` nur innerhalb von Funktionen verwendet werden kann, die mit `async def` definiert sind. + +Gleichzeitig müssen aber mit `async def` definierte Funktionen „erwartet“ („awaited“) werden. Daher können Funktionen mit `async def` nur innerhalb von Funktionen aufgerufen werden, die auch mit `async def` definiert sind. + +Daraus resultiert das Ei-und-Huhn-Problem: Wie ruft man die erste `async` Funktion auf? + +Wenn Sie mit **FastAPI** arbeiten, müssen Sie sich darüber keine Sorgen machen, da diese „erste“ Funktion Ihre *Pfadoperation-Funktion* sein wird und FastAPI weiß, was zu tun ist. + +Wenn Sie jedoch `async` / `await` ohne FastAPI verwenden möchten, können Sie dies auch tun. + +### Schreiben Sie Ihren eigenen asynchronen Code + +Starlette (und **FastAPI**) basiert auf AnyIO, was bedeutet, es ist sowohl kompatibel mit der Python-Standardbibliothek asyncio, als auch mit Trio. + +Insbesondere können Sie AnyIO direkt verwenden für Ihre fortgeschritten nebenläufigen und parallelen Anwendungsfälle, die fortgeschrittenere Muster in Ihrem eigenen Code erfordern. + +Und selbst wenn Sie FastAPI nicht verwenden würden, könnten Sie auch Ihre eigenen asynchronen Anwendungen mit AnyIO so schreiben, dass sie hoch kompatibel sind und Sie dessen Vorteile nutzen können (z. B. *strukturierte Nebenläufigkeit*). + +### Andere Formen von asynchronem Code + +Diese Art der Verwendung von `async` und `await` ist in der Sprache relativ neu. + +Aber sie erleichtert die Arbeit mit asynchronem Code erheblich. + +Die gleiche Syntax (oder fast identisch) wurde kürzlich auch in moderne Versionen von JavaScript (im Browser und in NodeJS) aufgenommen. + +Davor war der Umgang mit asynchronem Code jedoch deutlich komplexer und schwieriger. + +In früheren Versionen von Python hätten Sie Threads oder Gevent verwenden können. Der Code ist jedoch viel komplexer zu verstehen, zu debuggen und nachzuvollziehen. + +In früheren Versionen von NodeJS / Browser JavaScript hätten Sie „Callbacks“ verwendet. Was zur Callback-Hölle führt. + +## Coroutinen + +**Coroutine** ist nur ein schicker Begriff für dasjenige, was von einer `async def`-Funktion zurückgegeben wird. Python weiß, dass es so etwas wie eine Funktion ist, die es starten kann und die irgendwann endet, aber auch dass sie pausiert ⏸ werden kann, wann immer darin ein `await` steht. + +Aber all diese Funktionalität der Verwendung von asynchronem Code mit `async` und `await` wird oft als Verwendung von „Coroutinen“ zusammengefasst. Es ist vergleichbar mit dem Hauptmerkmal von Go, den „Goroutinen“. + +## Fazit + +Sehen wir uns den gleichen Satz von oben noch mal an: + +> Moderne Versionen von Python unterstützen **„asynchronen Code“** unter Verwendung sogenannter **„Coroutinen“** mithilfe der Syntax **`async`** und **`await`**. + +Das sollte jetzt mehr Sinn ergeben. ✨ + +All das ist es, was FastAPI (via Starlette) befeuert und es eine so beeindruckende Performanz haben lässt. + +## Sehr technische Details + +!!! warning "Achtung" + Das folgende können Sie wahrscheinlich überspringen. + + Dies sind sehr technische Details darüber, wie **FastAPI** unter der Haube funktioniert. + + Wenn Sie über gute technische Kenntnisse verfügen (Coroutinen, Threads, Blocking, usw.) und neugierig sind, wie FastAPI mit `async def`s im Vergleich zu normalen `def`s umgeht, fahren Sie fort. + +### Pfadoperation-Funktionen + +Wenn Sie eine *Pfadoperation-Funktion* mit normalem `def` anstelle von `async def` deklarieren, wird sie in einem externen Threadpool ausgeführt, der dann `await`et wird, anstatt direkt aufgerufen zu werden (da dies den Server blockieren würde). + +Wenn Sie von einem anderen asynchronen Framework kommen, das nicht auf die oben beschriebene Weise funktioniert, und Sie es gewohnt sind, triviale, nur-berechnende *Pfadoperation-Funktionen* mit einfachem `def` zu definieren, um einen geringfügigen Geschwindigkeitsgewinn (etwa 100 Nanosekunden) zu erzielen, beachten Sie bitte, dass der Effekt in **FastAPI** genau gegenteilig wäre. In solchen Fällen ist es besser, `async def` zu verwenden, es sei denn, Ihre *Pfadoperation-Funktionen* verwenden Code, der blockierende I/O-Operationen durchführt. + +Dennoch besteht in beiden Fällen eine gute Chance, dass **FastAPI** [immer noch schneller](index.md#performanz){.internal-link target=_blank} als Ihr bisheriges Framework (oder zumindest damit vergleichbar) ist. + +### Abhängigkeiten + +Das Gleiche gilt für [Abhängigkeiten](tutorial/dependencies/index.md){.internal-link target=_blank}. Wenn eine Abhängigkeit eine normale `def`-Funktion ist, anstelle einer `async def`-Funktion, dann wird sie im externen Threadpool ausgeführt. + +### Unterabhängigkeiten + +Sie können mehrere Abhängigkeiten und [Unterabhängigkeiten](tutorial/dependencies/sub-dependencies.md){.internal-link target=_blank} haben, die einander bedingen (als Parameter der Funktionsdefinitionen), einige davon könnten erstellt werden mit `async def` und einige mit normalem `def`. Es würde immer noch funktionieren und diejenigen, die mit normalem `def` erstellt wurden, würden in einem externen Thread (vom Threadpool stammend) aufgerufen werden, anstatt `await`et zu werden. + +### Andere Hilfsfunktionen + +Jede andere Hilfsfunktion, die Sie direkt aufrufen, kann mit normalem `def` oder `async def` erstellt werden, und FastAPI beeinflusst nicht die Art und Weise, wie Sie sie aufrufen. + +Dies steht im Gegensatz zu den Funktionen, die FastAPI für Sie aufruft: *Pfadoperation-Funktionen* und Abhängigkeiten. + +Wenn Ihre Hilfsfunktion eine normale Funktion mit `def` ist, wird sie direkt aufgerufen (so wie Sie es in Ihrem Code schreiben), nicht in einem Threadpool. Wenn die Funktion mit `async def` erstellt wurde, sollten Sie sie `await`en, wenn Sie sie in Ihrem Code aufrufen. + +--- + +Nochmal, es handelt sich hier um sehr technische Details, die Ihnen helfen, falls Sie danach gesucht haben. + +Andernfalls liegen Sie richtig, wenn Sie sich an die Richtlinien aus dem obigen Abschnitt halten: In Eile?. diff --git a/docs/de/docs/benchmarks.md b/docs/de/docs/benchmarks.md new file mode 100644 index 0000000000000..6efd56e8307c4 --- /dev/null +++ b/docs/de/docs/benchmarks.md @@ -0,0 +1,34 @@ +# Benchmarks + +Unabhängige TechEmpower-Benchmarks zeigen, **FastAPI**-Anwendungen, die unter Uvicorn ausgeführt werden, gehören zu den schnellsten existierenden Python-Frameworks, nur Starlette und Uvicorn selbst (intern von FastAPI verwendet) sind schneller. + +Beim Ansehen von Benchmarks und Vergleichen sollten Sie jedoch Folgende Punkte beachten. + +## Benchmarks und Geschwindigkeit + +Wenn Sie sich die Benchmarks ansehen, werden häufig mehrere Tools mit unterschiedlichen Eigenschaften als gleichwertig verglichen. + +Konkret geht es darum, Uvicorn, Starlette und FastAPI miteinander zu vergleichen (neben vielen anderen Tools). + +Je einfacher das Problem, welches durch das Tool gelöst wird, desto besser ist die Performanz. Und die meisten Benchmarks testen nicht die zusätzlichen Funktionen, welche das Tool bietet. + +Die Hierarchie ist wie folgt: + +* **Uvicorn**: ein ASGI-Server + * **Starlette**: (verwendet Uvicorn) ein Web-Mikroframework + * **FastAPI**: (verwendet Starlette) ein API-Mikroframework mit mehreren zusätzlichen Funktionen zum Erstellen von APIs, mit Datenvalidierung, usw. + +* **Uvicorn**: + * Bietet die beste Leistung, da außer dem Server selbst nicht viel zusätzlicher Code vorhanden ist. + * Sie würden eine Anwendung nicht direkt in Uvicorn schreiben. Das würde bedeuten, dass Ihr Code zumindest mehr oder weniger den gesamten von Starlette (oder **FastAPI**) bereitgestellten Code enthalten müsste. Und wenn Sie das täten, hätte Ihre endgültige Anwendung den gleichen Overhead wie die Verwendung eines Frameworks nebst Minimierung Ihres Anwendungscodes und der Fehler. + * Wenn Sie Uvicorn vergleichen, vergleichen Sie es mit Anwendungsservern wie Daphne, Hypercorn, uWSGI, usw. +* **Starlette**: + * Wird nach Uvicorn die nächstbeste Performanz erbringen. Tatsächlich nutzt Starlette intern Uvicorn. Daher kann es wahrscheinlich nur „langsamer“ als Uvicorn sein, weil mehr Code ausgeführt wird. + * Aber es bietet Ihnen die Tools zum Erstellen einfacher Webanwendungen, mit Routing basierend auf Pfaden, usw. + * Wenn Sie Starlette vergleichen, vergleichen Sie es mit Webframeworks (oder Mikroframeworks) wie Sanic, Flask, Django, usw. +* **FastAPI**: + * So wie Starlette Uvicorn verwendet und nicht schneller als dieses sein kann, verwendet **FastAPI** Starlette, sodass es nicht schneller als dieses sein kann. + * FastAPI bietet zusätzlich zu Starlette weitere Funktionen. Funktionen, die Sie beim Erstellen von APIs fast immer benötigen, wie Datenvalidierung und Serialisierung. Und wenn Sie es verwenden, erhalten Sie kostenlos automatische Dokumentation (die automatische Dokumentation verursacht nicht einmal zusätzlichen Aufwand für laufende Anwendungen, sie wird beim Start generiert). + * Wenn Sie FastAPI nicht, und direkt Starlette (oder ein anderes Tool wie Sanic, Flask, Responder, usw.) verwenden würden, müssten Sie die gesamte Datenvalidierung und Serialisierung selbst implementieren. Ihre finale Anwendung hätte also immer noch den gleichen Overhead, als ob sie mit FastAPI erstellt worden wäre. Und in vielen Fällen ist diese Datenvalidierung und Serialisierung der größte Teil des in Anwendungen geschriebenen Codes. + * Durch die Verwendung von FastAPI sparen Sie also Entwicklungszeit, Fehler und Codezeilen und würden wahrscheinlich die gleiche Leistung (oder eine bessere) erzielen, die Sie hätten, wenn Sie es nicht verwenden würden (da Sie alles in Ihrem Code implementieren müssten). + * Wenn Sie FastAPI vergleichen, vergleichen Sie es mit einem Webanwendung-Framework (oder einer Reihe von Tools), welche Datenvalidierung, Serialisierung und Dokumentation bereitstellen, wie Flask-apispec, NestJS, Molten, usw. – Frameworks mit integrierter automatischer Datenvalidierung, Serialisierung und Dokumentation. diff --git a/docs/de/docs/deployment/cloud.md b/docs/de/docs/deployment/cloud.md new file mode 100644 index 0000000000000..2d70fe4e5a827 --- /dev/null +++ b/docs/de/docs/deployment/cloud.md @@ -0,0 +1,17 @@ +# FastAPI-Deployment bei Cloud-Anbietern + +Sie können praktisch **jeden Cloud-Anbieter** für das Deployment Ihrer FastAPI-Anwendung verwenden. + +In den meisten Fällen verfügen die Haupt-Cloud-Anbieter über Anleitungen zum Deployment von FastAPI. + +## Cloud-Anbieter – Sponsoren + +Einige Cloud-Anbieter ✨ [**sponsern FastAPI**](../help-fastapi.md#den-autor-sponsern){.internal-link target=_blank} ✨, dies gewährleistet die kontinuierliche und gesunde **Entwicklung** von FastAPI und seinem **Ökosystem**. + +Und es zeigt deren wahres Engagement für FastAPI und seine **Community** (Sie), da diese Ihnen nicht nur einen **guten Service** bieten möchten, sondern auch sicherstellen möchten, dass Sie über ein **gutes und gesundes Framework** verfügen, FastAPI. 🙇 + +Vielleicht möchten Sie deren Dienste ausprobieren und deren Anleitungen folgen: + +* Platform.sh +* Porter +* Coherence diff --git a/docs/de/docs/deployment/concepts.md b/docs/de/docs/deployment/concepts.md new file mode 100644 index 0000000000000..5e1a4f10980f9 --- /dev/null +++ b/docs/de/docs/deployment/concepts.md @@ -0,0 +1,311 @@ +# Deployment-Konzepte + +Bei dem Deployment – der Bereitstellung – einer **FastAPI**-Anwendung, oder eigentlich jeder Art von Web-API, gibt es mehrere Konzepte, die Sie wahrscheinlich interessieren, und mithilfe der Sie die **am besten geeignete** Methode zur **Bereitstellung Ihrer Anwendung** finden können. + +Einige wichtige Konzepte sind: + +* Sicherheit – HTTPS +* Beim Hochfahren ausführen +* Neustarts +* Replikation (die Anzahl der laufenden Prozesse) +* Arbeitsspeicher +* Schritte vor dem Start + +Wir werden sehen, wie diese sich auf das **Deployment** auswirken. + +Letztendlich besteht das ultimative Ziel darin, **Ihre API-Clients** auf **sichere** Weise zu bedienen, um **Unterbrechungen** zu vermeiden und die **Rechenressourcen** (z. B. entfernte Server/virtuelle Maschinen) so effizient wie möglich zu nutzen. 🚀 + +Ich erzähle Ihnen hier etwas mehr über diese **Konzepte**, was Ihnen hoffentlich die **Intuition** gibt, die Sie benötigen, um zu entscheiden, wie Sie Ihre API in sehr unterschiedlichen Umgebungen bereitstellen, möglicherweise sogar in **zukünftigen**, die jetzt noch nicht existieren. + +Durch die Berücksichtigung dieser Konzepte können Sie die beste Variante der Bereitstellung **Ihrer eigenen APIs** **evaluieren und konzipieren**. + +In den nächsten Kapiteln werde ich Ihnen mehr **konkrete Rezepte** für die Bereitstellung von FastAPI-Anwendungen geben. + +Aber schauen wir uns zunächst einmal diese grundlegenden **konzeptionellen Ideen** an. Diese Konzepte gelten auch für jede andere Art von Web-API. 💡 + +## Sicherheit – HTTPS + +Im [vorherigen Kapitel über HTTPS](https.md){.internal-link target=_blank} haben wir erfahren, wie HTTPS Verschlüsselung für Ihre API bereitstellt. + +Wir haben auch gesehen, dass HTTPS normalerweise von einer Komponente **außerhalb** Ihres Anwendungsservers bereitgestellt wird, einem **TLS-Terminierungsproxy**. + +Und es muss etwas geben, das für die **Erneuerung der HTTPS-Zertifikate** zuständig ist, es könnte sich um dieselbe Komponente handeln oder um etwas anderes. + +### Beispieltools für HTTPS + +Einige der Tools, die Sie als TLS-Terminierungsproxy verwenden können, sind: + +* Traefik + * Handhabt automatisch Zertifikat-Erneuerungen ✨ +* Caddy + * Handhabt automatisch Zertifikat-Erneuerungen ✨ +* Nginx + * Mit einer externen Komponente wie Certbot für Zertifikat-Erneuerungen +* HAProxy + * Mit einer externen Komponente wie Certbot für Zertifikat-Erneuerungen +* Kubernetes mit einem Ingress Controller wie Nginx + * Mit einer externen Komponente wie cert-manager für Zertifikat-Erneuerungen +* Es wird intern von einem Cloud-Anbieter als Teil seiner Dienste verwaltet (siehe unten 👇) + +Eine andere Möglichkeit besteht darin, dass Sie einen **Cloud-Dienst** verwenden, der den größten Teil der Arbeit übernimmt, einschließlich der Einrichtung von HTTPS. Er könnte einige Einschränkungen haben oder Ihnen mehr in Rechnung stellen, usw. In diesem Fall müssten Sie jedoch nicht selbst einen TLS-Terminierungsproxy einrichten. + +In den nächsten Kapiteln zeige ich Ihnen einige konkrete Beispiele. + +--- + +Die nächsten zu berücksichtigenden Konzepte drehen sich dann um das Programm, das Ihre eigentliche API ausführt (z. B. Uvicorn). + +## Programm und Prozess + +Wir werden viel über den laufenden „**Prozess**“ sprechen, daher ist es nützlich, Klarheit darüber zu haben, was das bedeutet und was der Unterschied zum Wort „**Programm**“ ist. + +### Was ist ein Programm? + +Das Wort **Programm** wird häufig zur Beschreibung vieler Dinge verwendet: + +* Der **Code**, den Sie schreiben, die **Python-Dateien**. +* Die **Datei**, die vom Betriebssystem **ausgeführt** werden kann, zum Beispiel: `python`, `python.exe` oder `uvicorn`. +* Ein bestimmtes Programm, während es auf dem Betriebssystem **läuft**, die CPU nutzt und Dinge im Arbeitsspeicher ablegt. Dies wird auch als **Prozess** bezeichnet. + +### Was ist ein Prozess? + +Das Wort **Prozess** wird normalerweise spezifischer verwendet und bezieht sich nur auf das, was im Betriebssystem ausgeführt wird (wie im letzten Punkt oben): + +* Ein bestimmtes Programm, während es auf dem Betriebssystem **ausgeführt** wird. + * Dies bezieht sich weder auf die Datei noch auf den Code, sondern **speziell** auf das, was vom Betriebssystem **ausgeführt** und verwaltet wird. +* Jedes Programm, jeder Code **kann nur dann Dinge tun**, wenn er **ausgeführt** wird, wenn also ein **Prozess läuft**. +* Der Prozess kann von Ihnen oder vom Betriebssystem **terminiert** („beendet“, „gekillt“) werden. An diesem Punkt hört es auf zu laufen/ausgeführt zu werden und kann **keine Dinge mehr tun**. +* Hinter jeder Anwendung, die Sie auf Ihrem Computer ausführen, steckt ein Prozess, jedes laufende Programm, jedes Fenster usw. Und normalerweise laufen viele Prozesse **gleichzeitig**, während ein Computer eingeschaltet ist. +* Es können **mehrere Prozesse** desselben **Programms** gleichzeitig ausgeführt werden. + +Wenn Sie sich den „Task-Manager“ oder „Systemmonitor“ (oder ähnliche Tools) in Ihrem Betriebssystem ansehen, können Sie viele dieser laufenden Prozesse sehen. + +Und Sie werden beispielsweise wahrscheinlich feststellen, dass mehrere Prozesse dasselbe Browserprogramm ausführen (Firefox, Chrome, Edge, usw.). Normalerweise führen diese einen Prozess pro Browsertab sowie einige andere zusätzliche Prozesse aus. + + + +--- + +Nachdem wir nun den Unterschied zwischen den Begriffen **Prozess** und **Programm** kennen, sprechen wir weiter über das Deployment. + +## Beim Hochfahren ausführen + +Wenn Sie eine Web-API erstellen, möchten Sie in den meisten Fällen, dass diese **immer läuft**, ununterbrochen, damit Ihre Clients immer darauf zugreifen können. Es sei denn natürlich, Sie haben einen bestimmten Grund, warum Sie möchten, dass diese nur in bestimmten Situationen ausgeführt wird. Meistens möchten Sie jedoch, dass sie ständig ausgeführt wird und **verfügbar** ist. + +### Auf einem entfernten Server + +Wenn Sie einen entfernten Server (einen Cloud-Server, eine virtuelle Maschine, usw.) einrichten, können Sie am einfachsten Uvicorn (oder ähnliches) manuell ausführen, genau wie bei der lokalen Entwicklung. + +Und es wird funktionieren und **während der Entwicklung** nützlich sein. + +Wenn Ihre Verbindung zum Server jedoch unterbrochen wird, wird der **laufende Prozess** wahrscheinlich abstürzen. + +Und wenn der Server neu gestartet wird (z. B. nach Updates oder Migrationen vom Cloud-Anbieter), werden Sie das wahrscheinlich **nicht bemerken**. Und deshalb wissen Sie nicht einmal, dass Sie den Prozess manuell neu starten müssen. Ihre API bleibt also einfach tot. 😱 + +### Beim Hochfahren automatisch ausführen + +Im Allgemeinen möchten Sie wahrscheinlich, dass das Serverprogramm (z. B. Uvicorn) beim Hochfahren des Servers automatisch gestartet wird und kein **menschliches Eingreifen** erforderlich ist, sodass immer ein Prozess mit Ihrer API ausgeführt wird (z. B. Uvicorn, welches Ihre FastAPI-Anwendung ausführt). + +### Separates Programm + +Um dies zu erreichen, haben Sie normalerweise ein **separates Programm**, welches sicherstellt, dass Ihre Anwendung beim Hochfahren ausgeführt wird. Und in vielen Fällen würde es auch sicherstellen, dass auch andere Komponenten oder Anwendungen ausgeführt werden, beispielsweise eine Datenbank. + +### Beispieltools zur Ausführung beim Hochfahren + +Einige Beispiele für Tools, die diese Aufgabe übernehmen können, sind: + +* Docker +* Kubernetes +* Docker Compose +* Docker im Schwarm-Modus +* Systemd +* Supervisor +* Es wird intern von einem Cloud-Anbieter im Rahmen seiner Dienste verwaltet +* Andere ... + +In den nächsten Kapiteln werde ich Ihnen konkretere Beispiele geben. + +## Neustart + +Ähnlich wie Sie sicherstellen möchten, dass Ihre Anwendung beim Hochfahren ausgeführt wird, möchten Sie wahrscheinlich auch sicherstellen, dass diese nach Fehlern **neu gestartet** wird. + +### Wir machen Fehler + +Wir, als Menschen, machen ständig **Fehler**. Software hat fast *immer* **Bugs**, die an verschiedenen Stellen versteckt sind. 🐛 + +Und wir als Entwickler verbessern den Code ständig, wenn wir diese Bugs finden und neue Funktionen implementieren (und möglicherweise auch neue Bugs hinzufügen 😅). + +### Kleine Fehler automatisch handhaben + +Wenn beim Erstellen von Web-APIs mit FastAPI ein Fehler in unserem Code auftritt, wird FastAPI ihn normalerweise dem einzelnen Request zurückgeben, der den Fehler ausgelöst hat. 🛡 + +Der Client erhält für diesen Request einen **500 Internal Server Error**, aber die Anwendung arbeitet bei den nächsten Requests weiter, anstatt einfach komplett abzustürzen. + +### Größere Fehler – Abstürze + +Dennoch kann es vorkommen, dass wir Code schreiben, der **die gesamte Anwendung zum Absturz bringt** und so zum Absturz von Uvicorn und Python führt. 💥 + +Und dennoch möchten Sie wahrscheinlich nicht, dass die Anwendung tot bleibt, weil an einer Stelle ein Fehler aufgetreten ist. Sie möchten wahrscheinlich, dass sie zumindest für die *Pfadoperationen*, die nicht fehlerhaft sind, **weiterläuft**. + +### Neustart nach Absturz + +Aber in den Fällen mit wirklich schwerwiegenden Fehlern, die den laufenden **Prozess** zum Absturz bringen, benötigen Sie eine externe Komponente, die den Prozess **neu startet**, zumindest ein paar Mal ... + +!!! tip "Tipp" + ... Obwohl es wahrscheinlich keinen Sinn macht, sie immer wieder neu zu starten, wenn die gesamte Anwendung einfach **sofort abstürzt**. Aber in diesen Fällen werden Sie es wahrscheinlich während der Entwicklung oder zumindest direkt nach dem Deployment bemerken. + + Konzentrieren wir uns also auf die Hauptfälle, in denen die Anwendung in bestimmten Fällen **in der Zukunft** völlig abstürzen könnte und es dann dennoch sinnvoll ist, sie neu zu starten. + +Sie möchten wahrscheinlich, dass eine **externe Komponente** für den Neustart Ihrer Anwendung verantwortlich ist, da zu diesem Zeitpunkt dieselbe Anwendung mit Uvicorn und Python bereits abgestürzt ist und es daher nichts im selben Code derselben Anwendung gibt, was etwas dagegen tun kann. + +### Beispieltools zum automatischen Neustart + +In den meisten Fällen wird dasselbe Tool, das zum **Ausführen des Programms beim Hochfahren** verwendet wird, auch für automatische **Neustarts** verwendet. + +Dies könnte zum Beispiel erledigt werden durch: + +* Docker +* Kubernetes +* Docker Compose +* Docker im Schwarm-Modus +* Systemd +* Supervisor +* Intern von einem Cloud-Anbieter im Rahmen seiner Dienste +* Andere ... + +## Replikation – Prozesse und Arbeitsspeicher + +Wenn Sie eine FastAPI-Anwendung verwenden und ein Serverprogramm wie Uvicorn verwenden, kann **ein einzelner Prozess** mehrere Clients gleichzeitig bedienen. + +In vielen Fällen möchten Sie jedoch mehrere Prozesse gleichzeitig ausführen. + +### Mehrere Prozesse – Worker + +Wenn Sie mehr Clients haben, als ein einzelner Prozess verarbeiten kann (z. B. wenn die virtuelle Maschine nicht sehr groß ist) und die CPU des Servers **mehrere Kerne** hat, dann könnten **mehrere Prozesse** gleichzeitig mit derselben Anwendung laufen und alle Requests unter sich verteilen. + +Wenn Sie mit **mehreren Prozessen** dasselbe API-Programm ausführen, werden diese üblicherweise als **Worker** bezeichnet. + +### Workerprozesse und Ports + +Erinnern Sie sich aus der Dokumentation [Über HTTPS](https.md){.internal-link target=_blank}, dass nur ein Prozess auf einer Kombination aus Port und IP-Adresse auf einem Server lauschen kann? + +Das ist immer noch wahr. + +Um also **mehrere Prozesse** gleichzeitig zu haben, muss es einen **einzelnen Prozess geben, der einen Port überwacht**, welcher dann die Kommunikation auf irgendeine Weise an jeden Workerprozess überträgt. + +### Arbeitsspeicher pro Prozess + +Wenn das Programm nun Dinge in den Arbeitsspeicher lädt, zum Beispiel ein Modell für maschinelles Lernen in einer Variablen oder den Inhalt einer großen Datei in einer Variablen, verbraucht das alles **einen Teil des Arbeitsspeichers (RAM – Random Access Memory)** des Servers. + +Und mehrere Prozesse teilen sich normalerweise keinen Speicher. Das bedeutet, dass jeder laufende Prozess seine eigenen Dinge, eigenen Variablen und eigenen Speicher hat. Und wenn Sie in Ihrem Code viel Speicher verbrauchen, verbraucht **jeder Prozess** die gleiche Menge Speicher. + +### Serverspeicher + +Wenn Ihr Code beispielsweise ein Machine-Learning-Modell mit **1 GB Größe** lädt und Sie einen Prozess mit Ihrer API ausführen, verbraucht dieser mindestens 1 GB RAM. Und wenn Sie **4 Prozesse** (4 Worker) starten, verbraucht jeder 1 GB RAM. Insgesamt verbraucht Ihre API also **4 GB RAM**. + +Und wenn Ihr entfernter Server oder Ihre virtuelle Maschine nur über 3 GB RAM verfügt, führt der Versuch, mehr als 4 GB RAM zu laden, zu Problemen. 🚨 + +### Mehrere Prozesse – Ein Beispiel + +Im folgenden Beispiel gibt es einen **Manager-Prozess**, welcher zwei **Workerprozesse** startet und steuert. + +Dieser Manager-Prozess wäre wahrscheinlich derjenige, welcher der IP am **Port** lauscht. Und er würde die gesamte Kommunikation an die Workerprozesse weiterleiten. + +Diese Workerprozesse würden Ihre Anwendung ausführen, sie würden die Hauptberechnungen durchführen, um einen **Request** entgegenzunehmen und eine **Response** zurückzugeben, und sie würden alles, was Sie in Variablen einfügen, in den RAM laden. + + + +Und natürlich würden auf derselben Maschine neben Ihrer Anwendung wahrscheinlich auch **andere Prozesse** laufen. + +Ein interessantes Detail ist dabei, dass der Prozentsatz der von jedem Prozess verwendeten **CPU** im Laufe der Zeit stark **variieren** kann, der **Arbeitsspeicher (RAM)** jedoch normalerweise mehr oder weniger **stabil** bleibt. + +Wenn Sie eine API haben, die jedes Mal eine vergleichbare Menge an Berechnungen durchführt, und Sie viele Clients haben, dann wird die **CPU-Auslastung** wahrscheinlich *ebenfalls stabil sein* (anstatt ständig schnell zu steigen und zu fallen). + +### Beispiele für Replikation-Tools und -Strategien + +Es gibt mehrere Ansätze, um dies zu erreichen, und ich werde Ihnen in den nächsten Kapiteln mehr über bestimmte Strategien erzählen, beispielsweise wenn es um Docker und Container geht. + +Die wichtigste zu berücksichtigende Einschränkung besteht darin, dass es eine **einzelne** Komponente geben muss, welche die **öffentliche IP** auf dem **Port** verwaltet. Und dann muss diese irgendwie die Kommunikation **weiterleiten**, an die replizierten **Prozesse/Worker**. + +Hier sind einige mögliche Kombinationen und Strategien: + +* **Gunicorn**, welches **Uvicorn-Worker** managt + * Gunicorn wäre der **Prozessmanager**, der die **IP** und den **Port** überwacht, die Replikation würde durch **mehrere Uvicorn-Workerprozesse** erfolgen +* **Uvicorn**, welches **Uvicorn-Worker** managt + * Ein Uvicorn-**Prozessmanager** würde der **IP** am **Port** lauschen, und er würde **mehrere Uvicorn-Workerprozesse** starten. +* **Kubernetes** und andere verteilte **Containersysteme** + * Etwas in der **Kubernetes**-Ebene würde die **IP** und den **Port** abhören. Die Replikation hätte **mehrere Container**, in jedem wird jeweils **ein Uvicorn-Prozess** ausgeführt. +* **Cloud-Dienste**, welche das für Sie erledigen + * Der Cloud-Dienst wird wahrscheinlich **die Replikation für Sie übernehmen**. Er würde Sie möglicherweise **einen auszuführenden Prozess** oder ein **zu verwendendes Container-Image** definieren lassen, in jedem Fall wäre es höchstwahrscheinlich **ein einzelner Uvicorn-Prozess**, und der Cloud-Dienst wäre auch verantwortlich für die Replikation. + +!!! tip "Tipp" + Machen Sie sich keine Sorgen, wenn einige dieser Punkte zu **Containern**, Docker oder Kubernetes noch nicht viel Sinn ergeben. + + Ich werde Ihnen in einem zukünftigen Kapitel mehr über Container-Images, Docker, Kubernetes, usw. erzählen: [FastAPI in Containern – Docker](docker.md){.internal-link target=_blank}. + +## Schritte vor dem Start + +Es gibt viele Fälle, in denen Sie, **bevor Sie Ihre Anwendung starten**, einige Schritte ausführen möchten. + +Beispielsweise möchten Sie möglicherweise **Datenbankmigrationen** ausführen. + +In den meisten Fällen möchten Sie diese Schritte jedoch nur **einmal** ausführen. + +Sie möchten also einen **einzelnen Prozess** haben, um diese **Vorab-Schritte** auszuführen, bevor Sie die Anwendung starten. + +Und Sie müssen sicherstellen, dass es sich um einen einzelnen Prozess handelt, der die Vorab-Schritte ausführt, *auch* wenn Sie anschließend **mehrere Prozesse** (mehrere Worker) für die Anwendung selbst starten. Wenn diese Schritte von **mehreren Prozessen** ausgeführt würden, würden diese die Arbeit **verdoppeln**, indem sie sie **parallel** ausführen, und wenn es sich bei den Schritten um etwas Delikates wie eine Datenbankmigration handelt, könnte das miteinander Konflikte verursachen. + +Natürlich gibt es Fälle, in denen es kein Problem darstellt, die Vorab-Schritte mehrmals auszuführen. In diesem Fall ist die Handhabung viel einfacher. + +!!! tip "Tipp" + Bedenken Sie außerdem, dass Sie, abhängig von Ihrer Einrichtung, in manchen Fällen **gar keine Vorab-Schritte** benötigen, bevor Sie die Anwendung starten. + + In diesem Fall müssen Sie sich darüber keine Sorgen machen. 🤷 + +### Beispiele für Strategien für Vorab-Schritte + +Es hängt **stark** davon ab, wie Sie **Ihr System bereitstellen**, und hängt wahrscheinlich mit der Art und Weise zusammen, wie Sie Programme starten, Neustarts durchführen, usw. + +Hier sind einige mögliche Ideen: + +* Ein „Init-Container“ in Kubernetes, der vor Ihrem Anwendungs-Container ausgeführt wird +* Ein Bash-Skript, das die Vorab-Schritte ausführt und dann Ihre Anwendung startet + * Sie benötigen immer noch eine Möglichkeit, *dieses* Bash-Skript zu starten/neu zu starten, Fehler zu erkennen, usw. + +!!! tip "Tipp" + Konkretere Beispiele hierfür mit Containern gebe ich Ihnen in einem späteren Kapitel: [FastAPI in Containern – Docker](docker.md){.internal-link target=_blank}. + +## Ressourcennutzung + +Ihr(e) Server ist (sind) eine **Ressource**, welche Sie mit Ihren Programmen, der Rechenzeit auf den CPUs und dem verfügbaren RAM-Speicher verbrauchen oder **nutzen** können. + +Wie viele Systemressourcen möchten Sie verbrauchen/nutzen? Sie mögen „nicht viel“ denken, aber in Wirklichkeit möchten Sie tatsächlich **so viel wie möglich ohne Absturz** verwenden. + +Wenn Sie für drei Server bezahlen, aber nur wenig von deren RAM und CPU nutzen, **verschwenden Sie wahrscheinlich Geld** 💸 und wahrscheinlich **Strom für den Server** 🌎, usw. + +In diesem Fall könnte es besser sein, nur zwei Server zu haben und einen höheren Prozentsatz von deren Ressourcen zu nutzen (CPU, Arbeitsspeicher, Festplatte, Netzwerkbandbreite, usw.). + +Wenn Sie andererseits über zwei Server verfügen und **100 % ihrer CPU und ihres RAM** nutzen, wird irgendwann ein Prozess nach mehr Speicher fragen und der Server muss die Festplatte als „Speicher“ verwenden (was tausendmal langsamer sein kann) oder er könnte sogar **abstürzen**. Oder ein Prozess muss möglicherweise einige Berechnungen durchführen und müsste warten, bis die CPU wieder frei ist. + +In diesem Fall wäre es besser, **einen zusätzlichen Server** zu besorgen und einige Prozesse darauf auszuführen, damit alle über **genug RAM und CPU-Zeit** verfügen. + +Es besteht auch die Möglichkeit, dass es aus irgendeinem Grund zu **Spitzen** in der Nutzung Ihrer API kommt. Vielleicht ist diese viral gegangen, oder vielleicht haben andere Dienste oder Bots damit begonnen, sie zu nutzen. Und vielleicht möchten Sie in solchen Fällen über zusätzliche Ressourcen verfügen, um auf der sicheren Seite zu sein. + +Sie können eine **beliebige Zahl** festlegen, um beispielsweise eine Ressourcenauslastung zwischen **50 % und 90 %** anzustreben. Der Punkt ist, dass dies wahrscheinlich die wichtigen Dinge sind, die Sie messen und verwenden sollten, um Ihre Deployments zu optimieren. + +Sie können einfache Tools wie `htop` verwenden, um die in Ihrem Server verwendete CPU und den RAM oder die von jedem Prozess verwendete Menge anzuzeigen. Oder Sie können komplexere Überwachungstools verwenden, die möglicherweise auf mehrere Server usw. verteilt sind. + +## Zusammenfassung + +Sie haben hier einige der wichtigsten Konzepte gelesen, die Sie wahrscheinlich berücksichtigen müssen, wenn Sie entscheiden, wie Sie Ihre Anwendung bereitstellen: + +* Sicherheit – HTTPS +* Beim Hochfahren ausführen +* Neustarts +* Replikation (die Anzahl der laufenden Prozesse) +* Arbeitsspeicher +* Schritte vor dem Start + +Das Verständnis dieser Ideen und deren Anwendung sollte Ihnen die nötige Intuition vermitteln, um bei der Konfiguration und Optimierung Ihrer Deployments Entscheidungen zu treffen. 🤓 + +In den nächsten Abschnitten gebe ich Ihnen konkretere Beispiele für mögliche Strategien, die Sie verfolgen können. 🚀 diff --git a/docs/de/docs/deployment/docker.md b/docs/de/docs/deployment/docker.md new file mode 100644 index 0000000000000..b86cf92a4c888 --- /dev/null +++ b/docs/de/docs/deployment/docker.md @@ -0,0 +1,698 @@ +# FastAPI in Containern – Docker + +Beim Deployment von FastAPI-Anwendungen besteht ein gängiger Ansatz darin, ein **Linux-Containerimage** zu erstellen. Normalerweise erfolgt dies mit **Docker**. Sie können dieses Containerimage dann auf eine von mehreren möglichen Arten bereitstellen. + +Die Verwendung von Linux-Containern bietet mehrere Vorteile, darunter **Sicherheit**, **Replizierbarkeit**, **Einfachheit** und andere. + +!!! tip "Tipp" + Sie haben es eilig und kennen sich bereits aus? Springen Sie zum [`Dockerfile` unten 👇](#ein-docker-image-fur-fastapi-erstellen). + +
+Dockerfile-Vorschau 👀 + +```Dockerfile +FROM python:3.9 + +WORKDIR /code + +COPY ./requirements.txt /code/requirements.txt + +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt + +COPY ./app /code/app + +CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] + +# Wenn Sie hinter einem Proxy wie Nginx oder Traefik sind, fügen Sie --proxy-headers hinzu +# CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80", "--proxy-headers"] +``` + +
+ +## Was ist ein Container? + +Container (hauptsächlich Linux-Container) sind eine sehr **leichtgewichtige** Möglichkeit, Anwendungen einschließlich aller ihrer Abhängigkeiten und erforderlichen Dateien zu verpacken und sie gleichzeitig von anderen Containern (anderen Anwendungen oder Komponenten) im selben System isoliert zu halten. + +Linux-Container werden mit demselben Linux-Kernel des Hosts (Maschine, virtuellen Maschine, Cloud-Servers, usw.) ausgeführt. Das bedeutet einfach, dass sie sehr leichtgewichtig sind (im Vergleich zu vollständigen virtuellen Maschinen, die ein gesamtes Betriebssystem emulieren). + +Auf diese Weise verbrauchen Container **wenig Ressourcen**, eine Menge vergleichbar mit der direkten Ausführung der Prozesse (eine virtuelle Maschine würde viel mehr verbrauchen). + +Container verfügen außerdem über ihre eigenen **isoliert** laufenden Prozesse (üblicherweise nur einen Prozess), über ihr eigenes Dateisystem und ihr eigenes Netzwerk, was die Bereitstellung, Sicherheit, Entwicklung usw. vereinfacht. + +## Was ist ein Containerimage? + +Ein **Container** wird von einem **Containerimage** ausgeführt. + +Ein Containerimage ist eine **statische** Version aller Dateien, Umgebungsvariablen und des Standardbefehls/-programms, welche in einem Container vorhanden sein sollten. **Statisch** bedeutet hier, dass das Container-**Image** nicht läuft, nicht ausgeführt wird, sondern nur die gepackten Dateien und Metadaten enthält. + +Im Gegensatz zu einem „**Containerimage**“, bei dem es sich um den gespeicherten statischen Inhalt handelt, bezieht sich ein „**Container**“ normalerweise auf die laufende Instanz, das Ding, das **ausgeführt** wird. + +Wenn der **Container** gestartet und ausgeführt wird (gestartet von einem **Containerimage**), kann er Dateien, Umgebungsvariablen usw. erstellen oder ändern. Diese Änderungen sind nur in diesem Container vorhanden, nicht im zugrunde liegenden bestehen Containerimage (werden nicht auf der Festplatte gespeichert). + +Ein Containerimage ist vergleichbar mit der **Programmdatei** und ihrem Inhalt, z. B. `python` und eine Datei `main.py`. + +Und der **Container** selbst (im Gegensatz zum **Containerimage**) ist die tatsächlich laufende Instanz des Images, vergleichbar mit einem **Prozess**. Tatsächlich läuft ein Container nur, wenn er einen **laufenden Prozess** hat (und normalerweise ist es nur ein einzelner Prozess). Der Container stoppt, wenn kein Prozess darin ausgeführt wird. + +## Containerimages + +Docker ist eines der wichtigsten Tools zum Erstellen und Verwalten von **Containerimages** und **Containern**. + +Und es gibt einen öffentlichen Docker Hub mit vorgefertigten **offiziellen Containerimages** für viele Tools, Umgebungen, Datenbanken und Anwendungen. + +Beispielsweise gibt es ein offizielles Python-Image. + +Und es gibt viele andere Images für verschiedene Dinge wie Datenbanken, zum Beispiel für: + +* PostgreSQL +* MySQL +* MongoDB +* Redis, usw. + +Durch die Verwendung eines vorgefertigten Containerimages ist es sehr einfach, verschiedene Tools zu **kombinieren** und zu verwenden. Zum Beispiel, um eine neue Datenbank auszuprobieren. In den meisten Fällen können Sie die **offiziellen Images** verwenden und diese einfach mit Umgebungsvariablen konfigurieren. + +Auf diese Weise können Sie in vielen Fällen etwas über Container und Docker lernen und dieses Wissen mit vielen verschiedenen Tools und Komponenten wiederverwenden. + +Sie würden also **mehrere Container** mit unterschiedlichen Dingen ausführen, wie einer Datenbank, einer Python-Anwendung, einem Webserver mit einer React-Frontend-Anwendung, und diese über ihr internes Netzwerk miteinander verbinden. + +In alle Containerverwaltungssysteme (wie Docker oder Kubernetes) sind diese Netzwerkfunktionen integriert. + +## Container und Prozesse + +Ein **Containerimage** enthält normalerweise in seinen Metadaten das Standardprogramm oder den Standardbefehl, der ausgeführt werden soll, wenn der **Container** gestartet wird, sowie die Parameter, die an dieses Programm übergeben werden sollen. Sehr ähnlich zu dem, was wäre, wenn es über die Befehlszeile gestartet werden würde. + +Wenn ein **Container** gestartet wird, führt er diesen Befehl/dieses Programm aus (Sie können ihn jedoch überschreiben und einen anderen Befehl/ein anderes Programm ausführen lassen). + +Ein Container läuft, solange der **Hauptprozess** (Befehl oder Programm) läuft. + +Ein Container hat normalerweise einen **einzelnen Prozess**, aber es ist auch möglich, Unterprozesse vom Hauptprozess aus zu starten, und auf diese Weise haben Sie **mehrere Prozesse** im selben Container. + +Es ist jedoch nicht möglich, einen laufenden Container, ohne **mindestens einen laufenden Prozess** zu haben. Wenn der Hauptprozess stoppt, stoppt der Container. + +## Ein Docker-Image für FastAPI erstellen + +Okay, wollen wir jetzt etwas bauen! 🚀 + +Ich zeige Ihnen, wie Sie ein **Docker-Image** für FastAPI **von Grund auf** erstellen, basierend auf dem **offiziellen Python**-Image. + +Das ist, was Sie in **den meisten Fällen** tun möchten, zum Beispiel: + +* Bei Verwendung von **Kubernetes** oder ähnlichen Tools +* Beim Betrieb auf einem **Raspberry Pi** +* Bei Verwendung eines Cloud-Dienstes, der ein Containerimage für Sie ausführt, usw. + +### Paketanforderungen + +Normalerweise befinden sich die **Paketanforderungen** für Ihre Anwendung in einer Datei. + +Dies hängt hauptsächlich von dem Tool ab, mit dem Sie diese Anforderungen **installieren**. + +Die gebräuchlichste Methode besteht darin, eine Datei `requirements.txt` mit den Namen der Packages und deren Versionen zu erstellen, eine pro Zeile. + +Sie würden natürlich die gleichen Ideen verwenden, die Sie in [Über FastAPI-Versionen](versions.md){.internal-link target=_blank} gelesen haben, um die Versionsbereiche festzulegen. + +Ihre `requirements.txt` könnte beispielsweise so aussehen: + +``` +fastapi>=0.68.0,<0.69.0 +pydantic>=1.8.0,<2.0.0 +uvicorn>=0.15.0,<0.16.0 +``` + +Und normalerweise würden Sie diese Paketabhängigkeiten mit `pip` installieren, zum Beispiel: + +
+ +```console +$ pip install -r requirements.txt +---> 100% +Successfully installed fastapi pydantic uvicorn +``` + +
+ +!!! info + Es gibt andere Formate und Tools zum Definieren und Installieren von Paketabhängigkeiten. + + Ich zeige Ihnen später in einem Abschnitt unten ein Beispiel unter Verwendung von Poetry. 👇 + +### Den **FastAPI**-Code erstellen + +* Erstellen Sie ein `app`-Verzeichnis und betreten Sie es. +* Erstellen Sie eine leere Datei `__init__.py`. +* Erstellen Sie eine `main.py`-Datei mit: + +```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} +``` + +### Dockerfile + +Erstellen Sie nun im selben Projektverzeichnis eine Datei `Dockerfile` mit: + +```{ .dockerfile .annotate } +# (1) +FROM python:3.9 + +# (2) +WORKDIR /code + +# (3) +COPY ./requirements.txt /code/requirements.txt + +# (4) +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt + +# (5) +COPY ./app /code/app + +# (6) +CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] +``` + +1. Beginne mit dem offiziellen Python-Basisimage. + +2. Setze das aktuelle Arbeitsverzeichnis auf `/code`. + + Hier plazieren wir die Datei `requirements.txt` und das Verzeichnis `app`. + +3. Kopiere die Datei mit den Paketanforderungen in das Verzeichnis `/code`. + + Kopieren Sie zuerst **nur** die Datei mit den Anforderungen, nicht den Rest des Codes. + + Da sich diese Datei **nicht oft ändert**, erkennt Docker das und verwendet den **Cache** für diesen Schritt, wodurch der Cache auch für den nächsten Schritt aktiviert wird. + +4. Installiere die Paketabhängigkeiten aus der Anforderungsdatei. + + Die Option `--no-cache-dir` weist `pip` an, die heruntergeladenen Pakete nicht lokal zu speichern, da dies nur benötigt wird, sollte `pip` erneut ausgeführt werden, um dieselben Pakete zu installieren, aber das ist beim Arbeiten mit Containern nicht der Fall. + + !!! note "Hinweis" + Das `--no-cache-dir` bezieht sich nur auf `pip`, es hat nichts mit Docker oder Containern zu tun. + + Die Option `--upgrade` weist `pip` an, die Packages zu aktualisieren, wenn sie bereits installiert sind. + + Da der vorherige Schritt des Kopierens der Datei vom **Docker-Cache** erkannt werden konnte, wird dieser Schritt auch **den Docker-Cache verwenden**, sofern verfügbar. + + Durch die Verwendung des Caches in diesem Schritt **sparen** Sie viel **Zeit**, wenn Sie das Image während der Entwicklung immer wieder erstellen, anstatt **jedes Mal** alle Abhängigkeiten **herunterzuladen und zu installieren**. + +5. Kopiere das Verzeichnis `./app` in das Verzeichnis `/code`. + + Da hier der gesamte Code enthalten ist, der sich **am häufigsten ändert**, wird der Docker-**Cache** nicht ohne weiteres für diesen oder andere **folgende Schritte** verwendet. + + Daher ist es wichtig, dies **nahe dem Ende** des `Dockerfile`s zu platzieren, um die Erstellungszeiten des Containerimages zu optimieren. + +6. Lege den **Befehl** fest, um den `uvicorn`-Server zu starten. + + `CMD` nimmt eine Liste von Zeichenfolgen entgegen. Jede dieser Zeichenfolgen entspricht dem, was Sie durch Leerzeichen getrennt in die Befehlszeile eingeben würden. + + Dieser Befehl wird aus dem **aktuellen Arbeitsverzeichnis** ausgeführt, dem gleichen `/code`-Verzeichnis, das Sie oben mit `WORKDIR /code` festgelegt haben. + + Da das Programm unter `/code` gestartet wird und sich darin das Verzeichnis `./app` mit Ihrem Code befindet, kann **Uvicorn** `app` sehen und aus `app.main` **importieren**. + +!!! tip "Tipp" + Lernen Sie, was jede Zeile bewirkt, indem Sie auf die Zahlenblasen im Code klicken. 👆 + +Sie sollten jetzt eine Verzeichnisstruktur wie diese haben: + +``` +. +├── app +│   ├── __init__.py +│ └── main.py +├── Dockerfile +└── requirements.txt +``` + +#### Hinter einem TLS-Terminierungsproxy + +Wenn Sie Ihren Container hinter einem TLS-Terminierungsproxy (Load Balancer) wie Nginx oder Traefik ausführen, fügen Sie die Option `--proxy-headers` hinzu. Das sagt Uvicorn, den von diesem Proxy gesendeten Headern zu vertrauen und dass die Anwendung hinter HTTPS ausgeführt wird, usw. + +```Dockerfile +CMD ["uvicorn", "app.main:app", "--proxy-headers", "--host", "0.0.0.0", "--port", "80"] +``` + +#### Docker-Cache + +In diesem `Dockerfile` gibt es einen wichtigen Trick: Wir kopieren zuerst die **Datei nur mit den Abhängigkeiten**, nicht den Rest des Codes. Lassen Sie mich Ihnen erklären, warum. + +```Dockerfile +COPY ./requirements.txt /code/requirements.txt +``` + +Docker und andere Tools **erstellen** diese Containerimages **inkrementell**, fügen **eine Ebene über der anderen** hinzu, beginnend am Anfang des `Dockerfile`s und fügen alle durch die einzelnen Anweisungen des `Dockerfile`s erstellten Dateien hinzu. + +Docker und ähnliche Tools verwenden beim Erstellen des Images auch einen **internen Cache**. Wenn sich eine Datei seit der letzten Erstellung des Containerimages nicht geändert hat, wird **dieselbe Ebene wiederverwendet**, die beim letzten Mal erstellt wurde, anstatt die Datei erneut zu kopieren und eine neue Ebene von Grund auf zu erstellen. + +Das bloße Vermeiden des Kopierens von Dateien führt nicht unbedingt zu einer großen Verbesserung, aber da der Cache für diesen Schritt verwendet wurde, kann **der Cache für den nächsten Schritt verwendet werden**. Beispielsweise könnte der Cache verwendet werden für die Anweisung, welche die Abhängigkeiten installiert mit: + +```Dockerfile +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt +``` + +Die Datei mit den Paketanforderungen wird sich **nicht häufig ändern**. Wenn Docker also nur diese Datei kopiert, kann es für diesen Schritt **den Cache verwenden**. + +Und dann kann Docker **den Cache für den nächsten Schritt verwenden**, der diese Abhängigkeiten herunterlädt und installiert. Und hier **sparen wir viel Zeit**. ✨ ... und vermeiden die Langeweile beim Warten. 😪😆 + +Das Herunterladen und Installieren der Paketabhängigkeiten **könnte Minuten dauern**, aber die Verwendung des **Cache** würde höchstens **Sekunden** dauern. + +Und da Sie das Containerimage während der Entwicklung immer wieder erstellen würden, um zu überprüfen, ob Ihre Codeänderungen funktionieren, würde dies viel Zeit sparen. + +Dann, gegen Ende des `Dockerfile`s, kopieren wir den gesamten Code. Da sich der **am häufigsten ändert**, platzieren wir das am Ende, da fast immer alles nach diesem Schritt nicht mehr in der Lage sein wird, den Cache zu verwenden. + +```Dockerfile +COPY ./app /code/app +``` + +### Das Docker-Image erstellen + +Nachdem nun alle Dateien vorhanden sind, erstellen wir das Containerimage. + +* Gehen Sie zum Projektverzeichnis (dort, wo sich Ihr `Dockerfile` und Ihr `app`-Verzeichnis befindet). +* Erstellen Sie Ihr FastAPI-Image: + +
+ +```console +$ docker build -t myimage . + +---> 100% +``` + +
+ +!!! tip "Tipp" + Beachten Sie das `.` am Ende, es entspricht `./` und teilt Docker mit, welches Verzeichnis zum Erstellen des Containerimages verwendet werden soll. + + In diesem Fall handelt es sich um dasselbe aktuelle Verzeichnis (`.`). + +### Den Docker-Container starten + +* Führen Sie einen Container basierend auf Ihrem Image aus: + +
+ +```console +$ docker run -d --name mycontainer -p 80:80 myimage +``` + +
+ +## Es überprüfen + +Sie sollten es in der URL Ihres Docker-Containers überprüfen können, zum Beispiel: http://192.168.99.100/items/5?q=somequery oder http://127.0.0.1/items/5?q=somequery (oder gleichwertig, unter Verwendung Ihres Docker-Hosts). + +Sie werden etwas sehen wie: + +```JSON +{"item_id": 5, "q": "somequery"} +``` + +## Interaktive API-Dokumentation + +Jetzt können Sie auf http://192.168.99.100/docs oder http://127.0.0.1/docs gehen (oder ähnlich, unter Verwendung Ihres Docker-Hosts). + +Sie sehen die automatische interaktive API-Dokumentation (bereitgestellt von Swagger UI): + +![Swagger-Oberfläche](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +## Alternative API-Dokumentation + +Sie können auch auf http://192.168.99.100/redoc oder http://127.0.0.1/redoc gehen (oder ähnlich, unter Verwendung Ihres Docker-Hosts). + +Sie sehen die alternative automatische Dokumentation (bereitgestellt von ReDoc): + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +## Ein Docker-Image mit einem Single-File-FastAPI erstellen + +Wenn Ihr FastAPI eine einzelne Datei ist, zum Beispiel `main.py` ohne ein `./app`-Verzeichnis, könnte Ihre Dateistruktur wie folgt aussehen: + +``` +. +├── Dockerfile +├── main.py +└── requirements.txt +``` + +Dann müssten Sie nur noch die entsprechenden Pfade ändern, um die Datei im `Dockerfile` zu kopieren: + +```{ .dockerfile .annotate hl_lines="10 13" } +FROM python:3.9 + +WORKDIR /code + +COPY ./requirements.txt /code/requirements.txt + +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt + +# (1) +COPY ./main.py /code/ + +# (2) +CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] +``` + +1. Kopiere die Datei `main.py` direkt in das Verzeichnis `/code` (ohne ein Verzeichnis `./app`). + +2. Führe Uvicorn aus und weisen es an, das `app`-Objekt von `main` zu importieren (anstatt von `app.main` zu importieren). + +Passen Sie dann den Uvicorn-Befehl an, um das neue Modul `main` anstelle von `app.main` zu verwenden, um das FastAPI-Objekt `app` zu importieren. + +## Deployment-Konzepte + +Lassen Sie uns noch einmal über einige der gleichen [Deployment-Konzepte](concepts.md){.internal-link target=_blank} in Bezug auf Container sprechen. + +Container sind hauptsächlich ein Werkzeug, um den Prozess des **Erstellens und Deployments** einer Anwendung zu vereinfachen, sie erzwingen jedoch keinen bestimmten Ansatz für die Handhabung dieser **Deployment-Konzepte**, und es gibt mehrere mögliche Strategien. + +Die **gute Nachricht** ist, dass es mit jeder unterschiedlichen Strategie eine Möglichkeit gibt, alle Deployment-Konzepte abzudecken. 🎉 + +Sehen wir uns diese **Deployment-Konzepte** im Hinblick auf Container noch einmal an: + +* Sicherheit – HTTPS +* Beim Hochfahren ausführen +* Neustarts +* Replikation (die Anzahl der laufenden Prozesse) +* Arbeitsspeicher +* Schritte vor dem Start + +## HTTPS + +Wenn wir uns nur auf das **Containerimage** für eine FastAPI-Anwendung (und später auf den laufenden **Container**) konzentrieren, würde HTTPS normalerweise **extern** von einem anderen Tool verarbeitet. + +Es könnte sich um einen anderen Container handeln, zum Beispiel mit Traefik, welcher **HTTPS** und **automatischen** Erwerb von **Zertifikaten** handhabt. + +!!! tip "Tipp" + Traefik verfügt über Integrationen mit Docker, Kubernetes und anderen, sodass Sie damit ganz einfach HTTPS für Ihre Container einrichten und konfigurieren können. + +Alternativ könnte HTTPS von einem Cloud-Anbieter als einer seiner Dienste gehandhabt werden (während die Anwendung weiterhin in einem Container ausgeführt wird). + +## Beim Hochfahren ausführen und Neustarts + +Normalerweise gibt es ein anderes Tool, das für das **Starten und Ausführen** Ihres Containers zuständig ist. + +Es könnte sich um **Docker** direkt, **Docker Compose**, **Kubernetes**, einen **Cloud-Dienst**, usw. handeln. + +In den meisten (oder allen) Fällen gibt es eine einfache Option, um die Ausführung des Containers beim Hochfahren und Neustarts bei Fehlern zu ermöglichen. In Docker ist es beispielsweise die Befehlszeilenoption `--restart`. + +Ohne die Verwendung von Containern kann es umständlich und schwierig sein, Anwendungen beim Hochfahren auszuführen und neu zu starten. Bei der **Arbeit mit Containern** ist diese Funktionalität jedoch in den meisten Fällen standardmäßig enthalten. ✨ + +## Replikation – Anzahl der Prozesse + +Wenn Sie einen Cluster von Maschinen mit **Kubernetes**, Docker Swarm Mode, Nomad verwenden, oder einem anderen, ähnlich komplexen System zur Verwaltung verteilter Container auf mehreren Maschinen, möchten Sie wahrscheinlich die **Replikation auf Cluster-Ebene abwickeln**, anstatt in jedem Container einen **Prozessmanager** (wie Gunicorn mit Workern) zu verwenden. + +Diese verteilten Containerverwaltungssysteme wie Kubernetes verfügen normalerweise über eine integrierte Möglichkeit, die **Replikation von Containern** zu handhaben und gleichzeitig **Load Balancing** für die eingehenden Requests zu unterstützen. Alles auf **Cluster-Ebene**. + +In diesen Fällen möchten Sie wahrscheinlich ein **Docker-Image von Grund auf** erstellen, wie [oben erklärt](#dockerfile), Ihre Abhängigkeiten installieren und **einen einzelnen Uvicorn-Prozess** ausführen, anstatt etwas wie Gunicorn mit Uvicorn-Workern auszuführen. + +### Load Balancer + +Bei der Verwendung von Containern ist normalerweise eine Komponente vorhanden, **die am Hauptport lauscht**. Es könnte sich um einen anderen Container handeln, der auch ein **TLS-Terminierungsproxy** ist, um **HTTPS** zu verarbeiten, oder ein ähnliches Tool. + +Da diese Komponente die **Last** an Requests aufnehmen und diese (hoffentlich) **ausgewogen** auf die Worker verteilen würde, wird sie üblicherweise auch **Load Balancer** – Lastverteiler – genannt. + +!!! tip "Tipp" + Die gleiche **TLS-Terminierungsproxy**-Komponente, die für HTTPS verwendet wird, wäre wahrscheinlich auch ein **Load Balancer**. + +Und wenn Sie mit Containern arbeiten, verfügt das gleiche System, mit dem Sie diese starten und verwalten, bereits über interne Tools, um die **Netzwerkkommunikation** (z. B. HTTP-Requests) von diesem **Load Balancer** (das könnte auch ein **TLS-Terminierungsproxy** sein) zu den Containern mit Ihrer Anwendung weiterzuleiten. + +### Ein Load Balancer – mehrere Workercontainer + +Bei der Arbeit mit **Kubernetes** oder ähnlichen verteilten Containerverwaltungssystemen würde die Verwendung ihrer internen Netzwerkmechanismen es dem einzelnen **Load Balancer**, der den Haupt-**Port** überwacht, ermöglichen, Kommunikation (Requests) an möglicherweise **mehrere Container** weiterzuleiten, in denen Ihre Anwendung ausgeführt wird. + +Jeder dieser Container, in denen Ihre Anwendung ausgeführt wird, verfügt normalerweise über **nur einen Prozess** (z. B. einen Uvicorn-Prozess, der Ihre FastAPI-Anwendung ausführt). Es wären alles **identische Container**, die das Gleiche ausführen, welche aber jeweils über einen eigenen Prozess, Speicher, usw. verfügen. Auf diese Weise würden Sie die **Parallelisierung** in **verschiedenen Kernen** der CPU nutzen. Oder sogar in **verschiedenen Maschinen**. + +Und das verteilte Containersystem mit dem **Load Balancer** würde **die Requests abwechselnd** an jeden einzelnen Container mit Ihrer Anwendung verteilen. Jeder Request könnte also von einem der mehreren **replizierten Container** verarbeitet werden, in denen Ihre Anwendung ausgeführt wird. + +Und normalerweise wäre dieser **Load Balancer** in der Lage, Requests zu verarbeiten, die an *andere* Anwendungen in Ihrem Cluster gerichtet sind (z. B. eine andere Domain oder unter einem anderen URL-Pfad-Präfix), und würde diese Kommunikation an die richtigen Container weiterleiten für *diese andere* Anwendung, die in Ihrem Cluster ausgeführt wird. + +### Ein Prozess pro Container + +In einem solchen Szenario möchten Sie wahrscheinlich **einen einzelnen (Uvicorn-)Prozess pro Container** haben, da Sie die Replikation bereits auf Cluster ebene durchführen würden. + +In diesem Fall möchten Sie also **nicht** einen Prozessmanager wie Gunicorn mit Uvicorn-Workern oder Uvicorn mit seinen eigenen Uvicorn-Workern haben. Sie möchten nur einen **einzelnen Uvicorn-Prozess** pro Container haben (wahrscheinlich aber mehrere Container). + +Ein weiterer Prozessmanager im Container (wie es bei Gunicorn oder Uvicorn der Fall wäre, welche Uvicorn-Worker verwalten) würde nur **unnötige Komplexität** hinzufügen, um welche Sie sich höchstwahrscheinlich bereits mit Ihrem Clustersystem kümmern. + +### Container mit mehreren Prozessen und Sonderfälle + +Natürlich gibt es **Sonderfälle**, in denen Sie **einen Container** mit einem **Gunicorn-Prozessmanager** haben möchten, welcher mehrere **Uvicorn-Workerprozesse** darin startet. + +In diesen Fällen können Sie das **offizielle Docker-Image** verwenden, welches **Gunicorn** als Prozessmanager enthält, welcher mehrere **Uvicorn-Workerprozesse** ausführt, sowie einige Standardeinstellungen, um die Anzahl der Worker basierend auf den verfügbaren CPU-Kernen automatisch anzupassen. Ich erzähle Ihnen weiter unten in [Offizielles Docker-Image mit Gunicorn – Uvicorn](#offizielles-docker-image-mit-gunicorn-uvicorn) mehr darüber. + +Hier sind einige Beispiele, wann das sinnvoll sein könnte: + +#### Eine einfache Anwendung + +Sie könnten einen Prozessmanager im Container haben wollen, wenn Ihre Anwendung **einfach genug** ist, sodass Sie die Anzahl der Prozesse nicht (zumindest noch nicht) zu stark tunen müssen und Sie einfach einen automatisierten Standard verwenden können (mit dem offiziellen Docker-Image), und Sie führen es auf einem **einzelnen Server** aus, nicht auf einem Cluster. + +#### Docker Compose + +Sie könnten das Deployment auf einem **einzelnen Server** (kein Cluster) mit **Docker Compose** durchführen, sodass Sie keine einfache Möglichkeit hätten, die Replikation von Containern (mit Docker Compose) zu verwalten und gleichzeitig das gemeinsame Netzwerk mit **Load Balancing** zu haben. + +Dann möchten Sie vielleicht **einen einzelnen Container** mit einem **Prozessmanager** haben, der darin **mehrere Workerprozesse** startet. + +#### Prometheus und andere Gründe + +Sie könnten auch **andere Gründe** haben, die es einfacher machen würden, einen **einzelnen Container** mit **mehreren Prozessen** zu haben, anstatt **mehrere Container** mit **einem einzelnen Prozess** in jedem von ihnen. + +Beispielsweise könnten Sie (abhängig von Ihrem Setup) ein Tool wie einen Prometheus-Exporter im selben Container haben, welcher Zugriff auf **jeden der eingehenden Requests** haben sollte. + +Wenn Sie in hier **mehrere Container** hätten, würde Prometheus beim **Lesen der Metriken** standardmäßig jedes Mal diejenigen für **einen einzelnen Container** abrufen (für den Container, der den spezifischen Request verarbeitet hat), anstatt die **akkumulierten Metriken** für alle replizierten Container abzurufen. + +In diesem Fall könnte einfacher sein, **einen Container** mit **mehreren Prozessen** und ein lokales Tool (z. B. einen Prometheus-Exporter) in demselben Container zu haben, welches Prometheus-Metriken für alle internen Prozesse sammelt und diese Metriken für diesen einzelnen Container offenlegt. + +--- + +Der Hauptpunkt ist, dass **keine** dieser Regeln **in Stein gemeißelt** ist, der man blind folgen muss. Sie können diese Ideen verwenden, um **Ihren eigenen Anwendungsfall zu evaluieren**, zu entscheiden, welcher Ansatz für Ihr System am besten geeignet ist und herauszufinden, wie Sie folgende Konzepte verwalten: + +* Sicherheit – HTTPS +* Beim Hochfahren ausführen +* Neustarts +* Replikation (die Anzahl der laufenden Prozesse) +* Arbeitsspeicher +* Schritte vor dem Start + +## Arbeitsspeicher + +Wenn Sie **einen einzelnen Prozess pro Container** ausführen, wird von jedem dieser Container (mehr als einer, wenn sie repliziert werden) eine mehr oder weniger klar definierte, stabile und begrenzte Menge an Arbeitsspeicher verbraucht. + +Und dann können Sie dieselben Speichergrenzen und -anforderungen in Ihren Konfigurationen für Ihr Container-Management-System festlegen (z. B. in **Kubernetes**). Auf diese Weise ist es in der Lage, die Container auf den **verfügbaren Maschinen** zu replizieren, wobei die von denen benötigte Speichermenge und die auf den Maschinen im Cluster verfügbare Menge berücksichtigt werden. + +Wenn Ihre Anwendung **einfach** ist, wird dies wahrscheinlich **kein Problem darstellen** und Sie müssen möglicherweise keine festen Speichergrenzen angeben. Wenn Sie jedoch **viel Speicher verbrauchen** (z. B. bei **Modellen für maschinelles Lernen**), sollten Sie überprüfen, wie viel Speicher Sie verbrauchen, und die **Anzahl der Container** anpassen, die in **jeder Maschine** ausgeführt werden. (und möglicherweise weitere Maschinen zu Ihrem Cluster hinzufügen). + +Wenn Sie **mehrere Prozesse pro Container** ausführen (zum Beispiel mit dem offiziellen Docker-Image), müssen Sie sicherstellen, dass die Anzahl der gestarteten Prozesse nicht **mehr Speicher verbraucht** als verfügbar ist. + +## Schritte vor dem Start und Container + +Wenn Sie Container (z. B. Docker, Kubernetes) verwenden, können Sie hauptsächlich zwei Ansätze verwenden. + +### Mehrere Container + +Wenn Sie **mehrere Container** haben, von denen wahrscheinlich jeder einen **einzelnen Prozess** ausführt (z. B. in einem **Kubernetes**-Cluster), dann möchten Sie wahrscheinlich einen **separaten Container** haben, welcher die Arbeit der **Vorab-Schritte** in einem einzelnen Container, mit einem einzelnenen Prozess ausführt, **bevor** die replizierten Workercontainer ausgeführt werden. + +!!! info + Wenn Sie Kubernetes verwenden, wäre dies wahrscheinlich ein Init-Container. + +Wenn es in Ihrem Anwendungsfall kein Problem darstellt, diese vorherigen Schritte **mehrmals parallel** auszuführen (z. B. wenn Sie keine Datenbankmigrationen ausführen, sondern nur prüfen, ob die Datenbank bereits bereit ist), können Sie sie auch einfach in jedem Container direkt vor dem Start des Hauptprozesses einfügen. + +### Einzelner Container + +Wenn Sie ein einfaches Setup mit einem **einzelnen Container** haben, welcher dann mehrere **Workerprozesse** (oder auch nur einen Prozess) startet, können Sie die Vorab-Schritte im selben Container direkt vor dem Starten des Prozesses mit der Anwendung ausführen. Das offizielle Docker-Image unterstützt das intern. + +## Offizielles Docker-Image mit Gunicorn – Uvicorn + +Es gibt ein offizielles Docker-Image, in dem Gunicorn mit Uvicorn-Workern ausgeführt wird, wie in einem vorherigen Kapitel beschrieben: [Serverworker – Gunicorn mit Uvicorn](server-workers.md){.internal-link target=_blank}. + +Dieses Image wäre vor allem in den oben beschriebenen Situationen nützlich: [Container mit mehreren Prozessen und Sonderfälle](#container-mit-mehreren-prozessen-und-sonderfalle). + +* tiangolo/uvicorn-gunicorn-fastapi. + +!!! warning "Achtung" + Es besteht eine hohe Wahrscheinlichkeit, dass Sie dieses oder ein ähnliches Basisimage **nicht** benötigen und es besser wäre, wenn Sie das Image von Grund auf neu erstellen würden, wie [oben beschrieben in: Ein Docker-Image für FastAPI erstellen](#ein-docker-image-fur-fastapi-erstellen). + +Dieses Image verfügt über einen **Auto-Tuning**-Mechanismus, um die **Anzahl der Arbeitsprozesse** basierend auf den verfügbaren CPU-Kernen festzulegen. + +Es verfügt über **vernünftige Standardeinstellungen**, aber Sie können trotzdem alle Konfigurationen mit **Umgebungsvariablen** oder Konfigurationsdateien ändern und aktualisieren. + +Es unterstützt auch die Ausführung von **Vorab-Schritten vor dem Start** mit einem Skript. + +!!! tip "Tipp" + Um alle Konfigurationen und Optionen anzuzeigen, gehen Sie zur Docker-Image-Seite: tiangolo/uvicorn-gunicorn-fastapi. + +### Anzahl der Prozesse auf dem offiziellen Docker-Image + +Die **Anzahl der Prozesse** auf diesem Image wird **automatisch** anhand der verfügbaren CPU-**Kerne** berechnet. + +Das bedeutet, dass versucht wird, so viel **Leistung** wie möglich aus der CPU herauszuquetschen. + +Sie können das auch in der Konfiguration anpassen, indem Sie **Umgebungsvariablen**, usw. verwenden. + +Das bedeutet aber auch, da die Anzahl der Prozesse von der CPU abhängt, welche der Container ausführt, dass die **Menge des verbrauchten Speichers** ebenfalls davon abhängt. + +Wenn Ihre Anwendung also viel Speicher verbraucht (z. B. bei Modellen für maschinelles Lernen) und Ihr Server über viele CPU-Kerne, **aber wenig Speicher** verfügt, könnte Ihr Container am Ende versuchen, mehr Speicher als vorhanden zu verwenden, was zu erheblichen Leistungseinbußen (oder sogar zum Absturz) führen kann. 🚨 + +### Ein `Dockerfile` erstellen + +So würden Sie ein `Dockerfile` basierend auf diesem Image erstellen: + +```Dockerfile +FROM tiangolo/uvicorn-gunicorn-fastapi:python3.9 + +COPY ./requirements.txt /app/requirements.txt + +RUN pip install --no-cache-dir --upgrade -r /app/requirements.txt + +COPY ./app /app +``` + +### Größere Anwendungen + +Wenn Sie dem Abschnitt zum Erstellen von [größeren Anwendungen mit mehreren Dateien](../tutorial/bigger-applications.md){.internal-link target=_blank} gefolgt sind, könnte Ihr `Dockerfile` stattdessen wie folgt aussehen: + +```Dockerfile hl_lines="7" +FROM tiangolo/uvicorn-gunicorn-fastapi:python3.9 + +COPY ./requirements.txt /app/requirements.txt + +RUN pip install --no-cache-dir --upgrade -r /app/requirements.txt + +COPY ./app /app/app +``` + +### Wann verwenden + +Sie sollten dieses offizielle Basisimage (oder ein ähnliches) wahrscheinlich **nicht** benutzen, wenn Sie **Kubernetes** (oder andere) verwenden und Sie bereits **Replikation** auf Cluster ebene mit mehreren **Containern** eingerichtet haben. In diesen Fällen ist es besser, **ein Image von Grund auf zu erstellen**, wie oben beschrieben: [Ein Docker-Image für FastAPI erstellen](#ein-docker-image-fur-fastapi-erstellen). + +Dieses Image wäre vor allem in den oben in [Container mit mehreren Prozessen und Sonderfälle](#container-mit-mehreren-prozessen-und-sonderfalle) beschriebenen Sonderfällen nützlich. Wenn Ihre Anwendung beispielsweise **einfach genug** ist, dass das Festlegen einer Standardanzahl von Prozessen basierend auf der CPU gut funktioniert, möchten Sie sich nicht mit der manuellen Konfiguration der Replikation auf Cluster ebene herumschlagen und führen nicht mehr als einen Container mit Ihrer Anwendung aus. Oder wenn Sie das Deployment mit **Docker Compose** durchführen und auf einem einzelnen Server laufen, usw. + +## Deployment des Containerimages + +Nachdem Sie ein Containerimage (Docker) haben, gibt es mehrere Möglichkeiten, es bereitzustellen. + +Zum Beispiel: + +* Mit **Docker Compose** auf einem einzelnen Server +* Mit einem **Kubernetes**-Cluster +* Mit einem Docker Swarm Mode-Cluster +* Mit einem anderen Tool wie Nomad +* Mit einem Cloud-Dienst, der Ihr Containerimage nimmt und es bereitstellt + +## Docker-Image mit Poetry + +Wenn Sie Poetry verwenden, um die Abhängigkeiten Ihres Projekts zu verwalten, können Sie Dockers mehrphasige Builds verwenden: + +```{ .dockerfile .annotate } +# (1) +FROM python:3.9 as requirements-stage + +# (2) +WORKDIR /tmp + +# (3) +RUN pip install poetry + +# (4) +COPY ./pyproject.toml ./poetry.lock* /tmp/ + +# (5) +RUN poetry export -f requirements.txt --output requirements.txt --without-hashes + +# (6) +FROM python:3.9 + +# (7) +WORKDIR /code + +# (8) +COPY --from=requirements-stage /tmp/requirements.txt /code/requirements.txt + +# (9) +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt + +# (10) +COPY ./app /code/app + +# (11) +CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] +``` + +1. Dies ist die erste Phase, genannt `requirements-stage` – „Anforderungsphase“. + +2. Setze `/tmp` als aktuelles Arbeitsverzeichnis. + + Hier werden wir die Datei `requirements.txt` generieren. + +3. Installiere Poetry in dieser Docker-Phase. + +4. Kopiere die Dateien `pyproject.toml` und `poetry.lock` in das Verzeichnis `/tmp`. + + Da es `./poetry.lock*` verwendet (endet mit einem `*`), stürzt es nicht ab, wenn diese Datei noch nicht verfügbar ist. + +5. Generiere die Datei `requirements.txt`. + +6. Dies ist die letzte Phase. Alles hier bleibt im endgültigen Containerimage erhalten. + +7. Setze das aktuelle Arbeitsverzeichnis auf `/code`. + +8. Kopiere die Datei `requirements.txt` in das Verzeichnis `/code`. + + Diese Datei existiert nur in der vorherigen Docker-Phase, deshalb verwenden wir `--from-requirements-stage`, um sie zu kopieren. + +9. Installiere die Paketabhängigkeiten von der generierten Datei `requirements.txt`. + +10. Kopiere das Verzeichnis `app` in das Verzeichnis `/code`. + +11. Führe den Befehl `uvicorn` aus und weise ihn an, das aus `app.main` importierte `app`-Objekt zu verwenden. + +!!! tip "Tipp" + Klicken Sie auf die Zahlenblasen, um zu sehen, was jede Zeile bewirkt. + +Eine **Docker-Phase** ist ein Teil eines `Dockerfile`s, welcher als **temporäres Containerimage** fungiert und nur zum Generieren einiger Dateien für die spätere Verwendung verwendet wird. + +Die erste Phase wird nur zur **Installation von Poetry** und zur **Generierung der `requirements.txt`** mit deren Projektabhängigkeiten aus der Datei `pyproject.toml` von Poetry verwendet. + +Diese `requirements.txt`-Datei wird später in der **nächsten Phase** mit `pip` verwendet. + +Im endgültigen Containerimage bleibt **nur die letzte Stufe** erhalten. Die vorherigen Stufen werden verworfen. + +Bei der Verwendung von Poetry wäre es sinnvoll, **mehrstufige Docker-Builds** zu verwenden, da Poetry und seine Abhängigkeiten nicht wirklich im endgültigen Containerimage installiert sein müssen, sondern Sie brauchen **nur** die Datei `requirements.txt`, um Ihre Projektabhängigkeiten zu installieren. + +Dann würden Sie im nächsten (und letzten) Schritt das Image mehr oder weniger auf die gleiche Weise wie zuvor beschrieben erstellen. + +### Hinter einem TLS-Terminierungsproxy – Poetry + +Auch hier gilt: Wenn Sie Ihren Container hinter einem TLS-Terminierungsproxy (Load Balancer) wie Nginx oder Traefik ausführen, fügen Sie dem Befehl die Option `--proxy-headers` hinzu: + +```Dockerfile +CMD ["uvicorn", "app.main:app", "--proxy-headers", "--host", "0.0.0.0", "--port", "80"] +``` + +## Zusammenfassung + +Mithilfe von Containersystemen (z. B. mit **Docker** und **Kubernetes**) ist es ziemlich einfach, alle **Deployment-Konzepte** zu handhaben: + +* HTTPS +* Beim Hochfahren ausführen +* Neustarts +* Replikation (die Anzahl der laufenden Prozesse) +* Arbeitsspeicher +* Schritte vor dem Start + +In den meisten Fällen möchten Sie wahrscheinlich kein Basisimage verwenden und stattdessen **ein Containerimage von Grund auf erstellen**, eines basierend auf dem offiziellen Python-Docker-Image. + +Indem Sie auf die **Reihenfolge** der Anweisungen im `Dockerfile` und den **Docker-Cache** achten, können Sie **die Build-Zeiten minimieren**, um Ihre Produktivität zu erhöhen (und Langeweile zu vermeiden). 😎 + +In bestimmten Sonderfällen möchten Sie möglicherweise das offizielle Docker-Image für FastAPI verwenden. 🤓 diff --git a/docs/de/docs/deployment/https.md b/docs/de/docs/deployment/https.md new file mode 100644 index 0000000000000..3ebe59af24887 --- /dev/null +++ b/docs/de/docs/deployment/https.md @@ -0,0 +1,190 @@ +# Über HTTPS + +Es ist leicht anzunehmen, dass HTTPS etwas ist, was einfach nur „aktiviert“ wird oder nicht. + +Aber es ist viel komplexer als das. + +!!! tip "Tipp" + Wenn Sie es eilig haben oder es Ihnen egal ist, fahren Sie mit den nächsten Abschnitten fort, um Schritt-für-Schritt-Anleitungen für die Einrichtung der verschiedenen Technologien zu erhalten. + +Um **die Grundlagen von HTTPS** aus Sicht des Benutzers zu erlernen, schauen Sie sich https://howhttps.works/ an. + +Aus **Sicht des Entwicklers** sollten Sie beim Nachdenken über HTTPS Folgendes beachten: + +* Für HTTPS muss **der Server** über von einem **Dritten** generierte **„Zertifikate“** verfügen. + * Diese Zertifikate werden tatsächlich vom Dritten **erworben** und nicht „generiert“. +* Zertifikate haben eine **Lebensdauer**. + * Sie **verfallen**. + * Und dann müssen sie vom Dritten **erneuert**, **erneut erworben** werden. +* Die Verschlüsselung der Verbindung erfolgt auf **TCP-Ebene**. + * Das ist eine Schicht **unter HTTP**. + * Die Handhabung von **Zertifikaten und Verschlüsselung** erfolgt also **vor HTTP**. +* **TCP weiß nichts über „Domains“**. Nur über IP-Adressen. + * Die Informationen über die angeforderte **spezifische Domain** befinden sich in den **HTTP-Daten**. +* Die **HTTPS-Zertifikate** „zertifizieren“ eine **bestimmte Domain**, aber das Protokoll und die Verschlüsselung erfolgen auf TCP-Ebene, **ohne zu wissen**, um welche Domain es sich handelt. +* **Standardmäßig** bedeutet das, dass Sie nur **ein HTTPS-Zertifikat pro IP-Adresse** haben können. + * Ganz gleich, wie groß Ihr Server ist oder wie klein die einzelnen Anwendungen darauf sind. + * Hierfür gibt es jedoch eine **Lösung**. +* Es gibt eine **Erweiterung** zum **TLS**-Protokoll (dasjenige, das die Verschlüsselung auf TCP-Ebene, vor HTTP, verwaltet) namens **SNI**. + * Mit dieser SNI-Erweiterung kann ein einzelner Server (mit einer **einzelnen IP-Adresse**) über **mehrere HTTPS-Zertifikate** verfügen und **mehrere HTTPS-Domains/Anwendungen** bedienen. + * Damit das funktioniert, muss eine **einzelne** Komponente (Programm), die auf dem Server ausgeführt wird und welche die **öffentliche IP-Adresse** überwacht, **alle HTTPS-Zertifikate** des Servers haben. +* **Nachdem** eine sichere Verbindung hergestellt wurde, ist das Kommunikationsprotokoll **immer noch HTTP**. + * Die Inhalte sind **verschlüsselt**, auch wenn sie mit dem **HTTP-Protokoll** gesendet werden. + +Es ist eine gängige Praxis, **ein Programm/HTTP-Server** auf dem Server (der Maschine, dem Host usw.) laufen zu lassen, welches **alle HTTPS-Aspekte verwaltet**: Empfangen der **verschlüsselten HTTPS-Requests**, Senden der **entschlüsselten HTTP-Requests** an die eigentliche HTTP-Anwendung die auf demselben Server läuft (in diesem Fall die **FastAPI**-Anwendung), entgegennehmen der **HTTP-Response** von der Anwendung, **verschlüsseln derselben** mithilfe des entsprechenden **HTTPS-Zertifikats** und Zurücksenden zum Client über **HTTPS**. Dieser Server wird oft als **TLS-Terminierungsproxy** bezeichnet. + +Einige der Optionen, die Sie als TLS-Terminierungsproxy verwenden können, sind: + +* Traefik (kann auch Zertifikat-Erneuerungen durchführen) +* Caddy (kann auch Zertifikat-Erneuerungen durchführen) +* Nginx +* HAProxy + +## Let's Encrypt + +Vor Let's Encrypt wurden diese **HTTPS-Zertifikate** von vertrauenswürdigen Dritten verkauft. + +Der Prozess zum Erwerb eines dieser Zertifikate war früher umständlich, erforderte viel Papierarbeit und die Zertifikate waren ziemlich teuer. + +Aber dann wurde **Let's Encrypt** geschaffen. + +Es ist ein Projekt der Linux Foundation. Es stellt **kostenlose HTTPS-Zertifikate** automatisiert zur Verfügung. Diese Zertifikate nutzen standardmäßig die gesamte kryptografische Sicherheit und sind kurzlebig (circa 3 Monate), sodass die **Sicherheit tatsächlich besser ist**, aufgrund der kürzeren Lebensdauer. + +Die Domains werden sicher verifiziert und die Zertifikate werden automatisch generiert. Das ermöglicht auch die automatische Erneuerung dieser Zertifikate. + +Die Idee besteht darin, den Erwerb und die Erneuerung der Zertifikate zu automatisieren, sodass Sie **sicheres HTTPS, kostenlos und für immer** haben können. + +## HTTPS für Entwickler + +Hier ist ein Beispiel, wie eine HTTPS-API aussehen könnte, Schritt für Schritt, wobei vor allem die für Entwickler wichtigen Ideen berücksichtigt werden. + +### Domainname + +Alles beginnt wahrscheinlich damit, dass Sie einen **Domainnamen erwerben**. Anschließend konfigurieren Sie ihn in einem DNS-Server (wahrscheinlich beim selben Cloud-Anbieter). + +Sie würden wahrscheinlich einen Cloud-Server (eine virtuelle Maschine) oder etwas Ähnliches bekommen, und dieser hätte eine feste **öffentliche IP-Adresse**. + +In dem oder den DNS-Server(n) würden Sie einen Eintrag (einen „`A record`“) konfigurieren, um mit **Ihrer Domain** auf die öffentliche **IP-Adresse Ihres Servers** zu verweisen. + +Sie würden dies wahrscheinlich nur einmal tun, beim ersten Mal, wenn Sie alles einrichten. + +!!! tip "Tipp" + Dieser Domainnamen-Aspekt liegt weit vor HTTPS, aber da alles von der Domain und der IP-Adresse abhängt, lohnt es sich, das hier zu erwähnen. + +### DNS + +Konzentrieren wir uns nun auf alle tatsächlichen HTTPS-Aspekte. + +Zuerst würde der Browser mithilfe der **DNS-Server** herausfinden, welches die **IP für die Domain** ist, in diesem Fall für `someapp.example.com`. + +Die DNS-Server geben dem Browser eine bestimmte **IP-Adresse** zurück. Das wäre die von Ihrem Server verwendete öffentliche IP-Adresse, die Sie in den DNS-Servern konfiguriert haben. + + + +### TLS-Handshake-Start + +Der Browser kommuniziert dann mit dieser IP-Adresse über **Port 443** (den HTTPS-Port). + +Der erste Teil der Kommunikation besteht lediglich darin, die Verbindung zwischen dem Client und dem Server herzustellen und die zu verwendenden kryptografischen Schlüssel usw. zu vereinbaren. + + + +Diese Interaktion zwischen dem Client und dem Server zum Aufbau der TLS-Verbindung wird als **TLS-Handshake** bezeichnet. + +### TLS mit SNI-Erweiterung + +**Nur ein Prozess** im Server kann an einem bestimmten **Port** einer bestimmten **IP-Adresse** lauschen. Möglicherweise gibt es andere Prozesse, die an anderen Ports dieselbe IP-Adresse abhören, jedoch nur einen für jede Kombination aus IP-Adresse und Port. + +TLS (HTTPS) verwendet standardmäßig den spezifischen Port `443`. Das ist also der Port, den wir brauchen. + +Da an diesem Port nur ein Prozess lauschen kann, wäre der Prozess, der dies tun würde, der **TLS-Terminierungsproxy**. + +Der TLS-Terminierungsproxy hätte Zugriff auf ein oder mehrere **TLS-Zertifikate** (HTTPS-Zertifikate). + +Mithilfe der oben beschriebenen **SNI-Erweiterung** würde der TLS-Terminierungsproxy herausfinden, welches der verfügbaren TLS-Zertifikate (HTTPS) er für diese Verbindung verwenden muss, und zwar das, welches mit der vom Client erwarteten Domain übereinstimmt. + +In diesem Fall würde er das Zertifikat für `someapp.example.com` verwenden. + + + +Der Client **vertraut** bereits der Entität, die das TLS-Zertifikat generiert hat (in diesem Fall Let's Encrypt, aber wir werden später mehr darüber erfahren), sodass er **verifizieren** kann, dass das Zertifikat gültig ist. + +Mithilfe des Zertifikats entscheiden der Client und der TLS-Terminierungsproxy dann, **wie der Rest der TCP-Kommunikation verschlüsselt werden soll**. Damit ist der **TLS-Handshake** abgeschlossen. + +Danach verfügen der Client und der Server über eine **verschlüsselte TCP-Verbindung**, via TLS. Und dann können sie diese Verbindung verwenden, um die eigentliche **HTTP-Kommunikation** zu beginnen. + +Und genau das ist **HTTPS**, es ist einfach **HTTP** innerhalb einer **sicheren TLS-Verbindung**, statt einer puren (unverschlüsselten) TCP-Verbindung. + +!!! tip "Tipp" + Beachten Sie, dass die Verschlüsselung der Kommunikation auf der **TCP-Ebene** und nicht auf der HTTP-Ebene erfolgt. + +### HTTPS-Request + +Da Client und Server (sprich, der Browser und der TLS-Terminierungsproxy) nun über eine **verschlüsselte TCP-Verbindung** verfügen, können sie die **HTTP-Kommunikation** starten. + +Der Client sendet also einen **HTTPS-Request**. Das ist einfach ein HTTP-Request über eine verschlüsselte TLS-Verbindung. + + + +### Den Request entschlüsseln + +Der TLS-Terminierungsproxy würde die vereinbarte Verschlüsselung zum **Entschlüsseln des Requests** verwenden und den **einfachen (entschlüsselten) HTTP-Request** an den Prozess weiterleiten, der die Anwendung ausführt (z. B. einen Prozess, bei dem Uvicorn die FastAPI-Anwendung ausführt). + + + +### HTTP-Response + +Die Anwendung würde den Request verarbeiten und eine **einfache (unverschlüsselte) HTTP-Response** an den TLS-Terminierungsproxy senden. + + + +### HTTPS-Response + +Der TLS-Terminierungsproxy würde dann die Response mithilfe der zuvor vereinbarten Kryptografie (als das Zertifikat für `someapp.example.com` verhandelt wurde) **verschlüsseln** und sie an den Browser zurücksenden. + +Als Nächstes überprüft der Browser, ob die Response gültig und mit dem richtigen kryptografischen Schlüssel usw. verschlüsselt ist. Anschließend **entschlüsselt er die Response** und verarbeitet sie. + + + +Der Client (Browser) weiß, dass die Response vom richtigen Server kommt, da dieser die Kryptografie verwendet, die zuvor mit dem **HTTPS-Zertifikat** vereinbart wurde. + +### Mehrere Anwendungen + +Auf demselben Server (oder denselben Servern) könnten sich **mehrere Anwendungen** befinden, beispielsweise andere API-Programme oder eine Datenbank. + +Nur ein Prozess kann diese spezifische IP und den Port verarbeiten (in unserem Beispiel der TLS-Terminierungsproxy), aber die anderen Anwendungen/Prozesse können auch auf dem/den Server(n) ausgeführt werden, solange sie nicht versuchen, dieselbe **Kombination aus öffentlicher IP und Port** zu verwenden. + + + +Auf diese Weise könnte der TLS-Terminierungsproxy HTTPS und Zertifikate für **mehrere Domains**, für mehrere Anwendungen, verarbeiten und die Requests dann jeweils an die richtige Anwendung weiterleiten. + +### Verlängerung des Zertifikats + +Irgendwann in der Zukunft würde jedes Zertifikat **ablaufen** (etwa 3 Monate nach dem Erwerb). + +Und dann gäbe es ein anderes Programm (in manchen Fällen ist es ein anderes Programm, in manchen Fällen ist es derselbe TLS-Terminierungsproxy), das mit Let's Encrypt kommuniziert und das/die Zertifikat(e) erneuert. + + + +Die **TLS-Zertifikate** sind **einem Domainnamen zugeordnet**, nicht einer IP-Adresse. + +Um die Zertifikate zu erneuern, muss das erneuernde Programm der Behörde (Let's Encrypt) **nachweisen**, dass es diese Domain tatsächlich **besitzt und kontrolliert**. + +Um dies zu erreichen und den unterschiedlichen Anwendungsanforderungen gerecht zu werden, gibt es mehrere Möglichkeiten. Einige beliebte Methoden sind: + +* **Einige DNS-Einträge ändern**. + * Hierfür muss das erneuernde Programm die APIs des DNS-Anbieters unterstützen. Je nachdem, welchen DNS-Anbieter Sie verwenden, kann dies eine Option sein oder auch nicht. +* **Als Server ausführen** (zumindest während des Zertifikatserwerbsvorgangs), auf der öffentlichen IP-Adresse, die der Domain zugeordnet ist. + * Wie oben erwähnt, kann nur ein Prozess eine bestimmte IP und einen bestimmten Port überwachen. + * Das ist einer der Gründe, warum es sehr nützlich ist, wenn derselbe TLS-Terminierungsproxy auch den Zertifikats-Erneuerungsprozess übernimmt. + * Andernfalls müssen Sie möglicherweise den TLS-Terminierungsproxy vorübergehend stoppen, das Programm starten, welches die neuen Zertifikate beschafft, diese dann mit dem TLS-Terminierungsproxy konfigurieren und dann den TLS-Terminierungsproxy neu starten. Das ist nicht ideal, da Ihre Anwendung(en) während der Zeit, in der der TLS-Terminierungsproxy ausgeschaltet ist, nicht erreichbar ist/sind. + +Dieser ganze Erneuerungsprozess, während die Anwendung weiterhin bereitgestellt wird, ist einer der Hauptgründe, warum Sie ein **separates System zur Verarbeitung von HTTPS** mit einem TLS-Terminierungsproxy haben möchten, anstatt einfach die TLS-Zertifikate direkt mit dem Anwendungsserver zu verwenden (z. B. Uvicorn). + +## Zusammenfassung + +**HTTPS** zu haben ist sehr wichtig und in den meisten Fällen eine **kritische Anforderung**. Die meiste Arbeit, die Sie als Entwickler in Bezug auf HTTPS aufwenden müssen, besteht lediglich darin, **diese Konzepte zu verstehen** und wie sie funktionieren. + +Sobald Sie jedoch die grundlegenden Informationen zu **HTTPS für Entwickler** kennen, können Sie verschiedene Tools problemlos kombinieren und konfigurieren, um alles auf einfache Weise zu verwalten. + +In einigen der nächsten Kapitel zeige ich Ihnen einige konkrete Beispiele für die Einrichtung von **HTTPS** für **FastAPI**-Anwendungen. 🔒 diff --git a/docs/de/docs/deployment/index.md b/docs/de/docs/deployment/index.md new file mode 100644 index 0000000000000..1aa131097745e --- /dev/null +++ b/docs/de/docs/deployment/index.md @@ -0,0 +1,21 @@ +# Deployment + +Das Deployment einer **FastAPI**-Anwendung ist relativ einfach. + +## Was bedeutet Deployment? + +**Deployment** (Deutsch etwa: **Bereitstellen der Anwendung**) bedeutet, die notwendigen Schritte durchzuführen, um die Anwendung **für die Endbenutzer verfügbar** zu machen. + +Bei einer **Web-API** bedeutet das normalerweise, diese auf einem **entfernten Rechner** zu platzieren, mit einem **Serverprogramm**, welches gute Leistung, Stabilität, usw. bietet, damit Ihre **Benutzer** auf die Anwendung effizient und ohne Unterbrechungen oder Probleme **zugreifen** können. + +Das steht im Gegensatz zu den **Entwicklungsphasen**, in denen Sie ständig den Code ändern, kaputt machen, reparieren, den Entwicklungsserver stoppen und neu starten, usw. + +## Deployment-Strategien + +Abhängig von Ihrem spezifischen Anwendungsfall und den von Ihnen verwendeten Tools gibt es mehrere Möglichkeiten, das zu tun. + +Sie könnten mithilfe einer Kombination von Tools selbst **einen Server bereitstellen**, Sie könnten einen **Cloud-Dienst** nutzen, der einen Teil der Arbeit für Sie erledigt, oder andere mögliche Optionen. + +Ich zeige Ihnen einige der wichtigsten Konzepte, die Sie beim Deployment einer **FastAPI**-Anwendung wahrscheinlich berücksichtigen sollten (obwohl das meiste davon auch für jede andere Art von Webanwendung gilt). + +In den nächsten Abschnitten erfahren Sie mehr über die zu beachtenden Details und über die Techniken, das zu tun. ✨ diff --git a/docs/de/docs/deployment/manually.md b/docs/de/docs/deployment/manually.md new file mode 100644 index 0000000000000..c8e348aa1064b --- /dev/null +++ b/docs/de/docs/deployment/manually.md @@ -0,0 +1,145 @@ +# Einen Server manuell ausführen – Uvicorn + +Das Wichtigste, was Sie zum Ausführen einer **FastAPI**-Anwendung auf einer entfernten Servermaschine benötigen, ist ein ASGI-Serverprogramm, wie **Uvicorn**. + +Es gibt 3 Hauptalternativen: + +* Uvicorn: ein hochperformanter ASGI-Server. +* Hypercorn: ein ASGI-Server, der unter anderem mit HTTP/2 und Trio kompatibel ist. +* Daphne: Der für Django Channels entwickelte ASGI-Server. + +## Servermaschine und Serverprogramm + +Bei den Benennungen gibt es ein kleines Detail, das Sie beachten sollten. 💡 + +Das Wort „**Server**“ bezieht sich häufig sowohl auf den entfernten-/Cloud-Computer (die physische oder virtuelle Maschine) als auch auf das Programm, das auf dieser Maschine ausgeführt wird (z. B. Uvicorn). + +Denken Sie einfach daran, wenn Sie „Server“ im Allgemeinen lesen, dass es sich auf eines dieser beiden Dinge beziehen kann. + +Wenn man sich auf die entfernte Maschine bezieht, wird sie üblicherweise als **Server**, aber auch als **Maschine**, **VM** (virtuelle Maschine) oder **Knoten** bezeichnet. Diese Begriffe beziehen sich auf irgendeine Art von entfernten Rechner, normalerweise unter Linux, auf dem Sie Programme ausführen. + +## Das Serverprogramm installieren + +Sie können einen ASGI-kompatiblen Server installieren mit: + +=== "Uvicorn" + + * Uvicorn, ein blitzschneller ASGI-Server, basierend auf uvloop und httptools. + +
+ + ```console + $ pip install "uvicorn[standard]" + + ---> 100% + ``` + +
+ + !!! tip "Tipp" + Durch das Hinzufügen von `standard` installiert und verwendet Uvicorn einige empfohlene zusätzliche Abhängigkeiten. + + Inklusive `uvloop`, einen hochperformanten Drop-in-Ersatz für `asyncio`, welcher für einen großen Leistungsschub bei der Nebenläufigkeit sorgt. + +=== "Hypercorn" + + * Hypercorn, ein ASGI-Server, der auch mit HTTP/2 kompatibel ist. + +
+ + ```console + $ pip install hypercorn + + ---> 100% + ``` + +
+ + ... oder jeden anderen ASGI-Server. + +## Das Serverprogramm ausführen + +Anschließend können Sie Ihre Anwendung auf die gleiche Weise ausführen, wie Sie es in den Tutorials getan haben, jedoch ohne die Option `--reload`, z. B.: + +=== "Uvicorn" + +
+ + ```console + $ uvicorn main:app --host 0.0.0.0 --port 80 + + INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) + ``` + +
+ +=== "Hypercorn" + +
+ + ```console + $ hypercorn main:app --bind 0.0.0.0:80 + + Running on 0.0.0.0:8080 over http (CTRL + C to quit) + ``` + +
+ +!!! warning "Achtung" + Denken Sie daran, die Option `--reload` zu entfernen, wenn Sie diese verwendet haben. + + Die Option `--reload` verbraucht viel mehr Ressourcen, ist instabiler, usw. + + Sie hilft sehr während der **Entwicklung**, aber Sie sollten sie **nicht** in der **Produktion** verwenden. + +## Hypercorn mit Trio + +Starlette und **FastAPI** basieren auf AnyIO, welches diese sowohl mit der Python-Standardbibliothek asyncio, als auch mit Trio kompatibel macht. + +Dennoch ist Uvicorn derzeit nur mit asyncio kompatibel und verwendet normalerweise `uvloop`, den leistungsstarken Drop-in-Ersatz für `asyncio`. + +Wenn Sie jedoch **Trio** direkt verwenden möchten, können Sie **Hypercorn** verwenden, da dieses es unterstützt. ✨ + +### Hypercorn mit Trio installieren + +Zuerst müssen Sie Hypercorn mit Trio-Unterstützung installieren: + +
+ +```console +$ pip install "hypercorn[trio]" +---> 100% +``` + +
+ +### Mit Trio ausführen + +Dann können Sie die Befehlszeilenoption `--worker-class` mit dem Wert `trio` übergeben: + +
+ +```console +$ hypercorn main:app --worker-class trio +``` + +
+ +Und das startet Hypercorn mit Ihrer Anwendung und verwendet Trio als Backend. + +Jetzt können Sie Trio intern in Ihrer Anwendung verwenden. Oder noch besser: Sie können AnyIO verwenden, sodass Ihr Code sowohl mit Trio als auch asyncio kompatibel ist. 🎉 + +## Konzepte des Deployments + +Obige Beispiele führen das Serverprogramm (z. B. Uvicorn) aus, starten **einen einzelnen Prozess** und überwachen alle IPs (`0.0.0.0`) an einem vordefinierten Port (z. B. `80`). + +Das ist die Grundidee. Aber Sie möchten sich wahrscheinlich um einige zusätzliche Dinge kümmern, wie zum Beispiel: + +* Sicherheit – HTTPS +* Beim Hochfahren ausführen +* Neustarts +* Replikation (die Anzahl der laufenden Prozesse) +* Arbeitsspeicher +* Schritte vor dem Start + +In den nächsten Kapiteln erzähle ich Ihnen mehr über jedes dieser Konzepte, wie Sie über diese nachdenken, und gebe Ihnen einige konkrete Beispiele mit Strategien für den Umgang damit. 🚀 diff --git a/docs/de/docs/deployment/server-workers.md b/docs/de/docs/deployment/server-workers.md new file mode 100644 index 0000000000000..04d48dc6c945c --- /dev/null +++ b/docs/de/docs/deployment/server-workers.md @@ -0,0 +1,180 @@ +# Serverworker – Gunicorn mit Uvicorn + +Schauen wir uns die Deployment-Konzepte von früher noch einmal an: + +* Sicherheit – HTTPS +* Beim Hochfahren ausführen +* Neustarts +* **Replikation (die Anzahl der laufenden Prozesse)** +* Arbeitsspeicher +* Schritte vor dem Start + +Bis zu diesem Punkt, in allen Tutorials in der Dokumentation, haben Sie wahrscheinlich ein **Serverprogramm** wie Uvicorn ausgeführt, in einem **einzelnen Prozess**. + +Wenn Sie Anwendungen bereitstellen, möchten Sie wahrscheinlich eine gewisse **Replikation von Prozessen**, um **mehrere CPU-Kerne** zu nutzen und mehr Requests bearbeiten zu können. + +Wie Sie im vorherigen Kapitel über [Deployment-Konzepte](concepts.md){.internal-link target=_blank} gesehen haben, gibt es mehrere Strategien, die Sie anwenden können. + +Hier zeige ich Ihnen, wie Sie **Gunicorn** mit **Uvicorn Workerprozessen** verwenden. + +!!! info + Wenn Sie Container verwenden, beispielsweise mit Docker oder Kubernetes, erzähle ich Ihnen mehr darüber im nächsten Kapitel: [FastAPI in Containern – Docker](docker.md){.internal-link target=_blank}. + + Insbesondere wenn die Anwendung auf **Kubernetes** läuft, werden Sie Gunicorn wahrscheinlich **nicht** verwenden wollen und stattdessen **einen einzelnen Uvicorn-Prozess pro Container** ausführen wollen, aber ich werde Ihnen später in diesem Kapitel mehr darüber erzählen. + +## Gunicorn mit Uvicorn-Workern + +**Gunicorn** ist hauptsächlich ein Anwendungsserver, der den **WSGI-Standard** verwendet. Das bedeutet, dass Gunicorn Anwendungen wie Flask und Django ausliefern kann. Gunicorn selbst ist nicht mit **FastAPI** kompatibel, da FastAPI den neuesten **ASGI-Standard** verwendet. + +Aber Gunicorn kann als **Prozessmanager** arbeiten und Benutzer können ihm mitteilen, welche bestimmte **Workerprozessklasse** verwendet werden soll. Dann würde Gunicorn einen oder mehrere **Workerprozesse** starten, diese Klasse verwendend. + +Und **Uvicorn** hat eine **Gunicorn-kompatible Workerklasse**. + +Mit dieser Kombination würde Gunicorn als **Prozessmanager** fungieren und den **Port** und die **IP** abhören. Und er würde die Kommunikation an die Workerprozesse **weiterleiten**, welche die **Uvicorn-Klasse** ausführen. + +Und dann wäre die Gunicorn-kompatible **Uvicorn-Worker**-Klasse dafür verantwortlich, die von Gunicorn gesendeten Daten in den ASGI-Standard zu konvertieren, damit FastAPI diese verwenden kann. + +## Gunicorn und Uvicorn installieren + +
+ +```console +$ pip install "uvicorn[standard]" gunicorn + +---> 100% +``` + +
+ +Dadurch wird sowohl Uvicorn mit zusätzlichen `standard`-Packages (um eine hohe Leistung zu erzielen) als auch Gunicorn installiert. + +## Gunicorn mit Uvicorn-Workern ausführen + +Dann können Sie Gunicorn ausführen mit: + +
+ +```console +$ gunicorn main:app --workers 4 --worker-class uvicorn.workers.UvicornWorker --bind 0.0.0.0:80 + +[19499] [INFO] Starting gunicorn 20.1.0 +[19499] [INFO] Listening at: http://0.0.0.0:80 (19499) +[19499] [INFO] Using worker: uvicorn.workers.UvicornWorker +[19511] [INFO] Booting worker with pid: 19511 +[19513] [INFO] Booting worker with pid: 19513 +[19514] [INFO] Booting worker with pid: 19514 +[19515] [INFO] Booting worker with pid: 19515 +[19511] [INFO] Started server process [19511] +[19511] [INFO] Waiting for application startup. +[19511] [INFO] Application startup complete. +[19513] [INFO] Started server process [19513] +[19513] [INFO] Waiting for application startup. +[19513] [INFO] Application startup complete. +[19514] [INFO] Started server process [19514] +[19514] [INFO] Waiting for application startup. +[19514] [INFO] Application startup complete. +[19515] [INFO] Started server process [19515] +[19515] [INFO] Waiting for application startup. +[19515] [INFO] Application startup complete. +``` + +
+ +Sehen wir uns an, was jede dieser Optionen bedeutet: + +* `main:app`: Das ist die gleiche Syntax, die auch von Uvicorn verwendet wird. `main` bedeutet das Python-Modul mit dem Namen `main`, also eine Datei `main.py`. Und `app` ist der Name der Variable, welche die **FastAPI**-Anwendung ist. + * Stellen Sie sich einfach vor, dass `main:app` einer Python-`import`-Anweisung wie der folgenden entspricht: + + ```Python + from main import app + ``` + + * Der Doppelpunkt in `main:app` entspricht also dem Python-`import`-Teil in `from main import app`. + +* `--workers`: Die Anzahl der zu verwendenden Workerprozesse, jeder führt einen Uvicorn-Worker aus, in diesem Fall 4 Worker. + +* `--worker-class`: Die Gunicorn-kompatible Workerklasse zur Verwendung in den Workerprozessen. + * Hier übergeben wir die Klasse, die Gunicorn etwa so importiert und verwendet: + + ```Python + import uvicorn.workers.UvicornWorker + ``` + +* `--bind`: Das teilt Gunicorn die IP und den Port mit, welche abgehört werden sollen, wobei ein Doppelpunkt (`:`) verwendet wird, um die IP und den Port zu trennen. + * Wenn Sie Uvicorn direkt ausführen würden, würden Sie anstelle von `--bind 0.0.0.0:80` (die Gunicorn-Option) stattdessen `--host 0.0.0.0` und `--port 80` verwenden. + +In der Ausgabe können Sie sehen, dass die **PID** (Prozess-ID) jedes Prozesses angezeigt wird (es ist nur eine Zahl). + +Sie können sehen, dass: + +* Der Gunicorn **Prozessmanager** beginnt, mit der PID `19499` (in Ihrem Fall ist es eine andere Nummer). +* Dann beginnt er zu lauschen: `Listening at: http://0.0.0.0:80`. +* Dann erkennt er, dass er die Workerklasse `uvicorn.workers.UvicornWorker` verwenden muss. +* Und dann werden **4 Worker** gestartet, jeder mit seiner eigenen PID: `19511`, `19513`, `19514` und `19515`. + +Gunicorn würde sich bei Bedarf auch um die Verwaltung **beendeter Prozesse** und den **Neustart** von Prozessen kümmern, um die Anzahl der Worker aufrechtzuerhalten. Das hilft also teilweise beim **Neustarts**-Konzept aus der obigen Liste. + +Dennoch möchten Sie wahrscheinlich auch etwas außerhalb haben, um sicherzustellen, dass Gunicorn bei Bedarf **neu gestartet wird**, und er auch **beim Hochfahren ausgeführt wird**, usw. + +## Uvicorn mit Workern + +Uvicorn bietet ebenfalls die Möglichkeit, mehrere **Workerprozesse** zu starten und auszuführen. + +Dennoch sind die Fähigkeiten von Uvicorn zur Abwicklung von Workerprozessen derzeit eingeschränkter als die von Gunicorn. Wenn Sie also einen Prozessmanager auf dieser Ebene (auf der Python-Ebene) haben möchten, ist es vermutlich besser, es mit Gunicorn als Prozessmanager zu versuchen. + +Wie auch immer, Sie würden es so ausführen: + +
+ +```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. +``` + +
+ +Die einzige neue Option hier ist `--workers`, die Uvicorn anweist, 4 Workerprozesse zu starten. + +Sie können auch sehen, dass die **PID** jedes Prozesses angezeigt wird, `27365` für den übergeordneten Prozess (dies ist der **Prozessmanager**) und eine für jeden Workerprozess: `27368`, `27369`, `27370` und `27367`. + +## Deployment-Konzepte + +Hier haben Sie gesehen, wie Sie mit **Gunicorn** (oder Uvicorn) **Uvicorn-Workerprozesse** verwalten, um die Ausführung der Anwendung zu **parallelisieren**, **mehrere Kerne** der CPU zu nutzen und in der Lage zu sein, **mehr Requests** zu bedienen. + +In der Liste der Deployment-Konzepte von oben würde die Verwendung von Workern hauptsächlich beim **Replikation**-Teil und ein wenig bei **Neustarts** helfen, aber Sie müssen sich trotzdem um die anderen kümmern: + +* **Sicherheit – HTTPS** +* **Beim Hochfahren ausführen** +* **Neustarts** +* Replikation (die Anzahl der laufenden Prozesse) +* **Arbeitsspeicher** +* **Schritte vor dem Start** + +## Container und Docker + +Im nächsten Kapitel über [FastAPI in Containern – Docker](docker.md){.internal-link target=_blank} werde ich einige Strategien erläutern, die Sie für den Umgang mit den anderen **Deployment-Konzepten** verwenden können. + +Ich zeige Ihnen auch das **offizielle Docker-Image**, welches **Gunicorn mit Uvicorn-Workern** und einige Standardkonfigurationen enthält, die für einfache Fälle nützlich sein können. + +Dort zeige ich Ihnen auch, wie Sie **Ihr eigenes Image von Grund auf erstellen**, um einen einzelnen Uvicorn-Prozess (ohne Gunicorn) auszuführen. Es ist ein einfacher Vorgang und wahrscheinlich das, was Sie tun möchten, wenn Sie ein verteiltes Containerverwaltungssystem wie **Kubernetes** verwenden. + +## Zusammenfassung + +Sie können **Gunicorn** (oder auch Uvicorn) als Prozessmanager mit Uvicorn-Workern verwenden, um **Multikern-CPUs** zu nutzen und **mehrere Prozesse parallel** auszuführen. + +Sie können diese Tools und Ideen nutzen, wenn Sie **Ihr eigenes Deployment-System** einrichten und sich dabei selbst um die anderen Deployment-Konzepte kümmern. + +Schauen Sie sich das nächste Kapitel an, um mehr über **FastAPI** mit Containern (z. B. Docker und Kubernetes) zu erfahren. Sie werden sehen, dass diese Tools auch einfache Möglichkeiten bieten, die anderen **Deployment-Konzepte** zu lösen. ✨ diff --git a/docs/de/docs/deployment/versions.md b/docs/de/docs/deployment/versions.md new file mode 100644 index 0000000000000..d71aded2276a2 --- /dev/null +++ b/docs/de/docs/deployment/versions.md @@ -0,0 +1,86 @@ +# Über FastAPI-Versionen + +**FastAPI** wird bereits in vielen Anwendungen und Systemen produktiv eingesetzt. Und die Testabdeckung wird bei 100 % gehalten. Aber seine Entwicklung geht immer noch schnell voran. + +Es werden regelmäßig neue Funktionen hinzugefügt, Fehler werden regelmäßig behoben und der Code wird weiterhin kontinuierlich verbessert. + +Aus diesem Grund sind die aktuellen Versionen immer noch `0.x.x`, was darauf hindeutet, dass jede Version möglicherweise nicht abwärtskompatible Änderungen haben könnte. Dies folgt den Konventionen der semantischen Versionierung. + +Sie können jetzt Produktionsanwendungen mit **FastAPI** erstellen (und das tun Sie wahrscheinlich schon seit einiger Zeit), Sie müssen nur sicherstellen, dass Sie eine Version verwenden, die korrekt mit dem Rest Ihres Codes funktioniert. + +## `fastapi`-Version pinnen + +Als Erstes sollten Sie die Version von **FastAPI**, die Sie verwenden, an die höchste Version „pinnen“, von der Sie wissen, dass sie für Ihre Anwendung korrekt funktioniert. + +Angenommen, Sie verwenden in Ihrer Anwendung die Version `0.45.0`. + +Wenn Sie eine `requirements.txt`-Datei verwenden, können Sie die Version wie folgt angeben: + +```txt +fastapi==0.45.0 +``` + +Das würde bedeuten, dass Sie genau die Version `0.45.0` verwenden. + +Oder Sie können sie auch anpinnen mit: + +```txt +fastapi>=0.45.0,<0.46.0 +``` + +Das würde bedeuten, dass Sie eine Version `0.45.0` oder höher verwenden würden, aber kleiner als `0.46.0`, beispielsweise würde eine Version `0.45.2` immer noch akzeptiert. + +Wenn Sie zum Verwalten Ihrer Installationen andere Tools wie Poetry, Pipenv oder andere verwenden, sie verfügen alle über eine Möglichkeit, bestimmte Versionen für Ihre Packages zu definieren. + +## Verfügbare Versionen + +Die verfügbaren Versionen können Sie in den [Release Notes](../release-notes.md){.internal-link target=_blank} einsehen (z. B. um zu überprüfen, welches die neueste Version ist). + +## Über Versionen + +Gemäß den Konventionen zur semantischen Versionierung könnte jede Version unter `1.0.0` potenziell nicht abwärtskompatible Änderungen hinzufügen. + +FastAPI folgt auch der Konvention, dass jede „PATCH“-Versionsänderung für Bugfixes und abwärtskompatible Änderungen gedacht ist. + +!!! tip "Tipp" + Der „PATCH“ ist die letzte Zahl, zum Beispiel ist in `0.2.3` die PATCH-Version `3`. + +Sie sollten also in der Lage sein, eine Version wie folgt anzupinnen: + +```txt +fastapi>=0.45.0,<0.46.0 +``` + +Nicht abwärtskompatible Änderungen und neue Funktionen werden in „MINOR“-Versionen hinzugefügt. + +!!! tip "Tipp" + „MINOR“ ist die Zahl in der Mitte, zum Beispiel ist in `0.2.3` die MINOR-Version `2`. + +## Upgrade der FastAPI-Versionen + +Sie sollten Tests für Ihre Anwendung hinzufügen. + +Mit **FastAPI** ist das sehr einfach (dank Starlette), schauen Sie sich die Dokumentation an: [Testen](../tutorial/testing.md){.internal-link target=_blank} + +Nachdem Sie Tests erstellt haben, können Sie die **FastAPI**-Version auf eine neuere Version aktualisieren und sicherstellen, dass Ihr gesamter Code ordnungsgemäß funktioniert, indem Sie Ihre Tests ausführen. + +Wenn alles funktioniert oder nachdem Sie die erforderlichen Änderungen vorgenommen haben und alle Ihre Tests bestehen, können Sie Ihr `fastapi` an die neue aktuelle Version pinnen. + +## Über Starlette + +Sie sollten die Version von `starlette` nicht pinnen. + +Verschiedene Versionen von **FastAPI** verwenden eine bestimmte neuere Version von Starlette. + +Sie können **FastAPI** also einfach die korrekte Starlette-Version verwenden lassen. + +## Über Pydantic + +Pydantic integriert die Tests für **FastAPI** in seine eigenen Tests, sodass neue Versionen von Pydantic (über `1.0.0`) immer mit FastAPI kompatibel sind. + +Sie können Pydantic an jede für Sie geeignete Version über `1.0.0` und unter `2.0.0` anpinnen. + +Zum Beispiel: +```txt +pydantic>=1.2.0,<2.0.0 +``` diff --git a/docs/de/docs/external-links.md b/docs/de/docs/external-links.md new file mode 100644 index 0000000000000..d97f4d39cf27b --- /dev/null +++ b/docs/de/docs/external-links.md @@ -0,0 +1,36 @@ +# Externe Links und Artikel + +**FastAPI** hat eine großartige Community, die ständig wächst. + +Es gibt viele Beiträge, Artikel, Tools und Projekte zum Thema **FastAPI**. + +Hier ist eine unvollständige Liste einiger davon. + +!!! tip "Tipp" + Wenn Sie einen Artikel, ein Projekt, ein Tool oder irgendetwas im Zusammenhang mit **FastAPI** haben, was hier noch nicht aufgeführt ist, erstellen Sie einen Pull Request und fügen Sie es hinzu. + +!!! note "Hinweis Deutsche Übersetzung" + Die folgenden Überschriften und Links werden aus einer anderen Datei gelesen und sind daher nicht ins Deutsche übersetzt. + +{% for section_name, section_content in external_links.items() %} + +## {{ section_name }} + +{% for lang_name, lang_content in section_content.items() %} + +### {{ lang_name }} + +{% for item in lang_content %} + +* {{ item.title }} by {{ item.author }}. + +{% endfor %} +{% endfor %} +{% endfor %} + +## Projekte + +Die neuesten GitHub-Projekte zum Thema `fastapi`: + +
+
diff --git a/docs/de/docs/fastapi-people.md b/docs/de/docs/fastapi-people.md new file mode 100644 index 0000000000000..522a4bce55a4c --- /dev/null +++ b/docs/de/docs/fastapi-people.md @@ -0,0 +1,176 @@ +--- +hide: + - navigation +--- + +# FastAPI Leute + +FastAPI hat eine großartige Gemeinschaft, die Menschen mit unterschiedlichstem Hintergrund willkommen heißt. + +## Erfinder - Betreuer + +Hey! 👋 + +Das bin ich: + +{% if people %} +
+{% for user in people.maintainers %} + +
@{{ user.login }}
Answers: {{ user.answers }}
Pull Requests: {{ user.prs }}
+{% endfor %} + +
+{% endif %} + +Ich bin der Erfinder und Betreuer von **FastAPI**. Sie können mehr darüber in [FastAPI helfen – Hilfe erhalten – Mit dem Autor vernetzen](help-fastapi.md#mit-dem-autor-vernetzen){.internal-link target=_blank} erfahren. + +... Aber hier möchte ich Ihnen die Gemeinschaft vorstellen. + +--- + +**FastAPI** erhält eine Menge Unterstützung aus der Gemeinschaft. Und ich möchte ihre Beiträge hervorheben. + +Das sind die Menschen, die: + +* [Anderen bei Fragen auf GitHub helfen](help-fastapi.md#anderen-bei-fragen-auf-github-helfen){.internal-link target=_blank}. +* [Pull Requests erstellen](help-fastapi.md#einen-pull-request-erstellen){.internal-link target=_blank}. +* Pull Requests überprüfen (Review), [besonders wichtig für Übersetzungen](contributing.md#ubersetzungen){.internal-link target=_blank}. + +Eine Runde Applaus für sie. 👏 🙇 + +## Aktivste Benutzer im letzten Monat + +Hier die Benutzer, die im letzten Monat am meisten [anderen mit Fragen auf Github](help-fastapi.md#anderen-bei-fragen-auf-github-helfen){.internal-link target=_blank} geholfen haben. ☕ + +{% if people %} +
+{% for user in people.last_month_active %} + +
@{{ user.login }}
Fragen beantwortet: {{ user.count }}
+{% endfor %} + +
+{% endif %} + +## Experten + +Hier die **FastAPI-Experten**. 🤓 + +Das sind die Benutzer, die *insgesamt* [anderen am meisten mit Fragen auf GitHub geholfen haben](help-fastapi.md#anderen-bei-fragen-auf-github-helfen){.internal-link target=_blank}. + +Sie haben bewiesen, dass sie Experten sind, weil sie vielen anderen geholfen haben. ✨ + +{% if people %} +
+{% for user in people.experts %} + +
@{{ user.login }}
Fragen beantwortet: {{ user.count }}
+{% endfor %} + +
+{% endif %} + +## Top-Mitwirkende + +Hier sind die **Top-Mitwirkenden**. 👷 + +Diese Benutzer haben [die meisten Pull Requests erstellt](help-fastapi.md#einen-pull-request-erstellen){.internal-link target=_blank} welche *gemerged* wurden. + +Sie haben Quellcode, Dokumentation, Übersetzungen, usw. beigesteuert. 📦 + +{% if people %} +
+{% for user in people.top_contributors %} + +
@{{ user.login }}
Pull Requests: {{ user.count }}
+{% endfor %} + +
+{% endif %} + +Es gibt viele andere Mitwirkende (mehr als hundert), Sie können sie alle auf der FastAPI GitHub Contributors-Seite sehen. 👷 + +## Top-Rezensenten + +Diese Benutzer sind die **Top-Rezensenten**. 🕵️ + +### Rezensionen für Übersetzungen + +Ich spreche nur ein paar Sprachen (und nicht sehr gut 😅). Daher bestätigen Reviewer [**Übersetzungen der Dokumentation**](contributing.md#ubersetzungen){.internal-link target=_blank}. Ohne sie gäbe es keine Dokumentation in mehreren anderen Sprachen. + +--- + +Die **Top-Reviewer** 🕵️ haben die meisten Pull Requests von anderen überprüft und stellen die Qualität des Codes, der Dokumentation und insbesondere der **Übersetzungen** sicher. + +{% if people %} +
+{% for user in people.top_reviewers %} + +
@{{ user.login }}
Reviews: {{ user.count }}
+{% endfor %} + +
+{% endif %} + +## Sponsoren + +Dies sind die **Sponsoren**. 😎 + +Sie unterstützen meine Arbeit an **FastAPI** (und andere), hauptsächlich durch GitHub-Sponsoren. + +### Gold Sponsoren + +{% if sponsors %} +{% for sponsor in sponsors.gold -%} + +{% endfor %} +{% endif %} + +### Silber Sponsoren + +{% if sponsors %} +{% for sponsor in sponsors.silver -%} + +{% endfor %} +{% endif %} + +{% if people %} +{% if people.sponsors_50 %} + +### Bronze Sponsoren + +
+{% for user in people.sponsors_50 %} + + +{% endfor %} + +
+ +{% endif %} +{% endif %} + +### Individuelle Sponsoren + +{% if people %} +
+{% for user in people.sponsors %} + + +{% endfor %} + +
+{% endif %} + +## Über diese Daten - technische Details + +Der Hauptzweck dieser Seite ist es zu zeigen, wie die Gemeinschaft anderen hilft. + +Das beinhaltet auch Hilfe, die normalerweise weniger sichtbar und in vielen Fällen mühsamer ist, wie, anderen bei Problemen zu helfen und Pull Requests mit Übersetzungen zu überprüfen. + +Diese Daten werden jeden Monat berechnet, Sie können den Quellcode hier lesen. + +Hier weise ich auch auf Beiträge von Sponsoren hin. + +Ich behalte mir auch das Recht vor, den Algorithmus, die Abschnitte, die Schwellenwerte usw. zu aktualisieren (nur für den Fall 🤷). diff --git a/docs/de/docs/features.md b/docs/de/docs/features.md index f281afd1edc5b..76aad9f16436e 100644 --- a/docs/de/docs/features.md +++ b/docs/de/docs/features.md @@ -1,21 +1,26 @@ +--- +hide: + - navigation +--- + # Merkmale ## FastAPI Merkmale -**FastAPI** ermöglicht Ihnen folgendes: +**FastAPI** ermöglicht Ihnen Folgendes: ### Basiert auf offenen Standards -* OpenAPI für API-Erstellung, zusammen mit Deklarationen von Pfad Operationen, Parameter, Nachrichtenrumpf-Anfragen (englisch: body request), Sicherheit, etc. -* Automatische Dokumentation der Datenentitäten mit dem JSON Schema (OpenAPI basiert selber auf dem JSON Schema). -* Entworfen auf Grundlage dieser Standards nach einer sorgfältigen Studie, statt einer nachträglichen Schicht über diesen Standards. -* Dies ermöglicht automatische **Quellcode-Generierung auf Benutzerebene** in vielen Sprachen. +* OpenAPI für die Erstellung von APIs, inklusive Deklarationen von Pfad-Operationen, Parametern, Body-Anfragen, Sicherheit, usw. +* Automatische Dokumentation der Datenmodelle mit JSON Schema (da OpenAPI selbst auf JSON Schema basiert). +* Um diese Standards herum entworfen, nach sorgfältigem Studium. Statt einer nachträglichen Schicht darüber. +* Dies ermöglicht auch automatische **Client-Code-Generierung** in vielen Sprachen. ### Automatische Dokumentation -Mit einer interaktiven API-Dokumentation und explorativen webbasierten Benutzerschnittstellen. Da FastAPI auf OpenAPI basiert, gibt es hierzu mehrere Optionen, wobei zwei standardmäßig vorhanden sind. +Interaktive API-Dokumentation und erkundbare Web-Benutzeroberflächen. Da das Framework auf OpenAPI basiert, gibt es mehrere Optionen, zwei sind standardmäßig vorhanden. -* Swagger UI, bietet interaktive Exploration: testen und rufen Sie ihre API direkt vom Webbrowser auf. +* Swagger UI, bietet interaktive Erkundung, testen und rufen Sie ihre API direkt im Webbrowser auf. ![Swagger UI Interaktion](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) @@ -25,13 +30,11 @@ Mit einer interaktiven API-Dokumentation und explorativen webbasierten Benutzers ### Nur modernes Python -Alles basiert auf **Python 3.6 Typ**-Deklarationen (dank Pydantic). Es muss keine neue Syntax gelernt werden, nur standardisiertes modernes Python. - - +Alles basiert auf **Python 3.8 Typ**-Deklarationen (dank Pydantic). Es muss keine neue Syntax gelernt werden, nur standardisiertes modernes Python. -Wenn Sie eine kurze, zweiminütige, Auffrischung in der Benutzung von Python Typ-Deklarationen benötigen (auch wenn Sie FastAPI nicht nutzen), schauen Sie sich diese kurze Einführung an (Englisch): Python Types{.internal-link target=_blank}. +Wenn Sie eine zweiminütige Auffrischung benötigen, wie man Python-Typen verwendet (auch wenn Sie FastAPI nicht benutzen), schauen Sie sich das kurze Tutorial an: [Einführung in Python-Typen](python-types.md){.internal-link target=_blank}. -Sie schreiben Standard-Python mit Typ-Deklarationen: +Sie schreiben Standard-Python mit Typen: ```Python from typing import List, Dict @@ -39,20 +42,20 @@ from datetime import date from pydantic import BaseModel -# Deklariere eine Variable als str -# und bekomme Editor-Unterstütung innerhalb der Funktion +# Deklarieren Sie eine Variable als ein `str` +# und bekommen Sie Editor-Unterstütung innerhalb der Funktion def main(user_id: str): return user_id -# Ein Pydantic model +# Ein Pydantic-Modell class User(BaseModel): id: int name: str joined: date ``` -Dies kann nun wiefolgt benutzt werden: +Das kann nun wie folgt verwendet werden: ```Python my_user: User = User(id=3, name="John Doe", joined="2018-07-19") @@ -69,135 +72,133 @@ my_second_user: User = User(**second_user_data) !!! info `**second_user_data` bedeutet: - Übergebe die Schlüssel und die zugehörigen Werte des `second_user_data` Datenwörterbuches direkt als Schlüssel-Wert Argumente, äquivalent zu: `User(id=4, name="Mary", joined="2018-11-30")` + Nimm die Schlüssel-Wert-Paare des `second_user_data` Dicts und übergib sie direkt als Schlüsselwort-Argumente. Äquivalent zu: `User(id=4, name="Mary", joined="2018-11-30")`. ### Editor Unterstützung -FastAPI wurde so entworfen, dass es einfach und intuitiv zu benutzen ist; alle Entscheidungen wurden auf mehreren Editoren getestet (sogar vor der eigentlichen Implementierung), um so eine best mögliche Entwicklererfahrung zu gewährleisten. +Das ganze Framework wurde so entworfen, dass es einfach und intuitiv zu benutzen ist; alle Entscheidungen wurden auf mehreren Editoren getestet, sogar vor der Implementierung, um die bestmögliche Entwicklererfahrung zu gewährleisten. -In der letzen Python Entwickler Umfrage stellte sich heraus, dass die meist genutzte Funktion die "Autovervollständigung" ist. +In der letzten Python-Entwickler-Umfrage wurde klar, dass die meist genutzte Funktion die „Autovervollständigung“ ist. -Die gesamte Struktur von **FastAPI** soll dem gerecht werden. Autovervollständigung funktioniert überall. +Das gesamte **FastAPI**-Framework ist darauf ausgelegt, das zu erfüllen. Autovervollständigung funktioniert überall. -Sie müssen selten in die Dokumentation schauen. +Sie werden selten noch mal in der Dokumentation nachschauen müssen. So kann ihr Editor Sie unterstützen: * in Visual Studio Code: -![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) +![Editor Unterstützung](https://fastapi.tiangolo.com/img/vscode-completion.png) * in PyCharm: -![editor support](https://fastapi.tiangolo.com/img/pycharm-completion.png) +![Editor Unterstützung](https://fastapi.tiangolo.com/img/pycharm-completion.png) -Sie bekommen Autovervollständigung an Stellen, an denen Sie dies vorher nicht für möglich gehalten hätten. Zum Beispiel der `price` Schlüssel aus einem JSON Datensatz (dieser könnte auch verschachtelt sein) aus einer Anfrage. +Sie bekommen sogar Autovervollständigung an Stellen, an denen Sie dies vorher nicht für möglich gehalten hätten. Zum Beispiel der `price` Schlüssel in einem JSON Datensatz (dieser könnte auch verschachtelt sein), der aus einer Anfrage kommt. -Hierdurch werden Sie nie wieder einen falschen Schlüsselnamen benutzen und sparen sich lästiges Suchen in der Dokumentation, um beispielsweise herauszufinden ob Sie `username` oder `user_name` als Schlüssel verwenden. +Nie wieder falsche Schlüsselnamen tippen, Hin und Herhüpfen zwischen der Dokumentation, Hoch- und Runterscrollen, um herauszufinden, ob es `username` oder `user_name` war. ### Kompakt -FastAPI nutzt für alles sensible **Standard-Einstellungen**, welche optional überall konfiguriert werden können. Alle Parameter können ganz genau an Ihre Bedürfnisse angepasst werden, sodass sie genau die API definieren können, die sie brauchen. +Es gibt für alles sensible **Defaultwerte**, mit optionaler Konfiguration überall. Alle Parameter können feinjustiert werden, damit sie tun, was Sie benötigen, und die API definieren, die Sie brauchen. -Aber standardmäßig, **"funktioniert einfach"** alles. +Aber standardmäßig **„funktioniert einfach alles“**. ### Validierung -* Validierung für die meisten (oder alle?) Python **Datentypen**, hierzu gehören: +* Validierung für die meisten (oder alle?) Python-**Datentypen**, hierzu gehören: * JSON Objekte (`dict`). * JSON Listen (`list`), die den Typ ihrer Elemente definieren. - * Zeichenketten (`str`), mit definierter minimaler und maximaler Länge. - * Zahlen (`int`, `float`) mit minimaler und maximaler Größe, usw. + * Strings (`str`) mit definierter minimaler und maximaler Länge. + * Zahlen (`int`, `float`) mit Mindest- und Maximal-Werten, usw. -* Validierung für ungewöhnliche Typen, wie: +* Validierung für mehr exotische Typen, wie: * URL. - * Email. + * E-Mail. * UUID. * ... und andere. -Die gesamte Validierung übernimmt das etablierte und robuste **Pydantic**. +Die gesamte Validierung übernimmt das gut etablierte und robuste **Pydantic**. ### Sicherheit und Authentifizierung -Integrierte Sicherheit und Authentifizierung. Ohne Kompromisse bei Datenbanken oder Datenmodellen. +Sicherheit und Authentifizierung ist integriert. Ohne Kompromisse bei Datenbanken oder Datenmodellen. -Unterstützt werden alle von OpenAPI definierten Sicherheitsschemata, hierzu gehören: +Alle in OpenAPI definierten Sicherheitsschemas, inklusive: -* HTTP Basis Authentifizierung. -* **OAuth2** (auch mit **JWT Zugriffstokens**). Schauen Sie sich hierzu dieses Tutorial an: [OAuth2 mit JWT](tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. +* HTTP Basic Authentifizierung. +* **OAuth2** (auch mit **JWT Tokens**). Siehe dazu das Tutorial zu [OAuth2 mit JWT](tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. * API Schlüssel in: - * Kopfzeile (HTTP Header). + * Header-Feldern. * Anfrageparametern. - * Cookies, etc. + * Cookies, usw. -Zusätzlich gibt es alle Sicherheitsfunktionen von Starlette (auch **session cookies**). +Zusätzlich alle Sicherheitsfunktionen von Starlette (inklusive **Session Cookies**). -Alles wurde als wiederverwendbare Werkzeuge und Komponenten geschaffen, die einfach in ihre Systeme, Datenablagen, relationale und nicht-relationale Datenbanken, ..., integriert werden können. +Alles als wiederverwendbare Tools und Komponenten gebaut, die einfach in ihre Systeme, Datenspeicher, relationalen und nicht-relationalen Datenbanken, usw., integriert werden können. -### Einbringen von Abhängigkeiten (meist: Dependency Injection) +### Einbringen von Abhängigkeiten (Dependency Injection) -FastAPI enthält ein extrem einfaches, aber extrem mächtiges Dependency Injection System. +FastAPI enthält ein extrem einfach zu verwendendes, aber extrem mächtiges Dependency Injection System. -* Selbst Abhängigkeiten können Abhängigkeiten haben, woraus eine Hierachie oder ein **"Graph" von Abhängigkeiten** entsteht. -* **Automatische Umsetzung** durch FastAPI. -* Alle abhängigen Komponenten könnten Daten von Anfragen, **Erweiterungen der Pfadoperations-**Einschränkungen und der automatisierten Dokumentation benötigen. -* **Automatische Validierung** selbst für *Pfadoperationen*-Parameter, die in den Abhängigkeiten definiert wurden. -* Unterstützt komplexe Benutzerauthentifizierungssysteme, **Datenbankverbindungen**, usw. -* **Keine Kompromisse** bei Datenbanken, Eingabemasken, usw. Sondern einfache Integration von allen. +* Selbst Abhängigkeiten können Abhängigkeiten haben, woraus eine Hierarchie oder ein **„Graph“ von Abhängigkeiten** entsteht. +* Alles **automatisch gehandhabt** durch das Framework. +* Alle Abhängigkeiten können Daten von Anfragen anfordern und das Verhalten von **Pfadoperationen** und der automatisierten Dokumentation **modifizieren**. +* **Automatische Validierung** selbst für solche Parameter von *Pfadoperationen*, welche in Abhängigkeiten definiert sind. +* Unterstützung für komplexe Authentifizierungssysteme, **Datenbankverbindungen**, usw. +* **Keine Kompromisse** bei Datenbanken, Frontends, usw., sondern einfache Integration mit allen. ### Unbegrenzte Erweiterungen -Oder mit anderen Worten, sie werden nicht benötigt. Importieren und nutzen Sie Quellcode nach Bedarf. +Oder mit anderen Worten, sie werden nicht benötigt. Importieren und nutzen Sie den Code, den Sie brauchen. -Jede Integration wurde so entworfen, dass sie einfach zu nutzen ist (mit Abhängigkeiten), sodass Sie eine Erweiterung für Ihre Anwendung mit nur zwei Zeilen an Quellcode implementieren können. Hierbei nutzen Sie die selbe Struktur und Syntax, wie bei Pfadoperationen. +Jede Integration wurde so entworfen, dass sie so einfach zu nutzen ist (mit Abhängigkeiten), dass Sie eine Erweiterung für Ihre Anwendung mit nur zwei Zeilen Code erstellen können. Hierbei nutzen Sie die gleiche Struktur und Syntax, wie bei *Pfadoperationen*. ### Getestet -* 100% Testabdeckung. -* 100% Typen annotiert. +* 100 % Testabdeckung. +* 100 % Typen annotiert. * Verwendet in Produktionsanwendungen. ## Starlette's Merkmale -**FastAPI** ist vollkommen kompatibel (und basiert auf) Starlette. Das bedeutet, auch ihr eigener Starlette Quellcode funktioniert. +**FastAPI** ist vollkommen kompatibel (und basiert auf) Starlette. Das bedeutet, wenn Sie eigenen Starlette Quellcode haben, funktioniert der. -`FastAPI` ist eigentlich eine Unterklasse von `Starlette`. Wenn Sie also bereits Starlette kennen oder benutzen, können Sie das meiste Ihres Wissens direkt anwenden. +`FastAPI` ist tatsächlich eine Unterklasse von `Starlette`. Wenn Sie also bereits Starlette kennen oder benutzen, das meiste funktioniert genau so. -Mit **FastAPI** bekommen Sie viele von **Starlette**'s Funktionen (da FastAPI nur Starlette auf Steroiden ist): +Mit **FastAPI** bekommen Sie alles von **Starlette** (da FastAPI nur Starlette auf Steroiden ist): -* Stark beeindruckende Performanz. Es ist eines der schnellsten Python Frameworks, auf Augenhöhe mit **NodeJS** und **Go**. +* Schwer beeindruckende Performanz. Es ist eines der schnellsten Python-Frameworks, auf Augenhöhe mit **NodeJS** und **Go**. * **WebSocket**-Unterstützung. * Hintergrundaufgaben im selben Prozess. -* Ereignisse für das Starten und Herunterfahren. -* Testclient basierend auf HTTPX. -* **CORS**, GZip, statische Dateien, Antwortfluss. -* **Sitzungs und Cookie** Unterstützung. -* 100% Testabdeckung. -* 100% Typen annotiert. +* Ereignisse beim Starten und Herunterfahren. +* Testclient baut auf HTTPX auf. +* **CORS**, GZip, statische Dateien, Responses streamen. +* **Sitzungs- und Cookie**-Unterstützung. +* 100 % Testabdeckung. +* 100 % Typen annotierte Codebasis. ## Pydantic's Merkmale -**FastAPI** ist vollkommen kompatibel (und basiert auf) Pydantic. Das bedeutet, auch jeder zusätzliche Pydantic Quellcode funktioniert. +**FastAPI** ist vollkommen kompatibel (und basiert auf) Pydantic. Das bedeutet, wenn Sie eigenen Pydantic Quellcode haben, funktioniert der. -Verfügbar sind ebenso externe auf Pydantic basierende Bibliotheken, wie ORMs, ODMs für Datenbanken. +Inklusive externer Bibliotheken, die auf Pydantic basieren, wie ORMs, ODMs für Datenbanken. Daher können Sie in vielen Fällen das Objekt einer Anfrage **direkt zur Datenbank** schicken, weil alles automatisch validiert wird. -Das selbe gilt auch für die andere Richtung: Sie können jedes Objekt aus der Datenbank **direkt zum Klienten** schicken. +Das gleiche gilt auch für die andere Richtung: Sie können in vielen Fällen das Objekt aus der Datenbank **direkt zum Client** schicken. Mit **FastAPI** bekommen Sie alle Funktionen von **Pydantic** (da FastAPI für die gesamte Datenverarbeitung Pydantic nutzt): * **Kein Kopfzerbrechen**: - * Sie müssen keine neue Schemadefinitionssprache lernen. - * Wenn Sie mit Python's Typisierung arbeiten können, können Sie auch mit Pydantic arbeiten. -* Gutes Zusammenspiel mit Ihrer/Ihrem **IDE/linter/Gehirn**: - * Weil Datenstrukturen von Pydantic einfach nur Instanzen ihrer definierten Klassen sind, sollten Autovervollständigung, Linting, mypy und ihre Intuition einwandfrei funktionieren. -* **Schnell**: - * In Vergleichen ist Pydantic schneller als jede andere getestete Bibliothek. + * Keine neue Schemadefinition-Mikrosprache zu lernen. + * Wenn Sie Pythons Typen kennen, wissen Sie, wie man Pydantic verwendet. +* Gutes Zusammenspiel mit Ihrer/Ihrem **IDE/Linter/Gehirn**: + * Weil Pydantics Datenstrukturen einfach nur Instanzen ihrer definierten Klassen sind; Autovervollständigung, Linting, mypy und ihre Intuition sollten alle einwandfrei mit ihren validierten Daten funktionieren. * Validierung von **komplexen Strukturen**: - * Benutzung von hierachischen Pydantic Schemata, Python `typing`’s `List` und `Dict`, etc. - * Validierungen erlauben eine klare und einfache Datenschemadefinition, überprüft und dokumentiert als JSON Schema. - * Sie können stark **verschachtelte JSON** Objekte haben und diese sind trotzdem validiert und annotiert. + * Benutzung von hierarchischen Pydantic-Modellen, Python-`typing`s `List` und `Dict`, etc. + * Die Validierer erlauben es, komplexe Datenschemen klar und einfach zu definieren, überprüft und dokumentiert als JSON Schema. + * Sie können tief **verschachtelte JSON** Objekte haben, die alle validiert und annotiert sind. * **Erweiterbar**: - * Pydantic erlaubt die Definition von eigenen Datentypen oder sie können die Validierung mit einer `validator` dekorierten Methode erweitern. -* 100% Testabdeckung. + * Pydantic erlaubt die Definition von eigenen Datentypen oder sie können die Validierung mit einer `validator`-dekorierten Methode im Modell erweitern. +* 100 % Testabdeckung. diff --git a/docs/de/docs/help-fastapi.md b/docs/de/docs/help-fastapi.md new file mode 100644 index 0000000000000..bdc07e55f1443 --- /dev/null +++ b/docs/de/docs/help-fastapi.md @@ -0,0 +1,262 @@ +# FastAPI helfen – Hilfe erhalten + +Gefällt Ihnen **FastAPI**? + +Möchten Sie FastAPI, anderen Benutzern und dem Autor helfen? + +Oder möchten Sie Hilfe zu **FastAPI** erhalten? + +Es gibt sehr einfache Möglichkeiten zu helfen (manche erfordern nur ein oder zwei Klicks). + +Und es gibt auch viele Möglichkeiten, Hilfe zu bekommen. + +## Newsletter abonnieren + +Sie können den (unregelmäßig erscheinenden) [**FastAPI and Friends**-Newsletter](newsletter.md){.internal-link target=_blank} abonnieren, um auf dem Laufenden zu bleiben: + +* Neuigkeiten über FastAPI and Friends 🚀 +* Anleitungen 📝 +* Funktionen ✨ +* Breaking Changes 🚨 +* Tipps und Tricks ✅ +## FastAPI auf Twitter folgen + +Folgen Sie @fastapi auf **Twitter**, um die neuesten Nachrichten über **FastAPI** zu erhalten. 🐦 + +## **FastAPI** auf GitHub einen Stern geben + +Sie können FastAPI auf GitHub „starren“ (durch Klicken auf den Stern-Button oben rechts): https://github.com/tiangolo/fastapi. ⭐️ + +Durch das Hinzufügen eines Sterns können andere Benutzer es leichter finden und sehen, dass es für andere bereits nützlich war. + +## Das GitHub-Repository auf Releases beobachten + +Sie können FastAPI in GitHub beobachten (Klicken Sie oben rechts auf den Button „watch“): https://github.com/tiangolo/fastapi. 👀 + +Dort können Sie „Releases only“ auswählen. + +Auf diese Weise erhalten Sie Benachrichtigungen (per E-Mail), wenn es einen neuen Release (eine neue Version) von **FastAPI** mit Fehlerbehebungen und neuen Funktionen gibt. + +## Mit dem Autor vernetzen + +Sie können sich mit mir (Sebastián Ramírez / `tiangolo`), dem Autor, verbinden. + +Insbesondere: + +* Folgen Sie mir auf **GitHub**. + * Finden Sie andere Open-Source-Projekte, die ich erstellt habe und die Ihnen helfen könnten. + * Folgen Sie mir, um mitzubekommen, wenn ich ein neues Open-Source-Projekt erstelle. +* Folgen Sie mir auf **Twitter** oder Mastodon. + * Berichten Sie mir, wie Sie FastAPI verwenden (das höre ich gerne). + * Bekommen Sie mit, wenn ich Ankündigungen mache oder neue Tools veröffentliche. + * Sie können auch @fastapi auf Twitter folgen (ein separates Konto). +* Folgen Sie mir auf **LinkedIn**. + * Bekommen Sie mit, wenn ich Ankündigungen mache oder neue Tools veröffentliche (obwohl ich Twitter häufiger verwende 🤷‍♂). +* Lesen Sie, was ich schreibe (oder folgen Sie mir) auf **Dev.to** oder **Medium**. + * Lesen Sie andere Ideen, Artikel, und erfahren Sie mehr über die von mir erstellten Tools. + * Folgen Sie mir, um zu lesen, wenn ich etwas Neues veröffentliche. + +## Über **FastAPI** tweeten + +Tweeten Sie über **FastAPI** und teilen Sie mir und anderen mit, warum es Ihnen gefällt. 🎉 + +Ich höre gerne, wie **FastAPI** verwendet wird, was Ihnen daran gefallen hat, in welchem Projekt/Unternehmen Sie es verwenden, usw. + +## Für FastAPI abstimmen + +* Stimmen Sie für **FastAPI** auf Slant. +* Stimmen Sie für **FastAPI** auf AlternativeTo. +* Berichten Sie auf StackShare, dass Sie **FastAPI** verwenden. + +## Anderen bei Fragen auf GitHub helfen + +Sie können versuchen, anderen bei ihren Fragen zu helfen: + +* GitHub-Diskussionen +* GitHub-Issues + +In vielen Fällen kennen Sie möglicherweise bereits die Antwort auf diese Fragen. 🤓 + +Wenn Sie vielen Menschen bei ihren Fragen helfen, werden Sie offizieller [FastAPI-Experte](fastapi-people.md#experten){.internal-link target=_blank}. 🎉 + +Denken Sie aber daran, der wichtigste Punkt ist: Versuchen Sie, freundlich zu sein. Die Leute bringen ihre Frustrationen mit und fragen in vielen Fällen nicht auf die beste Art und Weise, aber versuchen Sie dennoch so gut wie möglich, freundlich zu sein. 🤗 + +Die **FastAPI**-Community soll freundlich und einladend sein. Und auch kein Mobbing oder respektloses Verhalten gegenüber anderen akzeptieren. Wir müssen uns umeinander kümmern. + +--- + +So helfen Sie anderen bei Fragen (in Diskussionen oder Problemen): + +### Die Frage verstehen + +* Fragen Sie sich, ob Sie verstehen, was das **Ziel** und der Anwendungsfall der fragenden Person ist. + +* Überprüfen Sie dann, ob die Frage (die überwiegende Mehrheit sind Fragen) **klar** ist. + +* In vielen Fällen handelt es sich bei der gestellten Frage um eine Lösung, die der Benutzer sich vorstellt, aber es könnte eine **bessere** Lösung geben. Wenn Sie das Problem und den Anwendungsfall besser verstehen, können Sie eine bessere **Alternativlösung** vorschlagen. + +* Wenn Sie die Frage nicht verstehen können, fragen Sie nach weiteren **Details**. + +### Das Problem reproduzieren + +In den meisten Fällen und bei den meisten Fragen ist etwas mit dem von der Person erstellten **eigenen Quellcode** los. + +In vielen Fällen wird nur ein Fragment des Codes gepostet, aber das reicht nicht aus, um **das Problem zu reproduzieren**. + +* Sie können die Person darum bitten, ein minimales, reproduzierbares Beispiel bereitzustellen, welches Sie **kopieren, einfügen** und lokal ausführen können, um den gleichen Fehler oder das gleiche Verhalten zu sehen, das die Person sieht, oder um ihren Anwendungsfall besser zu verstehen. + +* Wenn Sie in Geberlaune sind, können Sie versuchen, selbst ein solches Beispiel zu erstellen, nur basierend auf der Beschreibung des Problems. Denken Sie jedoch daran, dass dies viel Zeit in Anspruch nehmen kann und dass es besser sein kann, zunächst um eine Klärung des Problems zu bitten. + +### Lösungen vorschlagen + +* Nachdem Sie die Frage verstanden haben, können Sie eine mögliche **Antwort** geben. + +* In vielen Fällen ist es besser, das **zugrunde liegende Problem oder den Anwendungsfall** zu verstehen, da es möglicherweise einen besseren Weg zur Lösung gibt als das, was die Person versucht. + +### Um Schließung bitten + +Wenn die Person antwortet, besteht eine hohe Chance, dass Sie ihr Problem gelöst haben. Herzlichen Glückwunsch, **Sie sind ein Held**! 🦸 + +* Wenn es tatsächlich das Problem gelöst hat, können Sie sie darum bitten: + + * In GitHub-Diskussionen: den Kommentar als **Antwort** zu markieren. + * In GitHub-Issues: Das Issue zu **schließen**. + +## Das GitHub-Repository beobachten + +Sie können FastAPI auf GitHub „beobachten“ (Klicken Sie oben rechts auf die Schaltfläche „watch“): https://github.com/tiangolo/fastapi. 👀 + +Wenn Sie dann „Watching“ statt „Releases only“ auswählen, erhalten Sie Benachrichtigungen, wenn jemand ein neues Issue eröffnet oder eine neue Frage stellt. Sie können auch spezifizieren, dass Sie nur über neue Issues, Diskussionen, PRs, usw. benachrichtigt werden möchten. + +Dann können Sie versuchen, bei der Lösung solcher Fragen zu helfen. + +## Fragen stellen + +Sie können im GitHub-Repository eine neue Frage erstellen, zum Beispiel: + +* Stellen Sie eine **Frage** oder bitten Sie um Hilfe mit einem **Problem**. +* Schlagen Sie eine neue **Funktionalität** vor. + +**Hinweis**: Wenn Sie das tun, bitte ich Sie, auch anderen zu helfen. 😉 + +## Pull Requests prüfen + +Sie können mir helfen, Pull Requests von anderen zu überprüfen (Review). + +Noch einmal, bitte versuchen Sie Ihr Bestes, freundlich zu sein. 🤗 + +--- + +Hier ist, was Sie beachten sollten und wie Sie einen Pull Request überprüfen: + +### Das Problem verstehen + +* Stellen Sie zunächst sicher, dass Sie **das Problem verstehen**, welches der Pull Request zu lösen versucht. Möglicherweise gibt es eine längere Diskussion dazu in einer GitHub-Diskussion oder einem GitHub-Issue. + +* Es besteht auch eine gute Chance, dass der Pull Request nicht wirklich benötigt wird, da das Problem auf **andere Weise** gelöst werden kann. Dann können Sie das vorschlagen oder danach fragen. + +### Der Stil ist nicht so wichtig + +* Machen Sie sich nicht zu viele Gedanken über Dinge wie den Stil von Commit-Nachrichten, ich werde den Commit manuell zusammenführen und anpassen. + +* Machen Sie sich auch keine Sorgen über Stilregeln, es gibt bereits automatisierte Tools, die das überprüfen. + +Und wenn es irgendeinen anderen Stil- oder Konsistenz-Bedarf gibt, bitte ich direkt darum oder füge zusätzliche Commits mit den erforderlichen Änderungen hinzu. + +### Den Code überprüfen + +* Prüfen und lesen Sie den Code, fragen Sie sich, ob er Sinn macht, **führen Sie ihn lokal aus** und testen Sie, ob er das Problem tatsächlich löst. + +* Schreiben Sie dann einen **Kommentar** und berichten, dass Sie das getan haben. So weiß ich, dass Sie ihn wirklich überprüft haben. + +!!! info + Leider kann ich PRs, nur weil sie von Mehreren gutgeheißen wurden, nicht einfach vertrauen. + + Es ist mehrmals passiert, dass es PRs mit drei, fünf oder mehr Zustimmungen gibt, wahrscheinlich weil die Beschreibung ansprechend ist, aber wenn ich die PRs überprüfe, sind sie tatsächlich fehlerhaft, haben einen Bug, oder lösen das Problem nicht, welches sie behaupten, zu lösen. 😅 + + Daher ist es wirklich wichtig, dass Sie den Code tatsächlich lesen und ausführen und mir in den Kommentaren mitteilen, dass Sie dies getan haben. 🤓 + +* Wenn der PR irgendwie vereinfacht werden kann, fragen Sie ruhig danach, aber seien Sie nicht zu wählerisch, es gibt viele subjektive Standpunkte (und ich habe auch meinen eigenen 🙈), also ist es besser, wenn man sich auf die wesentlichen Dinge konzentriert. + +### Tests + +* Helfen Sie mir zu überprüfen, dass der PR **Tests** hat. + +* Überprüfen Sie, dass diese Tests vor dem PR **fehlschlagen**. 🚨 + +* Überprüfen Sie, dass diese Tests nach dem PR **bestanden** werden. ✅ + +* Viele PRs haben keine Tests. Sie können den Autor daran **erinnern**, Tests hinzuzufügen, oder Sie können sogar selbst einige Tests **vorschlagen**. Das ist eines der Dinge, die die meiste Zeit in Anspruch nehmen, und dabei können Sie viel helfen. + +* Kommentieren Sie auch hier anschließend, was Sie versucht haben, sodass ich weiß, dass Sie es überprüft haben. 🤓 + +## Einen Pull Request erstellen + +Sie können zum Quellcode mit Pull Requests [beitragen](contributing.md){.internal-link target=_blank}, zum Beispiel: + +* Um einen Tippfehler zu beheben, den Sie in der Dokumentation gefunden haben. +* Um einen Artikel, ein Video oder einen Podcast über FastAPI zu teilen, den Sie erstellt oder gefunden haben, indem Sie diese Datei bearbeiten. + * Stellen Sie sicher, dass Sie Ihren Link am Anfang des entsprechenden Abschnitts einfügen. +* Um zu helfen, [die Dokumentation in Ihre Sprache zu übersetzen](contributing.md#ubersetzungen){.internal-link target=_blank}. + * Sie können auch dabei helfen, die von anderen erstellten Übersetzungen zu überprüfen (Review). +* Um neue Dokumentationsabschnitte vorzuschlagen. +* Um ein bestehendes Problem / einen bestehenden Bug zu beheben. + * Stellen Sie sicher, dass Sie Tests hinzufügen. +* Um eine neue Funktionalität hinzuzufügen. + * Stellen Sie sicher, dass Sie Tests hinzufügen. + * Stellen Sie sicher, dass Sie Dokumentation hinzufügen, falls das notwendig ist. + +## FastAPI pflegen + +Helfen Sie mir, **FastAPI** instand zu halten! 🤓 + +Es gibt viel zu tun, und das meiste davon können **SIE** tun. + +Die Hauptaufgaben, die Sie jetzt erledigen können, sind: + +* [Helfen Sie anderen bei Fragen auf GitHub](#anderen-bei-fragen-auf-github-helfen){.internal-link target=_blank} (siehe Abschnitt oben). +* [Prüfen Sie Pull Requests](#pull-requests-prufen){.internal-link target=_blank} (siehe Abschnitt oben). + +Diese beiden Dinge sind es, die **die meiste Zeit in Anspruch nehmen**. Das ist die Hauptarbeit bei der Wartung von FastAPI. + +Wenn Sie mir dabei helfen können, **helfen Sie mir, FastAPI am Laufen zu erhalten** und sorgen dafür, dass es weiterhin **schneller und besser voranschreitet**. 🚀 + +## Beim Chat mitmachen + +Treten Sie dem 👥 Discord-Chatserver 👥 bei und treffen Sie sich mit anderen Mitgliedern der FastAPI-Community. + +!!! tip "Tipp" + Wenn Sie Fragen haben, stellen Sie sie bei GitHub Diskussionen, es besteht eine viel bessere Chance, dass Sie hier Hilfe von den [FastAPI-Experten](fastapi-people.md#experten){.internal-link target=_blank} erhalten. + + Nutzen Sie den Chat nur für andere allgemeine Gespräche. + +### Den Chat nicht für Fragen verwenden + +Bedenken Sie, da Chats mehr „freie Konversation“ ermöglichen, dass es verlockend ist, Fragen zu stellen, die zu allgemein und schwierig zu beantworten sind, sodass Sie möglicherweise keine Antworten erhalten. + +Auf GitHub hilft Ihnen die Vorlage dabei, die richtige Frage zu schreiben, sodass Sie leichter eine gute Antwort erhalten oder das Problem sogar selbst lösen können, noch bevor Sie fragen. Und auf GitHub kann ich sicherstellen, dass ich immer alles beantworte, auch wenn es einige Zeit dauert. Ich persönlich kann das mit den Chat-Systemen nicht machen. 😅 + +Unterhaltungen in den Chat-Systemen sind außerdem nicht so leicht durchsuchbar wie auf GitHub, sodass Fragen und Antworten möglicherweise im Gespräch verloren gehen. Und nur die auf GitHub machen einen [FastAPI-Experten](fastapi-people.md#experten){.internal-link target=_blank}, Sie werden also höchstwahrscheinlich mehr Aufmerksamkeit auf GitHub erhalten. + +Auf der anderen Seite gibt es Tausende von Benutzern in den Chat-Systemen, sodass die Wahrscheinlichkeit hoch ist, dass Sie dort fast immer jemanden zum Reden finden. 😄 + +## Den Autor sponsern + +Sie können den Autor (mich) auch über GitHub-Sponsoren finanziell unterstützen. + +Dort könnten Sie mir als Dankeschön einen Kaffee spendieren ☕️. 😄 + +Und Sie können auch Silber- oder Gold-Sponsor für FastAPI werden. 🏅🎉 + +## Die Tools sponsern, die FastAPI unterstützen + +Wie Sie in der Dokumentation gesehen haben, steht FastAPI auf den Schultern von Giganten, Starlette und Pydantic. + +Sie können auch sponsern: + +* Samuel Colvin (Pydantic) +* Encode (Starlette, Uvicorn) + +--- + +Danke! 🚀 diff --git a/docs/de/docs/help/index.md b/docs/de/docs/help/index.md new file mode 100644 index 0000000000000..8fdc4a0497d13 --- /dev/null +++ b/docs/de/docs/help/index.md @@ -0,0 +1,3 @@ +# Hilfe + +Helfen und Hilfe erhalten, beitragen, mitmachen. 🤝 diff --git a/docs/de/docs/history-design-future.md b/docs/de/docs/history-design-future.md new file mode 100644 index 0000000000000..22597b1f5a81b --- /dev/null +++ b/docs/de/docs/history-design-future.md @@ -0,0 +1,79 @@ +# Geschichte, Design und Zukunft + +Vor einiger Zeit fragte ein **FastAPI**-Benutzer: + +> Was ist die Geschichte dieses Projekts? Es scheint, als wäre es in ein paar Wochen aus dem Nichts zu etwas Großartigem geworden [...] + +Hier ist ein wenig über diese Geschichte. + +## Alternativen + +Ich habe seit mehreren Jahren APIs mit komplexen Anforderungen (maschinelles Lernen, verteilte Systeme, asynchrone Jobs, NoSQL-Datenbanken, usw.) erstellt und leitete mehrere Entwicklerteams. + +Dabei musste ich viele Alternativen untersuchen, testen und nutzen. + +Die Geschichte von **FastAPI** ist zu einem großen Teil die Geschichte seiner Vorgänger. + +Wie im Abschnitt [Alternativen](alternatives.md){.internal-link target=_blank} gesagt: + +
+ +**FastAPI** würde ohne die frühere Arbeit anderer nicht existieren. + +Es wurden zuvor viele Tools entwickelt, die als Inspiration für seine Entwicklung dienten. + +Ich habe die Schaffung eines neuen Frameworks viele Jahre lang vermieden. Zuerst habe ich versucht, alle von **FastAPI** abgedeckten Funktionen mithilfe vieler verschiedener Frameworks, Plugins und Tools zu lösen. + +Aber irgendwann gab es keine andere Möglichkeit, als etwas zu schaffen, das all diese Funktionen bereitstellte, die besten Ideen früherer Tools aufnahm und diese auf die bestmögliche Weise kombinierte, wobei Sprachfunktionen verwendet wurden, die vorher noch nicht einmal verfügbar waren (Python 3.6+ Typhinweise). + +
+ +## Investigation + +Durch die Nutzung all dieser vorherigen Alternativen hatte ich die Möglichkeit, von allen zu lernen, Ideen aufzunehmen und sie auf die beste Weise zu kombinieren, die ich für mich und die Entwicklerteams, mit denen ich zusammengearbeitet habe, finden konnte. + +Es war beispielsweise klar, dass es idealerweise auf Standard-Python-Typhinweisen basieren sollte. + +Der beste Ansatz bestand außerdem darin, bereits bestehende Standards zu nutzen. + +Bevor ich also überhaupt angefangen habe, **FastAPI** zu schreiben, habe ich mehrere Monate damit verbracht, die Spezifikationen für OpenAPI, JSON Schema, OAuth2, usw. zu studieren und deren Beziehungen, Überschneidungen und Unterschiede zu verstehen. + +## Design + +Dann habe ich einige Zeit damit verbracht, die Entwickler-„API“ zu entwerfen, die ich als Benutzer haben wollte (als Entwickler, welcher FastAPI verwendet). + +Ich habe mehrere Ideen in den beliebtesten Python-Editoren getestet: PyCharm, VS Code, Jedi-basierte Editoren. + +Laut der letzten Python-Entwickler-Umfrage, deckt das etwa 80 % der Benutzer ab. + +Das bedeutet, dass **FastAPI** speziell mit den Editoren getestet wurde, die von 80 % der Python-Entwickler verwendet werden. Und da die meisten anderen Editoren in der Regel ähnlich funktionieren, sollten alle diese Vorteile für praktisch alle Editoren funktionieren. + +Auf diese Weise konnte ich die besten Möglichkeiten finden, die Codeverdoppelung so weit wie möglich zu reduzieren, überall Autovervollständigung, Typ- und Fehlerprüfungen, usw. zu gewährleisten. + +Alles auf eine Weise, die allen Entwicklern das beste Entwicklungserlebnis bot. + +## Anforderungen + +Nachdem ich mehrere Alternativen getestet hatte, entschied ich, dass ich **Pydantic** wegen seiner Vorteile verwenden würde. + +Dann habe ich zu dessen Code beigetragen, um es vollständig mit JSON Schema kompatibel zu machen, und so verschiedene Möglichkeiten zum Definieren von einschränkenden Deklarationen (Constraints) zu unterstützen, und die Editorunterstützung (Typprüfungen, Codevervollständigung) zu verbessern, basierend auf den Tests in mehreren Editoren. + +Während der Entwicklung habe ich auch zu **Starlette** beigetragen, der anderen Schlüsselanforderung. + +## Entwicklung + +Als ich mit der Erstellung von **FastAPI** selbst begann, waren die meisten Teile bereits vorhanden, das Design definiert, die Anforderungen und Tools bereit und das Wissen über die Standards und Spezifikationen klar und frisch. + +## Zukunft + +Zu diesem Zeitpunkt ist bereits klar, dass **FastAPI** mit seinen Ideen für viele Menschen nützlich ist. + +Es wird gegenüber früheren Alternativen gewählt, da es für viele Anwendungsfälle besser geeignet ist. + +Viele Entwickler und Teams verlassen sich bei ihren Projekten bereits auf **FastAPI** (einschließlich mir und meinem Team). + +Dennoch stehen uns noch viele Verbesserungen und Funktionen bevor. + +**FastAPI** hat eine große Zukunft vor sich. + +Und [Ihre Hilfe](help-fastapi.md){.internal-link target=_blank} wird sehr geschätzt. diff --git a/docs/de/docs/how-to/conditional-openapi.md b/docs/de/docs/how-to/conditional-openapi.md new file mode 100644 index 0000000000000..7f277bb888858 --- /dev/null +++ b/docs/de/docs/how-to/conditional-openapi.md @@ -0,0 +1,58 @@ +# Bedingte OpenAPI + +Bei Bedarf können Sie OpenAPI mithilfe von Einstellungen und Umgebungsvariablen abhängig von der Umgebung bedingt konfigurieren und sogar vollständig deaktivieren. + +## Über Sicherheit, APIs und Dokumentation + +Das Verstecken Ihrer Dokumentationsoberflächen in der Produktion *sollte nicht* die Methode sein, Ihre API zu schützen. + +Dadurch wird Ihrer API keine zusätzliche Sicherheit hinzugefügt, die *Pfadoperationen* sind weiterhin dort verfügbar, wo sie sich befinden. + +Wenn Ihr Code eine Sicherheitslücke aufweist, ist diese weiterhin vorhanden. + +Das Verstecken der Dokumentation macht es nur schwieriger zu verstehen, wie mit Ihrer API interagiert werden kann, und könnte es auch schwieriger machen, diese in der Produktion zu debuggen. Man könnte es einfach als eine Form von Security through obscurity betrachten. + +Wenn Sie Ihre API sichern möchten, gibt es mehrere bessere Dinge, die Sie tun können, zum Beispiel: + +* Stellen Sie sicher, dass Sie über gut definierte Pydantic-Modelle für Ihre Requestbodys und Responses verfügen. +* Konfigurieren Sie alle erforderlichen Berechtigungen und Rollen mithilfe von Abhängigkeiten. +* Speichern Sie niemals Klartext-Passwörter, sondern nur Passwort-Hashes. +* Implementieren und verwenden Sie gängige kryptografische Tools wie Passlib und JWT-Tokens, usw. +* Fügen Sie bei Bedarf detailliertere Berechtigungskontrollen mit OAuth2-Scopes hinzu. +* ... usw. + +Dennoch kann es sein, dass Sie einen ganz bestimmten Anwendungsfall haben, bei dem Sie die API-Dokumentation für eine bestimmte Umgebung (z. B. für die Produktion) oder abhängig von Konfigurationen aus Umgebungsvariablen wirklich deaktivieren müssen. + +## Bedingte OpenAPI aus Einstellungen und Umgebungsvariablen + +Sie können problemlos dieselben Pydantic-Einstellungen verwenden, um Ihre generierte OpenAPI und die Dokumentationsoberflächen zu konfigurieren. + +Zum Beispiel: + +```Python hl_lines="6 11" +{!../../../docs_src/conditional_openapi/tutorial001.py!} +``` + +Hier deklarieren wir die Einstellung `openapi_url` mit dem gleichen Defaultwert `"/openapi.json"`. + +Und dann verwenden wir das beim Erstellen der `FastAPI`-App. + +Dann könnten Sie OpenAPI (einschließlich der Dokumentationsoberflächen) deaktivieren, indem Sie die Umgebungsvariable `OPENAPI_URL` auf einen leeren String setzen, wie zum Beispiel: + +
+ +```console +$ OPENAPI_URL= uvicorn main:app + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Wenn Sie dann zu den URLs unter `/openapi.json`, `/docs` oder `/redoc` gehen, erhalten Sie lediglich einen `404 Not Found`-Fehler, wie: + +```JSON +{ + "detail": "Not Found" +} +``` diff --git a/docs/de/docs/how-to/configure-swagger-ui.md b/docs/de/docs/how-to/configure-swagger-ui.md new file mode 100644 index 0000000000000..c18091efd1681 --- /dev/null +++ b/docs/de/docs/how-to/configure-swagger-ui.md @@ -0,0 +1,78 @@ +# Swagger-Oberfläche konfigurieren + +Sie können einige zusätzliche Parameter der Swagger-Oberfläche konfigurieren. + +Um diese zu konfigurieren, übergeben Sie das Argument `swagger_ui_parameters` beim Erstellen des `FastAPI()`-App-Objekts oder an die Funktion `get_swagger_ui_html()`. + +`swagger_ui_parameters` empfängt ein Dict mit den Konfigurationen, die direkt an die Swagger-Oberfläche übergeben werden. + +FastAPI konvertiert die Konfigurationen nach **JSON**, um diese mit JavaScript kompatibel zu machen, da die Swagger-Oberfläche das benötigt. + +## Syntaxhervorhebung deaktivieren + +Sie könnten beispielsweise die Syntaxhervorhebung in der Swagger-Oberfläche deaktivieren. + +Ohne Änderung der Einstellungen ist die Syntaxhervorhebung standardmäßig aktiviert: + + + +Sie können sie jedoch deaktivieren, indem Sie `syntaxHighlight` auf `False` setzen: + +```Python hl_lines="3" +{!../../../docs_src/configure_swagger_ui/tutorial001.py!} +``` + +... und dann zeigt die Swagger-Oberfläche die Syntaxhervorhebung nicht mehr an: + + + +## Das Theme ändern + +Auf die gleiche Weise könnten Sie das Theme der Syntaxhervorhebung mit dem Schlüssel `syntaxHighlight.theme` festlegen (beachten Sie, dass er einen Punkt in der Mitte hat): + +```Python hl_lines="3" +{!../../../docs_src/configure_swagger_ui/tutorial002.py!} +``` + +Obige Konfiguration würde das Theme für die Farbe der Syntaxhervorhebung ändern: + + + +## Defaultparameter der Swagger-Oberfläche ändern + +FastAPI enthält einige Defaultkonfigurationsparameter, die für die meisten Anwendungsfälle geeignet sind. + +Es umfasst die folgenden Defaultkonfigurationen: + +```Python +{!../../../fastapi/openapi/docs.py[ln:7-23]!} +``` + +Sie können jede davon überschreiben, indem Sie im Argument `swagger_ui_parameters` einen anderen Wert festlegen. + +Um beispielsweise `deepLinking` zu deaktivieren, könnten Sie folgende Einstellungen an `swagger_ui_parameters` übergeben: + +```Python hl_lines="3" +{!../../../docs_src/configure_swagger_ui/tutorial003.py!} +``` + +## Andere Parameter der Swagger-Oberfläche + +Um alle anderen möglichen Konfigurationen zu sehen, die Sie verwenden können, lesen Sie die offizielle Dokumentation für die Parameter der Swagger-Oberfläche. + +## JavaScript-basierte Einstellungen + +Die Swagger-Oberfläche erlaubt, dass andere Konfigurationen auch **JavaScript**-Objekte sein können (z. B. JavaScript-Funktionen). + +FastAPI umfasst auch diese Nur-JavaScript-`presets`-Einstellungen: + +```JavaScript +presets: [ + SwaggerUIBundle.presets.apis, + SwaggerUIBundle.SwaggerUIStandalonePreset +] +``` + +Dabei handelt es sich um **JavaScript**-Objekte, nicht um Strings, daher können Sie diese nicht direkt vom Python-Code aus übergeben. + +Wenn Sie solche JavaScript-Konfigurationen verwenden müssen, können Sie einen der früher genannten Wege verwenden. Überschreiben Sie alle *Pfadoperationen* der Swagger-Oberfläche und schreiben Sie manuell jedes benötigte JavaScript. diff --git a/docs/de/docs/how-to/custom-docs-ui-assets.md b/docs/de/docs/how-to/custom-docs-ui-assets.md new file mode 100644 index 0000000000000..991eaf26922f1 --- /dev/null +++ b/docs/de/docs/how-to/custom-docs-ui-assets.md @@ -0,0 +1,199 @@ +# Statische Assets der Dokumentationsoberfläche (selbst hosten) + +Die API-Dokumentation verwendet **Swagger UI** und **ReDoc**, und jede dieser Dokumentationen benötigt einige JavaScript- und CSS-Dateien. + +Standardmäßig werden diese Dateien von einem CDN bereitgestellt. + +Es ist jedoch möglich, das anzupassen, ein bestimmtes CDN festzulegen oder die Dateien selbst bereitzustellen. + +## Benutzerdefiniertes CDN für JavaScript und CSS + +Nehmen wir an, Sie möchten ein anderes CDN verwenden, zum Beispiel möchten Sie `https://unpkg.com/` verwenden. + +Das kann nützlich sein, wenn Sie beispielsweise in einem Land leben, in dem bestimmte URLs eingeschränkt sind. + +### Die automatischen Dokumentationen deaktivieren + +Der erste Schritt besteht darin, die automatischen Dokumentationen zu deaktivieren, da diese standardmäßig das Standard-CDN verwenden. + +Um diese zu deaktivieren, setzen Sie deren URLs beim Erstellen Ihrer `FastAPI`-App auf `None`: + +```Python hl_lines="8" +{!../../../docs_src/custom_docs_ui/tutorial001.py!} +``` + +### Die benutzerdefinierten Dokumentationen hinzufügen + +Jetzt können Sie die *Pfadoperationen* für die benutzerdefinierten Dokumentationen erstellen. + +Sie können die internen Funktionen von FastAPI wiederverwenden, um die HTML-Seiten für die Dokumentation zu erstellen und ihnen die erforderlichen Argumente zu übergeben: + +* `openapi_url`: die URL, unter welcher die HTML-Seite für die Dokumentation das OpenAPI-Schema für Ihre API abrufen kann. Sie können hier das Attribut `app.openapi_url` verwenden. +* `title`: der Titel Ihrer API. +* `oauth2_redirect_url`: Sie können hier `app.swagger_ui_oauth2_redirect_url` verwenden, um die Standardeinstellung zu verwenden. +* `swagger_js_url`: die URL, unter welcher der HTML-Code für Ihre Swagger-UI-Dokumentation die **JavaScript**-Datei abrufen kann. Dies ist die benutzerdefinierte CDN-URL. +* `swagger_css_url`: die URL, unter welcher der HTML-Code für Ihre Swagger-UI-Dokumentation die **CSS**-Datei abrufen kann. Dies ist die benutzerdefinierte CDN-URL. + +Und genau so für ReDoc ... + +```Python hl_lines="2-6 11-19 22-24 27-33" +{!../../../docs_src/custom_docs_ui/tutorial001.py!} +``` + +!!! tip "Tipp" + Die *Pfadoperation* für `swagger_ui_redirect` ist ein Hilfsmittel bei der Verwendung von OAuth2. + + Wenn Sie Ihre API mit einem OAuth2-Anbieter integrieren, können Sie sich authentifizieren und mit den erworbenen Anmeldeinformationen zur API-Dokumentation zurückkehren. Und mit ihr interagieren, die echte OAuth2-Authentifizierung verwendend. + + Swagger UI erledigt das hinter den Kulissen für Sie, benötigt aber diesen „Umleitungs“-Helfer. + +### Eine *Pfadoperation* erstellen, um es zu testen + +Um nun testen zu können, ob alles funktioniert, erstellen Sie eine *Pfadoperation*: + +```Python hl_lines="36-38" +{!../../../docs_src/custom_docs_ui/tutorial001.py!} +``` + +### Es ausprobieren + +Jetzt sollten Sie in der Lage sein, zu Ihrer Dokumentation auf http://127.0.0.1:8000/docs zu gehen und die Seite neu zuladen, die Assets werden nun vom neuen CDN geladen. + +## JavaScript und CSS für die Dokumentation selbst hosten + +Das Selbst Hosten von JavaScript und CSS kann nützlich sein, wenn Sie beispielsweise möchten, dass Ihre Anwendung auch offline, ohne bestehenden Internetzugang oder in einem lokalen Netzwerk weiter funktioniert. + +Hier erfahren Sie, wie Sie diese Dateien selbst in derselben FastAPI-App bereitstellen und die Dokumentation für deren Verwendung konfigurieren. + +### Projektdateistruktur + +Nehmen wir an, die Dateistruktur Ihres Projekts sieht folgendermaßen aus: + +``` +. +├── app +│ ├── __init__.py +│ ├── main.py +``` + +Erstellen Sie jetzt ein Verzeichnis zum Speichern dieser statischen Dateien. + +Ihre neue Dateistruktur könnte so aussehen: + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +└── static/ +``` + +### Die Dateien herunterladen + +Laden Sie die für die Dokumentation benötigten statischen Dateien herunter und legen Sie diese im Verzeichnis `static/` ab. + +Sie können wahrscheinlich mit der rechten Maustaste auf jeden Link klicken und eine Option wie etwa `Link speichern unter...` auswählen. + +**Swagger UI** verwendet folgende Dateien: + +* `swagger-ui-bundle.js` +* `swagger-ui.css` + +Und **ReDoc** verwendet diese Datei: + +* `redoc.standalone.js` + +Danach könnte Ihre Dateistruktur wie folgt aussehen: + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +└── static + ├── redoc.standalone.js + ├── swagger-ui-bundle.js + └── swagger-ui.css +``` + +### Die statischen Dateien bereitstellen + +* Importieren Sie `StaticFiles`. +* „Mounten“ Sie eine `StaticFiles()`-Instanz in einem bestimmten Pfad. + +```Python hl_lines="7 11" +{!../../../docs_src/custom_docs_ui/tutorial002.py!} +``` + +### Die statischen Dateien testen + +Starten Sie Ihre Anwendung und gehen Sie auf http://127.0.0.1:8000/static/redoc.standalone.js. + +Sie sollten eine sehr lange JavaScript-Datei für **ReDoc** sehen. + +Sie könnte beginnen mit etwas wie: + +```JavaScript +/*! + * ReDoc - OpenAPI/Swagger-generated API Reference Documentation + * ------------------------------------------------------------- + * Version: "2.0.0-rc.18" + * Repo: https://github.com/Redocly/redoc + */ +!function(e,t){"object"==typeof exports&&"object"==typeof m + +... +``` + +Das zeigt, dass Sie statische Dateien aus Ihrer Anwendung bereitstellen können und dass Sie die statischen Dateien für die Dokumentation an der richtigen Stelle platziert haben. + +Jetzt können wir die Anwendung so konfigurieren, dass sie diese statischen Dateien für die Dokumentation verwendet. + +### Die automatischen Dokumentationen deaktivieren, für statische Dateien + +Wie bei der Verwendung eines benutzerdefinierten CDN besteht der erste Schritt darin, die automatischen Dokumentationen zu deaktivieren, da diese standardmäßig das CDN verwenden. + +Um diese zu deaktivieren, setzen Sie deren URLs beim Erstellen Ihrer `FastAPI`-App auf `None`: + +```Python hl_lines="9" +{!../../../docs_src/custom_docs_ui/tutorial002.py!} +``` + +### Die benutzerdefinierten Dokumentationen, mit statischen Dateien, hinzufügen + +Und genau wie bei einem benutzerdefinierten CDN können Sie jetzt die *Pfadoperationen* für die benutzerdefinierten Dokumentationen erstellen. + +Auch hier können Sie die internen Funktionen von FastAPI wiederverwenden, um die HTML-Seiten für die Dokumentationen zu erstellen, und diesen die erforderlichen Argumente übergeben: + +* `openapi_url`: die URL, unter der die HTML-Seite für die Dokumentation das OpenAPI-Schema für Ihre API abrufen kann. Sie können hier das Attribut `app.openapi_url` verwenden. +* `title`: der Titel Ihrer API. +* `oauth2_redirect_url`: Sie können hier `app.swagger_ui_oauth2_redirect_url` verwenden, um die Standardeinstellung zu verwenden. +* `swagger_js_url`: die URL, unter welcher der HTML-Code für Ihre Swagger-UI-Dokumentation die **JavaScript**-Datei abrufen kann. **Das ist die, welche jetzt von Ihrer eigenen Anwendung bereitgestellt wird**. +* `swagger_css_url`: die URL, unter welcher der HTML-Code für Ihre Swagger-UI-Dokumentation die **CSS**-Datei abrufen kann. **Das ist die, welche jetzt von Ihrer eigenen Anwendung bereitgestellt wird**. + +Und genau so für ReDoc ... + +```Python hl_lines="2-6 14-22 25-27 30-36" +{!../../../docs_src/custom_docs_ui/tutorial002.py!} +``` + +!!! tip "Tipp" + Die *Pfadoperation* für `swagger_ui_redirect` ist ein Hilfsmittel bei der Verwendung von OAuth2. + + Wenn Sie Ihre API mit einem OAuth2-Anbieter integrieren, können Sie sich authentifizieren und mit den erworbenen Anmeldeinformationen zur API-Dokumentation zurückkehren. Und mit ihr interagieren, die echte OAuth2-Authentifizierung verwendend. + + Swagger UI erledigt das hinter den Kulissen für Sie, benötigt aber diesen „Umleitungs“-Helfer. + +### Eine *Pfadoperation* erstellen, um statische Dateien zu testen + +Um nun testen zu können, ob alles funktioniert, erstellen Sie eine *Pfadoperation*: + +```Python hl_lines="39-41" +{!../../../docs_src/custom_docs_ui/tutorial002.py!} +``` + +### Benutzeroberfläche, mit statischen Dateien, testen + +Jetzt sollten Sie in der Lage sein, Ihr WLAN zu trennen, gehen Sie zu Ihrer Dokumentation unter http://127.0.0.1:8000/docs und laden Sie die Seite neu. + +Und selbst ohne Internet könnten Sie die Dokumentation für Ihre API sehen und damit interagieren. diff --git a/docs/de/docs/how-to/custom-request-and-route.md b/docs/de/docs/how-to/custom-request-and-route.md new file mode 100644 index 0000000000000..b51a20bfce4e9 --- /dev/null +++ b/docs/de/docs/how-to/custom-request-and-route.md @@ -0,0 +1,109 @@ +# Benutzerdefinierte Request- und APIRoute-Klasse + +In einigen Fällen möchten Sie möglicherweise die von den Klassen `Request` und `APIRoute` verwendete Logik überschreiben. + +Das kann insbesondere eine gute Alternative zur Logik in einer Middleware sein. + +Wenn Sie beispielsweise den Requestbody lesen oder manipulieren möchten, bevor er von Ihrer Anwendung verarbeitet wird. + +!!! danger "Gefahr" + Dies ist eine „fortgeschrittene“ Funktion. + + Wenn Sie gerade erst mit **FastAPI** beginnen, möchten Sie diesen Abschnitt vielleicht überspringen. + +## Anwendungsfälle + +Einige Anwendungsfälle sind: + +* Konvertieren von Nicht-JSON-Requestbodys nach JSON (z. B. `msgpack`). +* Dekomprimierung gzip-komprimierter Requestbodys. +* Automatisches Loggen aller Requestbodys. + +## Handhaben von benutzerdefinierten Requestbody-Kodierungen + +Sehen wir uns an, wie Sie eine benutzerdefinierte `Request`-Unterklasse verwenden, um gzip-Requests zu dekomprimieren. + +Und eine `APIRoute`-Unterklasse zur Verwendung dieser benutzerdefinierten Requestklasse. + +### Eine benutzerdefinierte `GzipRequest`-Klasse erstellen + +!!! tip "Tipp" + Dies ist nur ein einfaches Beispiel, um zu demonstrieren, wie es funktioniert. Wenn Sie Gzip-Unterstützung benötigen, können Sie die bereitgestellte [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware){.internal-link target=_blank} verwenden. + +Zuerst erstellen wir eine `GzipRequest`-Klasse, welche die Methode `Request.body()` überschreibt, um den Body bei Vorhandensein eines entsprechenden Headers zu dekomprimieren. + +Wenn der Header kein `gzip` enthält, wird nicht versucht, den Body zu dekomprimieren. + +Auf diese Weise kann dieselbe Routenklasse gzip-komprimierte oder unkomprimierte Requests verarbeiten. + +```Python hl_lines="8-15" +{!../../../docs_src/custom_request_and_route/tutorial001.py!} +``` + +### Eine benutzerdefinierte `GzipRoute`-Klasse erstellen + +Als Nächstes erstellen wir eine benutzerdefinierte Unterklasse von `fastapi.routing.APIRoute`, welche `GzipRequest` nutzt. + +Dieses Mal wird die Methode `APIRoute.get_route_handler()` überschrieben. + +Diese Methode gibt eine Funktion zurück. Und diese Funktion empfängt einen Request und gibt eine Response zurück. + +Hier verwenden wir sie, um aus dem ursprünglichen Request einen `GzipRequest` zu erstellen. + +```Python hl_lines="18-26" +{!../../../docs_src/custom_request_and_route/tutorial001.py!} +``` + +!!! note "Technische Details" + Ein `Request` hat ein `request.scope`-Attribut, welches einfach ein Python-`dict` ist, welches die mit dem Request verbundenen Metadaten enthält. + + Ein `Request` hat auch ein `request.receive`, welches eine Funktion ist, die den Hauptteil des Requests empfängt. + + Das `scope`-`dict` und die `receive`-Funktion sind beide Teil der ASGI-Spezifikation. + + Und diese beiden Dinge, `scope` und `receive`, werden benötigt, um eine neue `Request`-Instanz zu erstellen. + + Um mehr über den `Request` zu erfahren, schauen Sie sich Starlettes Dokumentation zu Requests an. + +Das Einzige, was die von `GzipRequest.get_route_handler` zurückgegebene Funktion anders macht, ist die Konvertierung von `Request` in ein `GzipRequest`. + +Dabei kümmert sich unser `GzipRequest` um die Dekomprimierung der Daten (falls erforderlich), bevor diese an unsere *Pfadoperationen* weitergegeben werden. + +Danach ist die gesamte Verarbeitungslogik dieselbe. + +Aufgrund unserer Änderungen in `GzipRequest.body` wird der Requestbody jedoch bei Bedarf automatisch dekomprimiert, wenn er von **FastAPI** geladen wird. + +## Zugriff auf den Requestbody in einem Exceptionhandler + +!!! tip "Tipp" + Um dasselbe Problem zu lösen, ist es wahrscheinlich viel einfacher, den `body` in einem benutzerdefinierten Handler für `RequestValidationError` zu verwenden ([Fehlerbehandlung](../tutorial/handling-errors.md#den-requestvalidationerror-body-verwenden){.internal-link target=_blank}). + + Dieses Beispiel ist jedoch immer noch gültig und zeigt, wie mit den internen Komponenten interagiert wird. + +Wir können denselben Ansatz auch verwenden, um in einem Exceptionhandler auf den Requestbody zuzugreifen. + +Alles, was wir tun müssen, ist, den Request innerhalb eines `try`/`except`-Blocks zu handhaben: + +```Python hl_lines="13 15" +{!../../../docs_src/custom_request_and_route/tutorial002.py!} +``` + +Wenn eine Exception auftritt, befindet sich die `Request`-Instanz weiterhin im Gültigkeitsbereich, sodass wir den Requestbody lesen und bei der Fehlerbehandlung verwenden können: + +```Python hl_lines="16-18" +{!../../../docs_src/custom_request_and_route/tutorial002.py!} +``` + +## Benutzerdefinierte `APIRoute`-Klasse in einem Router + +Sie können auch den Parameter `route_class` eines `APIRouter` festlegen: + +```Python hl_lines="26" +{!../../../docs_src/custom_request_and_route/tutorial003.py!} +``` + +In diesem Beispiel verwenden die *Pfadoperationen* unter dem `router` die benutzerdefinierte `TimedRoute`-Klasse und haben in der Response einen zusätzlichen `X-Response-Time`-Header mit der Zeit, die zum Generieren der Response benötigt wurde: + +```Python hl_lines="13-20" +{!../../../docs_src/custom_request_and_route/tutorial003.py!} +``` diff --git a/docs/de/docs/how-to/extending-openapi.md b/docs/de/docs/how-to/extending-openapi.md new file mode 100644 index 0000000000000..2fbfa13e5a786 --- /dev/null +++ b/docs/de/docs/how-to/extending-openapi.md @@ -0,0 +1,87 @@ +# OpenAPI erweitern + +In einigen Fällen müssen Sie möglicherweise das generierte OpenAPI-Schema ändern. + +In diesem Abschnitt erfahren Sie, wie. + +## Der normale Vorgang + +Der normale (Standard-)Prozess ist wie folgt. + +Eine `FastAPI`-Anwendung (-Instanz) verfügt über eine `.openapi()`-Methode, von der erwartet wird, dass sie das OpenAPI-Schema zurückgibt. + +Als Teil der Erstellung des Anwendungsobjekts wird eine *Pfadoperation* für `/openapi.json` (oder welcher Wert für den Parameter `openapi_url` gesetzt wurde) registriert. + +Diese gibt lediglich eine JSON-Response zurück, mit dem Ergebnis der Methode `.openapi()` der Anwendung. + +Standardmäßig überprüft die Methode `.openapi()` die Eigenschaft `.openapi_schema`, um zu sehen, ob diese Inhalt hat, und gibt diesen zurück. + +Ist das nicht der Fall, wird der Inhalt mithilfe der Hilfsfunktion unter `fastapi.openapi.utils.get_openapi` generiert. + +Und diese Funktion `get_openapi()` erhält als Parameter: + +* `title`: Der OpenAPI-Titel, der in der Dokumentation angezeigt wird. +* `version`: Die Version Ihrer API, z. B. `2.5.0`. +* `openapi_version`: Die Version der verwendeten OpenAPI-Spezifikation. Standardmäßig die neueste Version: `3.1.0`. +* `summary`: Eine kurze Zusammenfassung der API. +* `description`: Die Beschreibung Ihrer API. Dies kann Markdown enthalten und wird in der Dokumentation angezeigt. +* `routes`: Eine Liste von Routen, dies sind alle registrierten *Pfadoperationen*. Sie stammen von `app.routes`. + +!!! info + Der Parameter `summary` ist in OpenAPI 3.1.0 und höher verfügbar und wird von FastAPI 0.99.0 und höher unterstützt. + +## Überschreiben der Standardeinstellungen + +Mithilfe der oben genannten Informationen können Sie dieselbe Hilfsfunktion verwenden, um das OpenAPI-Schema zu generieren und jeden benötigten Teil zu überschreiben. + +Fügen wir beispielsweise ReDocs OpenAPI-Erweiterung zum Einbinden eines benutzerdefinierten Logos hinzu. + +### Normales **FastAPI** + +Schreiben Sie zunächst wie gewohnt Ihre ganze **FastAPI**-Anwendung: + +```Python hl_lines="1 4 7-9" +{!../../../docs_src/extending_openapi/tutorial001.py!} +``` + +### Das OpenAPI-Schema generieren + +Verwenden Sie dann dieselbe Hilfsfunktion, um das OpenAPI-Schema innerhalb einer `custom_openapi()`-Funktion zu generieren: + +```Python hl_lines="2 15-21" +{!../../../docs_src/extending_openapi/tutorial001.py!} +``` + +### Das OpenAPI-Schema ändern + +Jetzt können Sie die ReDoc-Erweiterung hinzufügen und dem `info`-„Objekt“ im OpenAPI-Schema ein benutzerdefiniertes `x-logo` hinzufügen: + +```Python hl_lines="22-24" +{!../../../docs_src/extending_openapi/tutorial001.py!} +``` + +### Zwischenspeichern des OpenAPI-Schemas + +Sie können die Eigenschaft `.openapi_schema` als „Cache“ verwenden, um Ihr generiertes Schema zu speichern. + +Auf diese Weise muss Ihre Anwendung das Schema nicht jedes Mal generieren, wenn ein Benutzer Ihre API-Dokumentation öffnet. + +Es wird nur einmal generiert und dann wird dasselbe zwischengespeicherte Schema für die nächsten Requests verwendet. + +```Python hl_lines="13-14 25-26" +{!../../../docs_src/extending_openapi/tutorial001.py!} +``` + +### Die Methode überschreiben + +Jetzt können Sie die Methode `.openapi()` durch Ihre neue Funktion ersetzen. + +```Python hl_lines="29" +{!../../../docs_src/extending_openapi/tutorial001.py!} +``` + +### Testen + +Sobald Sie auf http://127.0.0.1:8000/redoc gehen, werden Sie sehen, dass Ihr benutzerdefiniertes Logo verwendet wird (in diesem Beispiel das Logo von **FastAPI**): + + diff --git a/docs/de/docs/how-to/general.md b/docs/de/docs/how-to/general.md new file mode 100644 index 0000000000000..b38b5fabfb6bf --- /dev/null +++ b/docs/de/docs/how-to/general.md @@ -0,0 +1,39 @@ +# Allgemeines – How-To – Rezepte + +Hier finden Sie mehrere Verweise auf andere Stellen in der Dokumentation, für allgemeine oder häufige Fragen. + +## Daten filtern – Sicherheit + +Um sicherzustellen, dass Sie nicht mehr Daten zurückgeben, als Sie sollten, lesen Sie die Dokumentation unter [Tutorial – Responsemodell – Rückgabetyp](../tutorial/response-model.md){.internal-link target=_blank}. + +## Dokumentations-Tags – OpenAPI + +Um Tags zu Ihren *Pfadoperationen* hinzuzufügen und diese in der Oberfläche der Dokumentation zu gruppieren, lesen Sie die Dokumentation unter [Tutorial – Pfadoperation-Konfiguration – Tags](../tutorial/path-operation-configuration.md#tags){.internal-link target=_blank}. + +## Zusammenfassung und Beschreibung in der Dokumentation – OpenAPI + +Um Ihren *Pfadoperationen* eine Zusammenfassung und Beschreibung hinzuzufügen und diese in der Oberfläche der Dokumentation anzuzeigen, lesen Sie die Dokumentation unter [Tutorial – Pfadoperation-Konfiguration – Zusammenfassung und Beschreibung](../tutorial/path-operation-configuration.md#zusammenfassung-und-beschreibung){.internal-link target=_blank}. + +## Beschreibung der Response in der Dokumentation – OpenAPI + +Um die Beschreibung der Response zu definieren, welche in der Oberfläche der Dokumentation angezeigt wird, lesen Sie die Dokumentation unter [Tutorial – Pfadoperation-Konfiguration – Beschreibung der Response](../tutorial/path-operation-configuration.md#beschreibung-der-response){.internal-link target=_blank}. + +## *Pfadoperation* in der Dokumentation deprecaten – OpenAPI + +Um eine *Pfadoperation* zu deprecaten – sie als veraltet zu markieren – und das in der Oberfläche der Dokumentation anzuzeigen, lesen Sie die Dokumentation unter [Tutorial – Pfadoperation-Konfiguration – Deprecaten](../tutorial/path-operation-configuration.md#eine-pfadoperation-deprecaten){.internal-link target=_blank}. + +## Daten in etwas JSON-kompatibles konvertieren + +Um Daten in etwas JSON-kompatibles zu konvertieren, lesen Sie die Dokumentation unter [Tutorial – JSON-kompatibler Encoder](../tutorial/encoder.md){.internal-link target=_blank}. + +## OpenAPI-Metadaten – Dokumentation + +Um Metadaten zu Ihrem OpenAPI-Schema hinzuzufügen, einschließlich einer Lizenz, Version, Kontakt, usw., lesen Sie die Dokumentation unter [Tutorial – Metadaten und URLs der Dokumentationen](../tutorial/metadata.md){.internal-link target=_blank}. + +## Benutzerdefinierte OpenAPI-URL + +Um die OpenAPI-URL anzupassen (oder zu entfernen), lesen Sie die Dokumentation unter [Tutorial – Metadaten und URLs der Dokumentationen](../tutorial/metadata.md#openapi-url){.internal-link target=_blank}. + +## URLs der OpenAPI-Dokumentationen + +Um die URLs zu aktualisieren, die für die automatisch generierten Dokumentations-Oberflächen verwendet werden, lesen Sie die Dokumentation unter [Tutorial – Metadaten und URLs der Dokumentationen](../tutorial/metadata.md#urls-der-dokumentationen){.internal-link target=_blank}. diff --git a/docs/de/docs/how-to/graphql.md b/docs/de/docs/how-to/graphql.md new file mode 100644 index 0000000000000..9b03e8e05870c --- /dev/null +++ b/docs/de/docs/how-to/graphql.md @@ -0,0 +1,56 @@ +# GraphQL + +Da **FastAPI** auf dem **ASGI**-Standard basiert, ist es sehr einfach, jede **GraphQL**-Bibliothek zu integrieren, die auch mit ASGI kompatibel ist. + +Sie können normale FastAPI-*Pfadoperationen* mit GraphQL in derselben Anwendung kombinieren. + +!!! tip "Tipp" + **GraphQL** löst einige sehr spezifische Anwendungsfälle. + + Es hat **Vorteile** und **Nachteile** im Vergleich zu gängigen **Web-APIs**. + + Wiegen Sie ab, ob die **Vorteile** für Ihren Anwendungsfall die **Nachteile** ausgleichen. 🤓 + +## GraphQL-Bibliotheken + +Hier sind einige der **GraphQL**-Bibliotheken, welche **ASGI** unterstützen. Diese könnten Sie mit **FastAPI** verwenden: + +* Strawberry 🍓 + * Mit Dokumentation für FastAPI +* Ariadne + * Mit Dokumentation für Starlette (welche auch für FastAPI gilt) +* Tartiflette + * Mit Tartiflette ASGI, für ASGI-Integration +* Graphene + * Mit starlette-graphene3 + +## GraphQL mit Strawberry + +Wenn Sie mit **GraphQL** arbeiten möchten oder müssen, ist **Strawberry** die **empfohlene** Bibliothek, da deren Design dem Design von **FastAPI** am nächsten kommt und alles auf **Typannotationen** basiert. + +Abhängig von Ihrem Anwendungsfall bevorzugen Sie vielleicht eine andere Bibliothek, aber wenn Sie mich fragen würden, würde ich Ihnen wahrscheinlich empfehlen, **Strawberry** auszuprobieren. + +Hier ist eine kleine Vorschau, wie Sie Strawberry mit FastAPI integrieren können: + +```Python hl_lines="3 22 25-26" +{!../../../docs_src/graphql/tutorial001.py!} +``` + +Weitere Informationen zu Strawberry finden Sie in der Strawberry-Dokumentation. + +Und auch die Dokumentation zu Strawberry mit FastAPI. + +## Ältere `GraphQLApp` von Starlette + +Frühere Versionen von Starlette enthielten eine `GraphQLApp`-Klasse zur Integration mit Graphene. + +Das wurde von Starlette deprecated, aber wenn Sie Code haben, der das verwendet, können Sie einfach zu starlette-graphene3 **migrieren**, welches denselben Anwendungsfall abdeckt und über eine **fast identische Schnittstelle** verfügt. + +!!! tip "Tipp" + Wenn Sie GraphQL benötigen, würde ich Ihnen trotzdem empfehlen, sich Strawberry anzuschauen, da es auf Typannotationen basiert, statt auf benutzerdefinierten Klassen und Typen. + +## Mehr darüber lernen + +Weitere Informationen zu **GraphQL** finden Sie in der offiziellen GraphQL-Dokumentation. + +Sie können auch mehr über jede der oben beschriebenen Bibliotheken in den jeweiligen Links lesen. diff --git a/docs/de/docs/how-to/index.md b/docs/de/docs/how-to/index.md new file mode 100644 index 0000000000000..101829ff86f36 --- /dev/null +++ b/docs/de/docs/how-to/index.md @@ -0,0 +1,10 @@ +# How-To – Rezepte + +Hier finden Sie verschiedene Rezepte und „How-To“-Anleitungen zu **verschiedenen Themen**. + +Die meisten dieser Ideen sind mehr oder weniger **unabhängig**, und in den meisten Fällen müssen Sie diese nur studieren, wenn sie direkt auf **Ihr Projekt** anwendbar sind. + +Wenn etwas für Ihr Projekt interessant und nützlich erscheint, lesen Sie es, andernfalls überspringen Sie es einfach. + +!!! tip "Tipp" + Wenn Sie strukturiert **FastAPI lernen** möchten (empfohlen), lesen Sie stattdessen Kapitel für Kapitel das [Tutorial – Benutzerhandbuch](../tutorial/index.md){.internal-link target=_blank}. diff --git a/docs/de/docs/how-to/separate-openapi-schemas.md b/docs/de/docs/how-to/separate-openapi-schemas.md new file mode 100644 index 0000000000000..000bcf6333626 --- /dev/null +++ b/docs/de/docs/how-to/separate-openapi-schemas.md @@ -0,0 +1,231 @@ +# Separate OpenAPI-Schemas für Eingabe und Ausgabe oder nicht + +Bei Verwendung von **Pydantic v2** ist die generierte OpenAPI etwas genauer und **korrekter** als zuvor. 😎 + +Tatsächlich gibt es in einigen Fällen sogar **zwei JSON-Schemas** in OpenAPI für dasselbe Pydantic-Modell für Eingabe und Ausgabe, je nachdem, ob sie **Defaultwerte** haben. + +Sehen wir uns an, wie das funktioniert und wie Sie es bei Bedarf ändern können. + +## Pydantic-Modelle für Eingabe und Ausgabe + +Nehmen wir an, Sie haben ein Pydantic-Modell mit Defaultwerten wie dieses: + +=== "Python 3.10+" + + ```Python hl_lines="7" + {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-7]!} + + # Code unterhalb weggelassen 👇 + ``` + +
+ 👀 Vollständige Dateivorschau + + ```Python + {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} + ``` + +
+ +=== "Python 3.9+" + + ```Python hl_lines="9" + {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-9]!} + + # Code unterhalb weggelassen 👇 + ``` + +
+ 👀 Vollständige Dateivorschau + + ```Python + {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} + ``` + +
+ +=== "Python 3.8+" + + ```Python hl_lines="9" + {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-9]!} + + # Code unterhalb weggelassen 👇 + ``` + +
+ 👀 Vollständige Dateivorschau + + ```Python + {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} + ``` + +
+ +### Modell für Eingabe + +Wenn Sie dieses Modell wie hier als Eingabe verwenden: + +=== "Python 3.10+" + + ```Python hl_lines="14" + {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-15]!} + + # Code unterhalb weggelassen 👇 + ``` + +
+ 👀 Vollständige Dateivorschau + + ```Python + {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} + ``` + +
+ +=== "Python 3.9+" + + ```Python hl_lines="16" + {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-17]!} + + # Code unterhalb weggelassen 👇 + ``` + +
+ 👀 Vollständige Dateivorschau + + ```Python + {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} + ``` + +
+ +=== "Python 3.8+" + + ```Python hl_lines="16" + {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-17]!} + + # Code unterhalb weggelassen 👇 + ``` + +
+ 👀 Vollständige Dateivorschau + + ```Python + {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} + ``` + +
+ +... dann ist das Feld `description` **nicht erforderlich**. Weil es den Defaultwert `None` hat. + +### Eingabemodell in der Dokumentation + +Sie können überprüfen, dass das Feld `description` in der Dokumentation kein **rotes Sternchen** enthält, es ist nicht als erforderlich markiert: + +
+ +
+ +### Modell für die Ausgabe + +Wenn Sie jedoch dasselbe Modell als Ausgabe verwenden, wie hier: + +=== "Python 3.10+" + + ```Python hl_lines="19" + {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="21" + {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="21" + {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} + ``` + +... dann, weil `description` einen Defaultwert hat, wird es, wenn Sie für dieses Feld **nichts zurückgeben**, immer noch diesen **Defaultwert** haben. + +### Modell für Ausgabe-Responsedaten + +Wenn Sie mit der Dokumentation interagieren und die Response überprüfen, enthält die JSON-Response den Defaultwert (`null`), obwohl der Code nichts in eines der `description`-Felder geschrieben hat: + +
+ +
+ +Das bedeutet, dass es **immer einen Wert** hat, der Wert kann jedoch manchmal `None` sein (oder `null` in JSON). + +Das bedeutet, dass Clients, die Ihre API verwenden, nicht prüfen müssen, ob der Wert vorhanden ist oder nicht. Sie können davon ausgehen, dass das Feld immer vorhanden ist. In einigen Fällen hat es jedoch nur den Defaultwert `None`. + +Um dies in OpenAPI zu kennzeichnen, markieren Sie dieses Feld als **erforderlich**, da es immer vorhanden sein wird. + +Aus diesem Grund kann das JSON-Schema für ein Modell unterschiedlich sein, je nachdem, ob es für **Eingabe oder Ausgabe** verwendet wird: + +* für die **Eingabe** ist `description` **nicht erforderlich** +* für die **Ausgabe** ist es **erforderlich** (und möglicherweise `None` oder, in JSON-Begriffen, `null`) + +### Ausgabemodell in der Dokumentation + +Sie können das Ausgabemodell auch in der Dokumentation überprüfen. **Sowohl** `name` **als auch** `description` sind mit einem **roten Sternchen** als **erforderlich** markiert: + +
+ +
+ +### Eingabe- und Ausgabemodell in der Dokumentation + +Und wenn Sie alle verfügbaren Schemas (JSON-Schemas) in OpenAPI überprüfen, werden Sie feststellen, dass es zwei gibt, ein `Item-Input` und ein `Item-Output`. + +Für `Item-Input` ist `description` **nicht erforderlich**, es hat kein rotes Sternchen. + +Aber für `Item-Output` ist `description` **erforderlich**, es hat ein rotes Sternchen. + +
+ +
+ +Mit dieser Funktion von **Pydantic v2** ist Ihre API-Dokumentation **präziser**, und wenn Sie über automatisch generierte Clients und SDKs verfügen, sind diese auch präziser, mit einer besseren **Entwicklererfahrung** und Konsistenz. 🎉 + +## Schemas nicht trennen + +Nun gibt es einige Fälle, in denen Sie möglicherweise **dasselbe Schema für Eingabe und Ausgabe** haben möchten. + +Der Hauptanwendungsfall hierfür besteht wahrscheinlich darin, dass Sie das mal tun möchten, wenn Sie bereits über einige automatisch generierte Client-Codes/SDKs verfügen und im Moment nicht alle automatisch generierten Client-Codes/SDKs aktualisieren möchten, möglicherweise später, aber nicht jetzt. + +In diesem Fall können Sie diese Funktion in **FastAPI** mit dem Parameter `separate_input_output_schemas=False` deaktivieren. + +!!! info + Unterstützung für `separate_input_output_schemas` wurde in FastAPI `0.102.0` hinzugefügt. 🤓 + +=== "Python 3.10+" + + ```Python hl_lines="10" + {!> ../../../docs_src/separate_openapi_schemas/tutorial002_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="12" + {!> ../../../docs_src/separate_openapi_schemas/tutorial002_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="12" + {!> ../../../docs_src/separate_openapi_schemas/tutorial002.py!} + ``` + +### Gleiches Schema für Eingabe- und Ausgabemodelle in der Dokumentation + +Und jetzt wird es ein einziges Schema für die Eingabe und Ausgabe des Modells geben, nur `Item`, und es wird `description` als **nicht erforderlich** kennzeichnen: + +
+ +
+ +Dies ist das gleiche Verhalten wie in Pydantic v1. 🤓 diff --git a/docs/de/docs/index.md b/docs/de/docs/index.md index f1c873d75f178..cf5a2b2d6954e 100644 --- a/docs/de/docs/index.md +++ b/docs/de/docs/index.md @@ -1,50 +1,58 @@ +--- +hide: + - navigation +--- -{!../../../docs/missing-translation.md!} - +

FastAPI

- FastAPI framework, high performance, easy to learn, fast to code, ready for production + FastAPI Framework, hochperformant, leicht zu erlernen, schnell zu programmieren, einsatzbereit

- - Test + + Test - - Coverage + + Coverage + + + Package-Version - Package version + Unterstützte Python-Versionen

--- -**Documentation**: https://fastapi.tiangolo.com +**Dokumentation**: https://fastapi.tiangolo.com -**Source Code**: https://github.com/tiangolo/fastapi +**Quellcode**: 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 ist ein modernes, schnelles (hoch performantes) Webframework zur Erstellung von APIs mit Python 3.8+ auf Basis von Standard-Python-Typhinweisen. -The key features are: +Seine Schlüssel-Merkmale sind: -* **Fast**: Very high performance, on par with **NodeJS** and **Go** (thanks to Starlette and Pydantic). [One of the fastest Python frameworks available](#performance). +* **Schnell**: Sehr hohe Leistung, auf Augenhöhe mit **NodeJS** und **Go** (Dank Starlette und Pydantic). [Eines der schnellsten verfügbaren Python-Frameworks](#performanz). -* **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. +* **Schnell zu programmieren**: Erhöhen Sie die Geschwindigkeit bei der Entwicklung von Funktionen um etwa 200 % bis 300 %. * +* **Weniger Bugs**: Verringern Sie die von Menschen (Entwicklern) verursachten Fehler um etwa 40 %. * +* **Intuitiv**: Exzellente Editor-Unterstützung. Code-Vervollständigung überall. Weniger Debuggen. +* **Einfach**: So konzipiert, dass es einfach zu benutzen und zu erlernen ist. Weniger Zeit für das Lesen der Dokumentation. +* **Kurz**: Minimieren Sie die Verdoppelung von Code. Mehrere Funktionen aus jeder Parameterdeklaration. Weniger Bugs. +* **Robust**: Erhalten Sie produktionsreifen Code. Mit automatischer, interaktiver Dokumentation. +* **Standards-basiert**: Basierend auf (und vollständig kompatibel mit) den offenen Standards für APIs: OpenAPI (früher bekannt als Swagger) und JSON Schema. -* estimation based on tests on an internal development team, building production applications. +* Schätzung auf Basis von Tests in einem internen Entwicklungsteam, das Produktionsanwendungen erstellt. -## Sponsors +## Sponsoren @@ -59,64 +67,70 @@ The key features are: -Other sponsors +Andere Sponsoren -## Opinions +## Meinungen -"_[...] 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._" +„_[...] Ich verwende **FastAPI** heutzutage sehr oft. [...] Ich habe tatsächlich vor, es für alle **ML-Dienste meines Teams bei Microsoft** zu verwenden. Einige davon werden in das Kernprodukt **Windows** und einige **Office**-Produkte integriert._“ -
Kabir Khan - Microsoft (ref)
+
Kabir Khan - Microsoft (Ref)
--- -"_We adopted the **FastAPI** library to spawn a **REST** server that can be queried to obtain **predictions**. [for Ludwig]_" +„_Wir haben die **FastAPI**-Bibliothek genommen, um einen **REST**-Server zu erstellen, der abgefragt werden kann, um **Vorhersagen** zu erhalten. [für Ludwig]_“ -
Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala - Uber (ref)
+
Piero Molino, Yaroslav Dudin, und 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** freut sich, die Open-Source-Veröffentlichung unseres **Krisenmanagement**-Orchestrierung-Frameworks bekannt zu geben: **Dispatch**! [erstellt mit **FastAPI**]_“ -
Kevin Glisson, Marc Vilanova, Forest Monsen - Netflix (ref)
+
Kevin Glisson, Marc Vilanova, Forest Monsen - Netflix (Ref)
--- -"_I’m over the moon excited about **FastAPI**. It’s so fun!_" +„_Ich bin überglücklich mit **FastAPI**. Es macht so viel Spaß!_“ -
Brian Okken - Python Bytes podcast host (ref)
+
Brian Okken - Host des Python Bytes Podcast (Ref)
--- -"_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._" +„_Ehrlich, was Du gebaut hast, sieht super solide und poliert aus. In vielerlei Hinsicht ist es so, wie ich **Hug** haben wollte – es ist wirklich inspirierend, jemanden so etwas bauen zu sehen._“ -
Timothy Crosley - Hug creator (ref)
+
Timothy Crosley - Autor von Hug (Ref)
--- -"_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 [...]_" +„_Wenn Sie ein **modernes Framework** zum Erstellen von REST-APIs erlernen möchten, schauen Sie sich **FastAPI** an. [...] Es ist schnell, einfach zu verwenden und leicht zu erlernen [...]_“ -"_We've switched over to **FastAPI** for our **APIs** [...] I think you'll like it [...]_" +„_Wir haben zu **FastAPI** für unsere **APIs** gewechselt [...] Ich denke, es wird Ihnen gefallen [...]_“ -
Ines Montani - Matthew Honnibal - Explosion AI founders - spaCy creators (ref) - (ref)
+
Ines Montani - Matthew Honnibal - Gründer von Explosion AI - Autoren von spaCy (Ref) - (Ref)
--- -## **Typer**, the FastAPI of CLIs +„_Falls irgendjemand eine Produktions-Python-API erstellen möchte, kann ich **FastAPI** wärmstens empfehlen. Es ist **wunderschön konzipiert**, **einfach zu verwenden** und **hoch skalierbar**; es ist zu einer **Schlüsselkomponente** in unserer API-First-Entwicklungsstrategie geworden und treibt viele Automatisierungen und Dienste an, wie etwa unseren virtuellen TAC-Ingenieur._“ + +
Deon Pillsbury - Cisco (Ref)
+ +--- + +## **Typer**, das FastAPI der CLIs -If you are building a CLI app to be used in the terminal instead of a web API, check out **Typer**. +Wenn Sie eine CLI-Anwendung für das Terminal erstellen, anstelle einer Web-API, schauen Sie sich **Typer** an. -**Typer** is FastAPI's little sibling. And it's intended to be the **FastAPI of CLIs**. ⌨️ 🚀 +**Typer** ist die kleine Schwester von FastAPI. Und es soll das **FastAPI der CLIs** sein. ⌨️ 🚀 -## Requirements +## Anforderungen -Python 3.7+ +Python 3.8+ -FastAPI stands on the shoulders of giants: +FastAPI steht auf den Schultern von Giganten: -* Starlette for the web parts. -* Pydantic for the data parts. +* Starlette für die Webanteile. +* Pydantic für die Datenanteile. ## Installation @@ -130,7 +144,7 @@ $ pip install fastapi -You will also need an ASGI server, for production such as Uvicorn or Hypercorn. +Sie benötigen außerdem einen ASGI-Server. Für die Produktumgebung beispielsweise Uvicorn oder Hypercorn.
@@ -142,11 +156,11 @@ $ pip install "uvicorn[standard]"
-## Example +## Beispiel -### Create it +### Erstellung -* Create a file `main.py` with: +* Erstellen Sie eine Datei `main.py` mit: ```Python from typing import Union @@ -167,9 +181,9 @@ def read_item(item_id: int, q: Union[str, None] = None): ```
-Or use async def... +Oder verwenden Sie async def ... -If your code uses `async` / `await`, use `async def`: +Wenn Ihr Code `async` / `await` verwendet, benutzen Sie `async def`: ```Python hl_lines="9 14" from typing import Union @@ -189,15 +203,14 @@ 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. +**Anmerkung**: +Wenn Sie das nicht kennen, schauen Sie sich den Abschnitt _„In Eile?“_ über `async` und `await` in der Dokumentation an.
-### Run it +### Starten -Run the server with: +Führen Sie den Server aus:
@@ -214,54 +227,54 @@ INFO: Application startup complete.
-About the command uvicorn main:app --reload... +Was macht der Befehl uvicorn main:app --reload ... -The command `uvicorn main:app` refers to: +Der Befehl `uvicorn main:app` bezieht sich auf: -* `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`: die Datei `main.py` (das Python-„Modul“). +* `app`: das Objekt, das innerhalb von `main.py` mit der Zeile `app = FastAPI()` erzeugt wurde. +* `--reload`: lässt den Server nach Codeänderungen neu starten. Tun Sie das nur während der Entwicklung.
-### Check it +### Testen -Open your browser at http://127.0.0.1:8000/items/5?q=somequery. +Öffnen Sie Ihren Browser unter http://127.0.0.1:8000/items/5?q=somequery. -You will see the JSON response as: +Sie erhalten die JSON-Response: ```JSON {"item_id": 5, "q": "somequery"} ``` -You already created an API that: +Damit haben Sie bereits eine API erstellt, welche: -* Receives HTTP requests in the _paths_ `/` and `/items/{item_id}`. -* Both _paths_ take `GET` operations (also known as HTTP _methods_). -* The _path_ `/items/{item_id}` has a _path parameter_ `item_id` that should be an `int`. -* The _path_ `/items/{item_id}` has an optional `str` _query parameter_ `q`. +* HTTP-Anfragen auf den _Pfaden_ `/` und `/items/{item_id}` entgegennimmt. +* Beide _Pfade_ erhalten `GET` Operationen (auch bekannt als HTTP _Methoden_). +* Der _Pfad_ `/items/{item_id}` hat einen _Pfadparameter_ `item_id`, der ein `int` sein sollte. +* Der _Pfad_ `/items/{item_id}` hat einen optionalen `str` _Query Parameter_ `q`. -### Interactive API docs +### Interaktive API-Dokumentation -Now go to http://127.0.0.1:8000/docs. +Gehen Sie nun auf http://127.0.0.1:8000/docs. -You will see the automatic interactive API documentation (provided by Swagger UI): +Sie sehen die automatische interaktive API-Dokumentation (bereitgestellt von Swagger UI): ![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) -### Alternative API docs +### Alternative API-Dokumentation -And now, go to http://127.0.0.1:8000/redoc. +Gehen Sie jetzt auf http://127.0.0.1:8000/redoc. -You will see the alternative automatic documentation (provided by ReDoc): +Sie sehen die alternative automatische Dokumentation (bereitgestellt von ReDoc): ![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) -## Example upgrade +## Beispiel Aktualisierung -Now modify the file `main.py` to receive a body from a `PUT` request. +Ändern Sie jetzt die Datei `main.py`, um den Body einer `PUT`-Anfrage zu empfangen. -Declare the body using standard Python types, thanks to Pydantic. +Deklarieren Sie den Body mithilfe von Standard-Python-Typen, dank Pydantic. ```Python hl_lines="4 9-12 25-27" from typing import Union @@ -293,171 +306,174 @@ 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). +Der Server sollte automatisch neu geladen werden (weil Sie oben `--reload` zum Befehl `uvicorn` hinzugefügt haben). -### Interactive API docs upgrade +### Aktualisierung der interaktiven API-Dokumentation -Now go to http://127.0.0.1:8000/docs. +Gehen Sie jetzt auf http://127.0.0.1:8000/docs. -* The interactive API documentation will be automatically updated, including the new body: +* Die interaktive API-Dokumentation wird automatisch aktualisiert, einschließlich des neuen Bodys: ![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) -* Click on the button "Try it out", it allows you to fill the parameters and directly interact with the API: +* Klicken Sie auf die Taste „Try it out“, damit können Sie die Parameter ausfüllen und direkt mit der API interagieren: -![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png) +![Swagger UI Interaktion](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png) -* Then click on the "Execute" button, the user interface will communicate with your API, send the parameters, get the results and show them on the screen: +* Klicken Sie dann auf die Taste „Execute“, die Benutzeroberfläche wird mit Ihrer API kommunizieren, sendet die Parameter, holt die Ergebnisse und zeigt sie auf dem Bildschirm an: -![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png) +![Swagger UI Interaktion](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png) -### Alternative API docs upgrade +### Aktualisierung der alternativen API-Dokumentation -And now, go to http://127.0.0.1:8000/redoc. +Und nun gehen Sie auf http://127.0.0.1:8000/redoc. -* The alternative documentation will also reflect the new query parameter and body: +* Die alternative Dokumentation wird ebenfalls den neuen Abfrageparameter und -inhalt widerspiegeln: ![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) -### Recap +### Zusammenfassung -In summary, you declare **once** the types of parameters, body, etc. as function parameters. +Zusammengefasst deklarieren Sie **einmal** die Typen von Parametern, Body, etc. als Funktionsparameter. -You do that with standard modern Python types. +Das machen Sie mit modernen Standard-Python-Typen. -You don't have to learn a new syntax, the methods or classes of a specific library, etc. +Sie müssen keine neue Syntax, Methoden oder Klassen einer bestimmten Bibliothek usw. lernen. -Just standard **Python 3.6+**. +Nur Standard-**Python 3.8+**. -For example, for an `int`: +Zum Beispiel für ein `int`: ```Python item_id: int ``` -or for a more complex `Item` model: +oder für ein komplexeres `Item`-Modell: ```Python item: Item ``` -...and with that single declaration you get: +... und mit dieser einen Deklaration erhalten Sie: -* 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: +* Editor-Unterstützung, einschließlich: + * Code-Vervollständigung. + * Typprüfungen. +* Validierung von Daten: + * Automatische und eindeutige Fehler, wenn die Daten ungültig sind. + * Validierung auch für tief verschachtelte JSON-Objekte. +* Konvertierung von Eingabedaten: Aus dem Netzwerk kommend, zu Python-Daten und -Typen. Lesen von: * JSON. - * Path parameters. - * Query parameters. + * Pfad-Parametern. + * Abfrage-Parametern. * 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: + * Header-Feldern. + * Formularen. + * Dateien. +* Konvertierung von Ausgabedaten: Konvertierung von Python-Daten und -Typen zu Netzwerkdaten (als JSON): + * Konvertieren von Python-Typen (`str`, `int`, `float`, `bool`, `list`, usw.). + * `Datetime`-Objekte. + * `UUID`-Objekte. + * Datenbankmodelle. + * ... und viele mehr. +* Automatische interaktive API-Dokumentation, einschließlich 2 alternativer Benutzeroberflächen: * 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. +Um auf das vorherige Codebeispiel zurückzukommen, **FastAPI** wird: + +* Überprüfen, dass es eine `item_id` im Pfad für `GET`- und `PUT`-Anfragen gibt. +* Überprüfen, ob die `item_id` vom Typ `int` für `GET`- und `PUT`-Anfragen ist. + * Falls nicht, wird dem Client ein nützlicher, eindeutiger Fehler angezeigt. +* Prüfen, ob es einen optionalen Abfrageparameter namens `q` (wie in `http://127.0.0.1:8000/items/foo?q=somequery`) für `GET`-Anfragen gibt. + * Da der `q`-Parameter mit `= None` deklariert ist, ist er optional. + * Ohne das `None` wäre er erforderlich (wie der Body im Fall von `PUT`). +* Bei `PUT`-Anfragen an `/items/{item_id}` den Body als JSON lesen: + * Prüfen, ob er ein erforderliches Attribut `name` hat, das ein `str` sein muss. + * Prüfen, ob er ein erforderliches Attribut `price` hat, das ein `float` sein muss. + * Prüfen, ob er ein optionales Attribut `is_offer` hat, das ein `bool` sein muss, falls vorhanden. + * All dies würde auch für tief verschachtelte JSON-Objekte funktionieren. +* Automatisch von und nach JSON konvertieren. +* Alles mit OpenAPI dokumentieren, welches verwendet werden kann von: + * Interaktiven Dokumentationssystemen. + * Automatisch Client-Code generierenden Systemen für viele Sprachen. +* Zwei interaktive Dokumentation-Webschnittstellen direkt zur Verfügung stellen. --- -We just scratched the surface, but you already get the idea of how it all works. +Wir haben nur an der Oberfläche gekratzt, aber Sie bekommen schon eine Vorstellung davon, wie das Ganze funktioniert. -Try changing the line with: +Versuchen Sie, diese Zeile zu ändern: ```Python return {"item_name": item.name, "item_id": item_id} ``` -...from: +... von: ```Python ... "item_name": item.name ... ``` -...to: +... zu: ```Python ... "item_price": item.price ... ``` -...and see how your editor will auto-complete the attributes and know their types: +... und sehen Sie, wie Ihr Editor die Attribute automatisch ausfüllt und ihre Typen kennt: -![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) +![Editor Unterstützung](https://fastapi.tiangolo.com/img/vscode-completion.png) -For a more complete example including more features, see the Tutorial - User Guide. +Für ein vollständigeres Beispiel, mit weiteren Funktionen, siehe das Tutorial - Benutzerhandbuch. -**Spoiler alert**: the tutorial - user guide includes: +**Spoiler-Alarm**: Das Tutorial - Benutzerhandbuch enthält: -* 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: +* Deklaration von **Parametern** von anderen verschiedenen Stellen wie: **Header-Felder**, **Cookies**, **Formularfelder** und **Dateien**. +* Wie man **Validierungseinschränkungen** wie `maximum_length` oder `regex` setzt. +* Ein sehr leistungsfähiges und einfach zu bedienendes System für **Dependency Injection**. +* Sicherheit und Authentifizierung, einschließlich Unterstützung für **OAuth2** mit **JWT-Tokens** und **HTTP-Basic**-Authentifizierung. +* Fortgeschrittenere (aber ebenso einfache) Techniken zur Deklaration **tief verschachtelter JSON-Modelle** (dank Pydantic). +* **GraphQL** Integration mit Strawberry und anderen Bibliotheken. +* Viele zusätzliche Funktionen (dank Starlette) wie: * **WebSockets** - * extremely easy tests based on `requests` and `pytest` + * extrem einfache Tests auf Basis von `httpx` und `pytest` * **CORS** * **Cookie Sessions** - * ...and more. + * ... und mehr. -## Performance +## Performanz -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). (*) +Unabhängige TechEmpower-Benchmarks zeigen **FastAPI**-Anwendungen, die unter Uvicorn laufen, als eines der schnellsten verfügbaren Python-Frameworks, nur noch hinter Starlette und Uvicorn selbst (intern von FastAPI verwendet). -To understand more about it, see the section Benchmarks. +Um mehr darüber zu erfahren, siehe den Abschnitt Benchmarks. -## Optional Dependencies +## Optionale Abhängigkeiten -Used by Pydantic: +Wird von Pydantic verwendet: -* email_validator - for email validation. +* email_validator - für E-Mail-Validierung. +* pydantic-settings - für die Verwaltung von Einstellungen. +* pydantic-extra-types - für zusätzliche Typen, mit Pydantic zu verwenden. -Used by Starlette: +Wird von Starlette verwendet: -* httpx - Required if you want to use the `TestClient`. -* jinja2 - Required if you want to use the default template configuration. -* python-multipart - Required if you want to support form "parsing", with `request.form()`. -* itsdangerous - Required for `SessionMiddleware` support. -* pyyaml - Required for Starlette's `SchemaGenerator` support (you probably don't need it with FastAPI). -* ujson - Required if you want to use `UJSONResponse`. +* httpx - erforderlich, wenn Sie den `TestClient` verwenden möchten. +* jinja2 - erforderlich, wenn Sie die Standardkonfiguration für Templates verwenden möchten. +* python-multipart - erforderlich, wenn Sie Formulare mittels `request.form()` „parsen“ möchten. +* itsdangerous - erforderlich für `SessionMiddleware` Unterstützung. +* pyyaml - erforderlich für Starlette's `SchemaGenerator` Unterstützung (Sie brauchen das wahrscheinlich nicht mit FastAPI). +* ujson - erforderlich, wenn Sie `UJSONResponse` verwenden möchten. -Used by FastAPI / Starlette: +Wird von FastAPI / Starlette verwendet: -* uvicorn - for the server that loads and serves your application. -* orjson - Required if you want to use `ORJSONResponse`. +* uvicorn - für den Server, der Ihre Anwendung lädt und serviert. +* orjson - erforderlich, wenn Sie `ORJSONResponse` verwenden möchten. -You can install all of these with `pip install fastapi[all]`. +Sie können diese alle mit `pip install "fastapi[all]"` installieren. -## License +## Lizenz -This project is licensed under the terms of the MIT license. +Dieses Projekt ist unter den Bedingungen der MIT-Lizenz lizenziert. diff --git a/docs/de/docs/learn/index.md b/docs/de/docs/learn/index.md new file mode 100644 index 0000000000000..b5582f55b6ae0 --- /dev/null +++ b/docs/de/docs/learn/index.md @@ -0,0 +1,5 @@ +# Lernen + +Hier finden Sie die einführenden Kapitel und Tutorials zum Erlernen von **FastAPI**. + +Sie könnten dies als **Buch**, als **Kurs**, als **offizielle** und empfohlene Methode zum Erlernen von FastAPI betrachten. 😎 diff --git a/docs/de/docs/newsletter.md b/docs/de/docs/newsletter.md new file mode 100644 index 0000000000000..31995b16487cd --- /dev/null +++ b/docs/de/docs/newsletter.md @@ -0,0 +1,5 @@ +# FastAPI und Freunde Newsletter + + + + diff --git a/docs/de/docs/project-generation.md b/docs/de/docs/project-generation.md new file mode 100644 index 0000000000000..c1ae6512de3f5 --- /dev/null +++ b/docs/de/docs/project-generation.md @@ -0,0 +1,84 @@ +# Projektgenerierung – Vorlage + +Sie können einen Projektgenerator für den Einstieg verwenden, welcher einen Großteil der Ersteinrichtung, Sicherheit, Datenbank und einige API-Endpunkte bereits für Sie erstellt. + +Ein Projektgenerator verfügt immer über ein sehr spezifisches Setup, das Sie aktualisieren und an Ihre eigenen Bedürfnisse anpassen sollten, aber es könnte ein guter Ausgangspunkt für Ihr Projekt sein. + +## Full Stack FastAPI PostgreSQL + +GitHub: https://github.com/tiangolo/full-stack-fastapi-postgresql + +### Full Stack FastAPI PostgreSQL – Funktionen + +* Vollständige **Docker**-Integration (Docker-basiert). +* Docker-Schwarmmodus-Deployment. +* **Docker Compose**-Integration und Optimierung für die lokale Entwicklung. +* **Produktionsbereit** Python-Webserver, verwendet Uvicorn und Gunicorn. +* Python **FastAPI**-Backend: + * **Schnell**: Sehr hohe Leistung, auf Augenhöhe mit **NodeJS** und **Go** (dank Starlette und Pydantic). + * **Intuitiv**: Hervorragende Editor-Unterstützung. Codevervollständigung überall. Weniger Zeitaufwand für das Debuggen. + * **Einfach**: Einfach zu bedienen und zu erlernen. Weniger Zeit für das Lesen von Dokumentationen. + * **Kurz**: Codeverdoppelung minimieren. Mehrere Funktionalitäten aus jeder Parameterdeklaration. + * **Robust**: Erhalten Sie produktionsbereiten Code. Mit automatischer, interaktiver Dokumentation. + * **Standards-basiert**: Basierend auf (und vollständig kompatibel mit) den offenen Standards für APIs: OpenAPI und JSON Schema. + * **Viele weitere Funktionen**, einschließlich automatischer Validierung, Serialisierung, interaktiver Dokumentation, Authentifizierung mit OAuth2-JWT-Tokens, usw. +* **Sicheres Passwort**-Hashing standardmäßig. +* **JWT-Token**-Authentifizierung. +* **SQLAlchemy**-Modelle (unabhängig von Flask-Erweiterungen, sodass sie direkt mit Celery-Workern verwendet werden können). +* Grundlegende Startmodelle für Benutzer (ändern und entfernen Sie nach Bedarf). +* **Alembic**-Migrationen. +* **CORS** (Cross Origin Resource Sharing). +* **Celery**-Worker, welche Modelle und Code aus dem Rest des Backends selektiv importieren und verwenden können. +* REST-Backend-Tests basierend auf **Pytest**, integriert in Docker, sodass Sie die vollständige API-Interaktion unabhängig von der Datenbank testen können. Da es in Docker ausgeführt wird, kann jedes Mal ein neuer Datenspeicher von Grund auf erstellt werden (Sie können also ElasticSearch, MongoDB, CouchDB oder was auch immer Sie möchten verwenden und einfach testen, ob die API funktioniert). +* Einfache Python-Integration mit **Jupyter-Kerneln** für Remote- oder In-Docker-Entwicklung mit Erweiterungen wie Atom Hydrogen oder Visual Studio Code Jupyter. +* **Vue**-Frontend: + * Mit Vue CLI generiert. + * Handhabung der **JWT-Authentifizierung**. + * Login-View. + * Nach der Anmeldung Hauptansicht des Dashboards. + * Haupt-Dashboard mit Benutzererstellung und -bearbeitung. + * Bearbeitung des eigenen Benutzers. + * **Vuex**. + * **Vue-Router**. + * **Vuetify** für schöne Material-Designkomponenten. + * **TypeScript**. + * Docker-Server basierend auf **Nginx** (konfiguriert, um gut mit Vue-Router zu funktionieren). + * Mehrstufigen Docker-Erstellung, sodass Sie kompilierten Code nicht speichern oder committen müssen. + * Frontend-Tests, welche zur Erstellungszeit ausgeführt werden (können auch deaktiviert werden). + * So modular wie möglich gestaltet, sodass es sofort einsatzbereit ist. Sie können es aber mit Vue CLI neu generieren oder es so wie Sie möchten erstellen und wiederverwenden, was Sie möchten. +* **PGAdmin** für die PostgreSQL-Datenbank, können Sie problemlos ändern, sodass PHPMyAdmin und MySQL verwendet wird. +* **Flower** für die Überwachung von Celery-Jobs. +* Load Balancing zwischen Frontend und Backend mit **Traefik**, sodass Sie beide unter derselben Domain haben können, getrennt durch den Pfad, aber von unterschiedlichen Containern ausgeliefert. +* Traefik-Integration, einschließlich automatischer Generierung von Let's Encrypt-**HTTPS**-Zertifikaten. +* GitLab **CI** (kontinuierliche Integration), einschließlich Frontend- und Backend-Testen. + +## Full Stack FastAPI Couchbase + +GitHub: https://github.com/tiangolo/full-stack-fastapi-couchbase + +⚠️ **WARNUNG** ⚠️ + +Wenn Sie ein neues Projekt von Grund auf starten, prüfen Sie die Alternativen hier. + +Zum Beispiel könnte der Projektgenerator Full Stack FastAPI PostgreSQL eine bessere Alternative sein, da er aktiv gepflegt und genutzt wird. Und er enthält alle neuen Funktionen und Verbesserungen. + +Es steht Ihnen weiterhin frei, den Couchbase-basierten Generator zu verwenden, wenn Sie möchten. Er sollte wahrscheinlich immer noch gut funktionieren, und wenn Sie bereits ein Projekt damit erstellt haben, ist das auch in Ordnung (und Sie haben es wahrscheinlich bereits an Ihre Bedürfnisse angepasst). + +Weitere Informationen hierzu finden Sie in der Dokumentation des Repos. + +## Full Stack FastAPI MongoDB + +... könnte später kommen, abhängig von meiner verfügbaren Zeit und anderen Faktoren. 😅 🎉 + +## Modelle für maschinelles Lernen mit spaCy und FastAPI + +GitHub: https://github.com/microsoft/cookiecutter-spacy-fastapi + +### Modelle für maschinelles Lernen mit spaCy und FastAPI – Funktionen + +* **spaCy** NER-Modellintegration. +* **Azure Cognitive Search**-Anforderungsformat integriert. +* **Produktionsbereit** Python-Webserver, verwendet Uvicorn und Gunicorn. +* **Azure DevOps** Kubernetes (AKS) CI/CD-Deployment integriert. +* **Mehrsprachig** Wählen Sie bei der Projekteinrichtung ganz einfach eine der integrierten Sprachen von spaCy aus. +* **Einfach erweiterbar** auf andere Modellframeworks (Pytorch, Tensorflow), nicht nur auf SpaCy. diff --git a/docs/de/docs/python-types.md b/docs/de/docs/python-types.md new file mode 100644 index 0000000000000..d11a193ddb2a9 --- /dev/null +++ b/docs/de/docs/python-types.md @@ -0,0 +1,537 @@ +# Einführung in Python-Typen + +Python hat Unterstützung für optionale „Typhinweise“ (Englisch: „Type Hints“). Auch „Typ Annotationen“ genannt. + +Diese **„Typhinweise“** oder -Annotationen sind eine spezielle Syntax, die es erlaubt, den Typ einer Variablen zu deklarieren. + +Durch das Deklarieren von Typen für Ihre Variablen können Editoren und Tools bessere Unterstützung bieten. + +Dies ist lediglich eine **schnelle Anleitung / Auffrischung** über Pythons Typhinweise. Sie deckt nur das Minimum ab, das nötig ist, um diese mit **FastAPI** zu verwenden ... was tatsächlich sehr wenig ist. + +**FastAPI** basiert vollständig auf diesen Typhinweisen, sie geben der Anwendung viele Vorteile und Möglichkeiten. + +Aber selbst wenn Sie **FastAPI** nie verwenden, wird es für Sie nützlich sein, ein wenig darüber zu lernen. + +!!! note "Hinweis" + Wenn Sie ein Python-Experte sind und bereits alles über Typhinweise wissen, überspringen Sie dieses Kapitel und fahren Sie mit dem nächsten fort. + +## Motivation + +Fangen wir mit einem einfachen Beispiel an: + +```Python +{!../../../docs_src/python_types/tutorial001.py!} +``` + +Dieses Programm gibt aus: + +``` +John Doe +``` + +Die Funktion macht Folgendes: + +* Nimmt einen `first_name` und `last_name`. +* Schreibt den ersten Buchstaben eines jeden Wortes groß, mithilfe von `title()`. +* Verkettet sie mit einem Leerzeichen in der Mitte. + +```Python hl_lines="2" +{!../../../docs_src/python_types/tutorial001.py!} +``` + +### Bearbeiten Sie es + +Es ist ein sehr einfaches Programm. + +Aber nun stellen Sie sich vor, Sie würden es selbst schreiben. + +Irgendwann sind die Funktions-Parameter fertig, Sie starten mit der Definition des Körpers ... + +Aber dann müssen Sie „diese Methode aufrufen, die den ersten Buchstaben in Großbuchstaben umwandelt“. + +War es `upper`? War es `uppercase`? `first_uppercase`? `capitalize`? + +Dann versuchen Sie es mit dem langjährigen Freund des Programmierers, der Editor-Autovervollständigung. + +Sie geben den ersten Parameter der Funktion ein, `first_name`, dann einen Punkt (`.`) und drücken `Strg+Leertaste`, um die Vervollständigung auszulösen. + +Aber leider erhalten Sie nichts Nützliches: + + + +### Typen hinzufügen + +Lassen Sie uns eine einzelne Zeile aus der vorherigen Version ändern. + +Wir ändern den folgenden Teil, die Parameter der Funktion, von: + +```Python + first_name, last_name +``` + +zu: + +```Python + first_name: str, last_name: str +``` + +Das war's. + +Das sind die „Typhinweise“: + +```Python hl_lines="1" +{!../../../docs_src/python_types/tutorial002.py!} +``` + +Das ist nicht das gleiche wie das Deklarieren von Defaultwerten, wie es hier der Fall ist: + +```Python + first_name="john", last_name="doe" +``` + +Das ist eine andere Sache. + +Wir verwenden Doppelpunkte (`:`), nicht Gleichheitszeichen (`=`). + +Und das Hinzufügen von Typhinweisen ändert normalerweise nichts an dem, was ohne sie passieren würde. + +Aber jetzt stellen Sie sich vor, Sie sind wieder mitten in der Erstellung dieser Funktion, aber mit Typhinweisen. + +An derselben Stelle versuchen Sie, die Autovervollständigung mit „Strg+Leertaste“ auszulösen, und Sie sehen: + + + +Hier können Sie durch die Optionen blättern, bis Sie diejenige finden, bei der es „Klick“ macht: + + + +## Mehr Motivation + +Sehen Sie sich diese Funktion an, sie hat bereits Typhinweise: + +```Python hl_lines="1" +{!../../../docs_src/python_types/tutorial003.py!} +``` + +Da der Editor die Typen der Variablen kennt, erhalten Sie nicht nur Code-Vervollständigung, sondern auch eine Fehlerprüfung: + + + +Jetzt, da Sie wissen, dass Sie das reparieren müssen, konvertieren Sie `age` mittels `str(age)` in einen String: + +```Python hl_lines="2" +{!../../../docs_src/python_types/tutorial004.py!} +``` + +## Deklarieren von Typen + +Sie haben gerade den Haupt-Einsatzort für die Deklaration von Typhinweisen gesehen. Als Funktionsparameter. + +Das ist auch meistens, wie sie in **FastAPI** verwendet werden. + +### Einfache Typen + +Sie können alle Standard-Python-Typen deklarieren, nicht nur `str`. + +Zum Beispiel diese: + +* `int` +* `float` +* `bool` +* `bytes` + +```Python hl_lines="1" +{!../../../docs_src/python_types/tutorial005.py!} +``` + +### Generische Typen mit Typ-Parametern + +Es gibt Datenstrukturen, die andere Werte enthalten können, wie etwa `dict`, `list`, `set` und `tuple`. Die inneren Werte können auch ihren eigenen Typ haben. + +Diese Typen mit inneren Typen werden „**generische**“ Typen genannt. Es ist möglich, sie mit ihren inneren Typen zu deklarieren. + +Um diese Typen und die inneren Typen zu deklarieren, können Sie Pythons Standardmodul `typing` verwenden. Es existiert speziell für die Unterstützung dieser Typhinweise. + +#### Neuere Python-Versionen + +Die Syntax, welche `typing` verwendet, ist **kompatibel** mit allen Versionen, von Python 3.6 aufwärts zu den neuesten, inklusive Python 3.9, Python 3.10, usw. + +Mit der Weiterentwicklung von Python kommen **neuere Versionen** heraus, mit verbesserter Unterstützung für Typannotationen, und in vielen Fällen müssen Sie gar nicht mehr das `typing`-Modul importieren, um Typannotationen zu schreiben. + +Wenn Sie eine neuere Python-Version für Ihr Projekt wählen können, werden Sie aus dieser zusätzlichen Vereinfachung Nutzen ziehen können. + +In der gesamten Dokumentation gibt es Beispiele, welche kompatibel mit unterschiedlichen Python-Versionen sind (wenn es Unterschiede gibt). + +Zum Beispiel bedeutet „**Python 3.6+**“, dass das Beispiel kompatibel mit Python 3.6 oder höher ist (inklusive 3.7, 3.8, 3.9, 3.10, usw.). Und „**Python 3.9+**“ bedeutet, es ist kompatibel mit Python 3.9 oder höher (inklusive 3.10, usw.). + +Wenn Sie über die **neueste Version von Python** verfügen, verwenden Sie die Beispiele für die neueste Version, diese werden die **beste und einfachste Syntax** haben, zum Beispiel, „**Python 3.10+**“. + +#### Liste + +Definieren wir zum Beispiel eine Variable, die eine `list` von `str` – eine Liste von Strings – sein soll. + +=== "Python 3.9+" + + Deklarieren Sie die Variable mit der gleichen Doppelpunkt-Syntax (`:`). + + Als Typ nehmen Sie `list`. + + Da die Liste ein Typ ist, welcher innere Typen enthält, werden diese von eckigen Klammern umfasst: + + ```Python hl_lines="1" + {!> ../../../docs_src/python_types/tutorial006_py39.py!} + ``` + +=== "Python 3.8+" + + Von `typing` importieren Sie `List` (mit Großbuchstaben `L`): + + ```Python hl_lines="1" + {!> ../../../docs_src/python_types/tutorial006.py!} + ``` + + Deklarieren Sie die Variable mit der gleichen Doppelpunkt-Syntax (`:`). + + Als Typ nehmen Sie das `List`, das Sie von `typing` importiert haben. + + Da die Liste ein Typ ist, welcher innere Typen enthält, werden diese von eckigen Klammern umfasst: + + ```Python hl_lines="4" + {!> ../../../docs_src/python_types/tutorial006.py!} + ``` + +!!! tip "Tipp" + Die inneren Typen in den eckigen Klammern werden als „Typ-Parameter“ bezeichnet. + + In diesem Fall ist `str` der Typ-Parameter, der an `List` übergeben wird (oder `list` in Python 3.9 und darüber). + +Das bedeutet: Die Variable `items` ist eine Liste – `list` – und jedes der Elemente in dieser Liste ist ein String – `str`. + +!!! tip "Tipp" + Wenn Sie Python 3.9 oder höher verwenden, müssen Sie `List` nicht von `typing` importieren, Sie können stattdessen den regulären `list`-Typ verwenden. + +Auf diese Weise kann Ihr Editor Sie auch bei der Bearbeitung von Einträgen aus der Liste unterstützen: + + + +Ohne Typen ist das fast unmöglich zu erreichen. + +Beachten Sie, dass die Variable `item` eines der Elemente in der Liste `items` ist. + +Und trotzdem weiß der Editor, dass es sich um ein `str` handelt, und bietet entsprechende Unterstützung. + +#### Tupel und Menge + +Das Gleiche gilt für die Deklaration eines Tupels – `tuple` – und einer Menge – `set`: + +=== "Python 3.9+" + + ```Python hl_lines="1" + {!> ../../../docs_src/python_types/tutorial007_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="1 4" + {!> ../../../docs_src/python_types/tutorial007.py!} + ``` + +Das bedeutet: + +* Die Variable `items_t` ist ein `tuple` mit 3 Elementen, einem `int`, einem weiteren `int` und einem `str`. +* Die Variable `items_s` ist ein `set`, und jedes seiner Elemente ist vom Typ `bytes`. + +#### Dict + +Um ein `dict` zu definieren, übergeben Sie zwei Typ-Parameter, getrennt durch Kommas. + +Der erste Typ-Parameter ist für die Schlüssel des `dict`. + +Der zweite Typ-Parameter ist für die Werte des `dict`: + +=== "Python 3.9+" + + ```Python hl_lines="1" + {!> ../../../docs_src/python_types/tutorial008_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="1 4" + {!> ../../../docs_src/python_types/tutorial008.py!} + ``` + +Das bedeutet: + +* Die Variable `prices` ist ein `dict`: + * Die Schlüssel dieses `dict` sind vom Typ `str` (z. B. die Namen der einzelnen Artikel). + * Die Werte dieses `dict` sind vom Typ `float` (z. B. der Preis jedes Artikels). + +#### Union + +Sie können deklarieren, dass eine Variable einer von **verschiedenen Typen** sein kann, zum Beispiel ein `int` oder ein `str`. + +In Python 3.6 und höher (inklusive Python 3.10) können Sie den `Union`-Typ von `typing` verwenden und die möglichen Typen innerhalb der eckigen Klammern auflisten. + +In Python 3.10 gibt es zusätzlich eine **neue Syntax**, die es erlaubt, die möglichen Typen getrennt von einem vertikalen Balken (`|`) aufzulisten. + +=== "Python 3.10+" + + ```Python hl_lines="1" + {!> ../../../docs_src/python_types/tutorial008b_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="1 4" + {!> ../../../docs_src/python_types/tutorial008b.py!} + ``` + +In beiden Fällen bedeutet das, dass `item` ein `int` oder ein `str` sein kann. + +#### Vielleicht `None` + +Sie können deklarieren, dass ein Wert ein `str`, aber vielleicht auch `None` sein kann. + +In Python 3.6 und darüber (inklusive Python 3.10) können Sie das deklarieren, indem Sie `Optional` vom `typing` Modul importieren und verwenden. + +```Python hl_lines="1 4" +{!../../../docs_src/python_types/tutorial009.py!} +``` + +Wenn Sie `Optional[str]` anstelle von nur `str` verwenden, wird Ihr Editor Ihnen dabei helfen, Fehler zu erkennen, bei denen Sie annehmen könnten, dass ein Wert immer eine String (`str`) ist, obwohl er auch `None` sein könnte. + +`Optional[Something]` ist tatsächlich eine Abkürzung für `Union[Something, None]`, diese beiden sind äquivalent. + +Das bedeutet auch, dass Sie in Python 3.10 `Something | None` verwenden können: + +=== "Python 3.10+" + + ```Python hl_lines="1" + {!> ../../../docs_src/python_types/tutorial009_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="1 4" + {!> ../../../docs_src/python_types/tutorial009.py!} + ``` + +=== "Python 3.8+ Alternative" + + ```Python hl_lines="1 4" + {!> ../../../docs_src/python_types/tutorial009b.py!} + ``` + +#### `Union` oder `Optional` verwenden? + +Wenn Sie eine Python-Version unterhalb 3.10 verwenden, hier ist mein sehr **subjektiver** Standpunkt dazu: + +* 🚨 Vermeiden Sie `Optional[SomeType]` +* Stattdessen ✨ **verwenden Sie `Union[SomeType, None]`** ✨. + +Beide sind äquivalent und im Hintergrund dasselbe, aber ich empfehle `Union` statt `Optional`, weil das Wort „**optional**“ impliziert, dass dieser Wert, zum Beispiel als Funktionsparameter, optional ist. Tatsächlich bedeutet es aber nur „Der Wert kann `None` sein“, selbst wenn der Wert nicht optional ist und benötigt wird. + +Ich denke, `Union[SomeType, None]` ist expliziter bezüglich seiner Bedeutung. + +Es geht nur um Wörter und Namen. Aber diese Worte können beeinflussen, wie Sie und Ihre Teamkollegen über den Code denken. + +Nehmen wir zum Beispiel diese Funktion: + +```Python hl_lines="1 4" +{!../../../docs_src/python_types/tutorial009c.py!} +``` + +Der Parameter `name` ist definiert als `Optional[str]`, aber er ist **nicht optional**, Sie können die Funktion nicht ohne diesen Parameter aufrufen: + +```Python +say_hi() # Oh, nein, das löst einen Fehler aus! 😱 +``` + +Der `name` Parameter wird **immer noch benötigt** (nicht *optional*), weil er keinen Default-Wert hat. `name` akzeptiert aber dennoch `None` als Wert: + +```Python +say_hi(name=None) # Das funktioniert, None is gültig 🎉 +``` + +Die gute Nachricht ist, dass Sie sich darüber keine Sorgen mehr machen müssen, wenn Sie Python 3.10 verwenden, da Sie einfach `|` verwenden können, um Vereinigungen von Typen zu definieren: + +```Python hl_lines="1 4" +{!../../../docs_src/python_types/tutorial009c_py310.py!} +``` + +Und dann müssen Sie sich nicht mehr um Namen wie `Optional` und `Union` kümmern. 😎 + +#### Generische Typen + +Diese Typen, die Typ-Parameter in eckigen Klammern akzeptieren, werden **generische Typen** oder **Generics** genannt. + +=== "Python 3.10+" + + Sie können die eingebauten Typen als Generics verwenden (mit eckigen Klammern und Typen darin): + + * `list` + * `tuple` + * `set` + * `dict` + + Verwenden Sie für den Rest, wie unter Python 3.8, das `typing`-Modul: + + * `Union` + * `Optional` (so wie unter Python 3.8) + * ... und andere. + + In Python 3.10 können Sie als Alternative zu den Generics `Union` und `Optional` den vertikalen Balken (`|`) verwenden, um Vereinigungen von Typen zu deklarieren, das ist besser und einfacher. + +=== "Python 3.9+" + + Sie können die eingebauten Typen als Generics verwenden (mit eckigen Klammern und Typen darin): + + * `list` + * `tuple` + * `set` + * `dict` + + Verwenden Sie für den Rest, wie unter Python 3.8, das `typing`-Modul: + + * `Union` + * `Optional` + * ... und andere. + +=== "Python 3.8+" + + * `List` + * `Tuple` + * `Set` + * `Dict` + * `Union` + * `Optional` + * ... und andere. + +### Klassen als Typen + +Sie können auch eine Klasse als Typ einer Variablen deklarieren. + +Nehmen wir an, Sie haben eine Klasse `Person`, mit einem Namen: + +```Python hl_lines="1-3" +{!../../../docs_src/python_types/tutorial010.py!} +``` + +Dann können Sie eine Variable vom Typ `Person` deklarieren: + +```Python hl_lines="6" +{!../../../docs_src/python_types/tutorial010.py!} +``` + +Und wiederum bekommen Sie die volle Editor-Unterstützung: + + + +Beachten Sie, das bedeutet: „`one_person` ist eine **Instanz** der Klasse `Person`“. + +Es bedeutet nicht: „`one_person` ist die **Klasse** genannt `Person`“. + +## Pydantic Modelle + +Pydantic ist eine Python-Bibliothek für die Validierung von Daten. + +Sie deklarieren die „Form“ der Daten als Klassen mit Attributen. + +Und jedes Attribut hat einen Typ. + +Dann erzeugen Sie eine Instanz dieser Klasse mit einigen Werten, und Pydantic validiert die Werte, konvertiert sie in den passenden Typ (falls notwendig) und gibt Ihnen ein Objekt mit allen Daten. + +Und Sie erhalten volle Editor-Unterstützung für dieses Objekt. + +Ein Beispiel aus der offiziellen Pydantic Dokumentation: + +=== "Python 3.10+" + + ```Python + {!> ../../../docs_src/python_types/tutorial011_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python + {!> ../../../docs_src/python_types/tutorial011_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python + {!> ../../../docs_src/python_types/tutorial011.py!} + ``` + +!!! info + Um mehr über Pydantic zu erfahren, schauen Sie sich dessen Dokumentation an. + +**FastAPI** basiert vollständig auf Pydantic. + +Viel mehr von all dem werden Sie in praktischer Anwendung im [Tutorial - Benutzerhandbuch](tutorial/index.md){.internal-link target=_blank} sehen. + +!!! tip "Tipp" + Pydantic verhält sich speziell, wenn Sie `Optional` oder `Union[Etwas, None]` ohne einen Default-Wert verwenden. Sie können darüber in der Pydantic Dokumentation unter Required fields mehr erfahren. + +## Typhinweise mit Metadaten-Annotationen + +Python bietet auch die Möglichkeit, **zusätzliche Metadaten** in Typhinweisen unterzubringen, mittels `Annotated`. + +=== "Python 3.9+" + + In Python 3.9 ist `Annotated` ein Teil der Standardbibliothek, Sie können es von `typing` importieren. + + ```Python hl_lines="1 4" + {!> ../../../docs_src/python_types/tutorial013_py39.py!} + ``` + +=== "Python 3.8+" + + In Versionen niedriger als Python 3.9 importieren Sie `Annotated` von `typing_extensions`. + + Es wird bereits mit **FastAPI** installiert sein. + + ```Python hl_lines="1 4" + {!> ../../../docs_src/python_types/tutorial013.py!} + ``` + +Python selbst macht nichts mit `Annotated`. Für Editoren und andere Tools ist der Typ immer noch `str`. + +Aber Sie können `Annotated` nutzen, um **FastAPI** mit Metadaten zu versorgen, die ihm sagen, wie sich ihre Anwendung verhalten soll. + +Wichtig ist, dass **der erste *Typ-Parameter***, den Sie `Annotated` übergeben, der **tatsächliche Typ** ist. Der Rest sind Metadaten für andere Tools. + +Im Moment müssen Sie nur wissen, dass `Annotated` existiert, und dass es Standard-Python ist. 😎 + +Später werden Sie sehen, wie **mächtig** es sein kann. + +!!! tip "Tipp" + Der Umstand, dass es **Standard-Python** ist, bedeutet, dass Sie immer noch die **bestmögliche Entwickler-Erfahrung** in ihrem Editor haben, sowie mit den Tools, die Sie nutzen, um ihren Code zu analysieren, zu refaktorisieren, usw. ✨ + + Und ebenfalls, dass Ihr Code sehr kompatibel mit vielen anderen Python-Tools und -Bibliotheken sein wird. 🚀 + +## Typhinweise in **FastAPI** + +**FastAPI** macht sich diese Typhinweise zunutze, um mehrere Dinge zu tun. + +Mit **FastAPI** deklarieren Sie Parameter mit Typhinweisen, und Sie erhalten: + +* **Editorunterstützung**. +* **Typ-Prüfungen**. + +... und **FastAPI** verwendet dieselben Deklarationen, um: + +* **Anforderungen** zu definieren: aus Anfrage-Pfadparametern, Abfrageparametern, Header-Feldern, Bodys, Abhängigkeiten, usw. +* **Daten umzuwandeln**: aus der Anfrage in den erforderlichen Typ. +* **Daten zu validieren**: aus jeder Anfrage: + * **Automatische Fehler** generieren, die an den Client zurückgegeben werden, wenn die Daten ungültig sind. +* Die API mit OpenAPI zu **dokumentieren**: + * Die dann von den Benutzeroberflächen der automatisch generierten interaktiven Dokumentation verwendet wird. + +Das mag alles abstrakt klingen. Machen Sie sich keine Sorgen. Sie werden all das in Aktion sehen im [Tutorial - Benutzerhandbuch](tutorial/index.md){.internal-link target=_blank}. + +Das Wichtigste ist, dass **FastAPI** durch die Verwendung von Standard-Python-Typen an einer einzigen Stelle (anstatt weitere Klassen, Dekoratoren usw. hinzuzufügen) einen Großteil der Arbeit für Sie erledigt. + +!!! info + Wenn Sie bereits das ganze Tutorial durchgearbeitet haben und mehr über Typen erfahren wollen, dann ist eine gute Ressource der „Cheat Sheet“ von `mypy`. diff --git a/docs/de/docs/reference/apirouter.md b/docs/de/docs/reference/apirouter.md new file mode 100644 index 0000000000000..b0728b7df9bf9 --- /dev/null +++ b/docs/de/docs/reference/apirouter.md @@ -0,0 +1,24 @@ +# `APIRouter`-Klasse + +Hier sind die Referenzinformationen für die Klasse `APIRouter` mit all ihren Parametern, Attributen und Methoden. + +Sie können die `APIRouter`-Klasse direkt von `fastapi` importieren: + +```python +from fastapi import APIRouter +``` + +::: fastapi.APIRouter + options: + members: + - websocket + - include_router + - get + - put + - post + - delete + - options + - head + - patch + - trace + - on_event diff --git a/docs/de/docs/reference/background.md b/docs/de/docs/reference/background.md new file mode 100644 index 0000000000000..0fd389325d49b --- /dev/null +++ b/docs/de/docs/reference/background.md @@ -0,0 +1,11 @@ +# Hintergrundtasks – `BackgroundTasks` + +Sie können einen Parameter in einer *Pfadoperation-Funktion* oder einer Abhängigkeitsfunktion mit dem Typ `BackgroundTasks` deklarieren und diesen danach verwenden, um die Ausführung von Hintergrundtasks nach dem Senden der Response zu definieren. + +Sie können `BackgroundTasks` direkt von `fastapi` importieren: + +```python +from fastapi import BackgroundTasks +``` + +::: fastapi.BackgroundTasks diff --git a/docs/de/docs/reference/dependencies.md b/docs/de/docs/reference/dependencies.md new file mode 100644 index 0000000000000..2ed5b5050146b --- /dev/null +++ b/docs/de/docs/reference/dependencies.md @@ -0,0 +1,29 @@ +# Abhängigkeiten – `Depends()` und `Security()` + +## `Depends()` + +Abhängigkeiten werden hauptsächlich mit der speziellen Funktion `Depends()` behandelt, die ein Callable entgegennimmt. + +Hier finden Sie deren Referenz und Parameter. + +Sie können sie direkt von `fastapi` importieren: + +```python +from fastapi import Depends +``` + +::: fastapi.Depends + +## `Security()` + +In vielen Szenarien können Sie die Sicherheit (Autorisierung, Authentifizierung usw.) mit Abhängigkeiten handhaben, indem Sie `Depends()` verwenden. + +Wenn Sie jedoch auch OAuth2-Scopes deklarieren möchten, können Sie `Security()` anstelle von `Depends()` verwenden. + +Sie können `Security()` direkt von `fastapi` importieren: + +```python +from fastapi import Security +``` + +::: fastapi.Security diff --git a/docs/de/docs/reference/encoders.md b/docs/de/docs/reference/encoders.md new file mode 100644 index 0000000000000..2489b8c603c4f --- /dev/null +++ b/docs/de/docs/reference/encoders.md @@ -0,0 +1,3 @@ +# Encoder – `jsonable_encoder` + +::: fastapi.encoders.jsonable_encoder diff --git a/docs/de/docs/reference/exceptions.md b/docs/de/docs/reference/exceptions.md new file mode 100644 index 0000000000000..230f902a9eb50 --- /dev/null +++ b/docs/de/docs/reference/exceptions.md @@ -0,0 +1,20 @@ +# Exceptions – `HTTPException` und `WebSocketException` + +Dies sind die Exceptions, die Sie auslösen können, um dem Client Fehler zu berichten. + +Wenn Sie eine Exception auslösen, wird, wie es bei normalem Python der Fall wäre, der Rest der Ausführung abgebrochen. Auf diese Weise können Sie diese Exceptions von überall im Code werfen, um einen Request abzubrechen und den Fehler dem Client anzuzeigen. + +Sie können Folgendes verwenden: + +* `HTTPException` +* `WebSocketException` + +Diese Exceptions können direkt von `fastapi` importiert werden: + +```python +from fastapi import HTTPException, WebSocketException +``` + +::: fastapi.HTTPException + +::: fastapi.WebSocketException diff --git a/docs/de/docs/reference/fastapi.md b/docs/de/docs/reference/fastapi.md new file mode 100644 index 0000000000000..4e6a5697100e2 --- /dev/null +++ b/docs/de/docs/reference/fastapi.md @@ -0,0 +1,31 @@ +# `FastAPI`-Klasse + +Hier sind die Referenzinformationen für die Klasse `FastAPI` mit all ihren Parametern, Attributen und Methoden. + +Sie können die `FastAPI`-Klasse direkt von `fastapi` importieren: + +```python +from fastapi import FastAPI +``` + +::: fastapi.FastAPI + options: + members: + - openapi_version + - webhooks + - state + - dependency_overrides + - openapi + - websocket + - include_router + - get + - put + - post + - delete + - options + - head + - patch + - trace + - on_event + - middleware + - exception_handler diff --git a/docs/de/docs/reference/httpconnection.md b/docs/de/docs/reference/httpconnection.md new file mode 100644 index 0000000000000..32a9696fa5f41 --- /dev/null +++ b/docs/de/docs/reference/httpconnection.md @@ -0,0 +1,11 @@ +# `HTTPConnection`-Klasse + +Wenn Sie Abhängigkeiten definieren möchten, die sowohl mit HTTP als auch mit WebSockets kompatibel sein sollen, können Sie einen Parameter definieren, der eine `HTTPConnection` anstelle eines `Request` oder eines `WebSocket` akzeptiert. + +Sie können diese von `fastapi.requests` importieren: + +```python +from fastapi.requests import HTTPConnection +``` + +::: fastapi.requests.HTTPConnection diff --git a/docs/de/docs/reference/index.md b/docs/de/docs/reference/index.md new file mode 100644 index 0000000000000..e9362b962a7e5 --- /dev/null +++ b/docs/de/docs/reference/index.md @@ -0,0 +1,8 @@ +# Referenz – Code-API + +Hier ist die Referenz oder Code-API, die Klassen, Funktionen, Parameter, Attribute und alle FastAPI-Teile, die Sie in Ihren Anwendungen verwenden können. + +Wenn Sie **FastAPI** lernen möchten, ist es viel besser, das [FastAPI-Tutorial](https://fastapi.tiangolo.com/tutorial/) zu lesen. + +!!! note "Hinweis Deutsche Übersetzung" + Die nachfolgende API wird aus der Quelltext-Dokumentation erstellt, daher sind nur die Einleitungen auf Deutsch. diff --git a/docs/de/docs/reference/middleware.md b/docs/de/docs/reference/middleware.md new file mode 100644 index 0000000000000..d8d2d50fc911e --- /dev/null +++ b/docs/de/docs/reference/middleware.md @@ -0,0 +1,45 @@ +# Middleware + +Es gibt mehrere Middlewares, die direkt von Starlette bereitgestellt werden. + +Lesen Sie mehr darüber in der [FastAPI-Dokumentation über Middleware](../advanced/middleware.md). + +::: fastapi.middleware.cors.CORSMiddleware + +Kann von `fastapi` importiert werden: + +```python +from fastapi.middleware.cors import CORSMiddleware +``` + +::: fastapi.middleware.gzip.GZipMiddleware + +Kann von `fastapi` importiert werden: + +```python +from fastapi.middleware.gzip import GZipMiddleware +``` + +::: fastapi.middleware.httpsredirect.HTTPSRedirectMiddleware + +Kann von `fastapi` importiert werden: + +```python +from fastapi.middleware.httpsredirect import HTTPSRedirectMiddleware +``` + +::: fastapi.middleware.trustedhost.TrustedHostMiddleware + +Kann von `fastapi` importiert werden: + +```python +from fastapi.middleware.trustedhost import TrustedHostMiddleware +``` + +::: fastapi.middleware.wsgi.WSGIMiddleware + +Kann von `fastapi` importiert werden: + +```python +from fastapi.middleware.wsgi import WSGIMiddleware +``` diff --git a/docs/de/docs/reference/openapi/docs.md b/docs/de/docs/reference/openapi/docs.md new file mode 100644 index 0000000000000..3c19ba91734ce --- /dev/null +++ b/docs/de/docs/reference/openapi/docs.md @@ -0,0 +1,11 @@ +# OpenAPI `docs` + +Werkzeuge zur Verwaltung der automatischen OpenAPI-UI-Dokumentation, einschließlich Swagger UI (standardmäßig unter `/docs`) und ReDoc (standardmäßig unter `/redoc`). + +::: fastapi.openapi.docs.get_swagger_ui_html + +::: fastapi.openapi.docs.get_redoc_html + +::: fastapi.openapi.docs.get_swagger_ui_oauth2_redirect_html + +::: fastapi.openapi.docs.swagger_ui_default_parameters diff --git a/docs/de/docs/reference/openapi/index.md b/docs/de/docs/reference/openapi/index.md new file mode 100644 index 0000000000000..0ae3d67c699c1 --- /dev/null +++ b/docs/de/docs/reference/openapi/index.md @@ -0,0 +1,5 @@ +# OpenAPI + +Es gibt mehrere Werkzeuge zur Handhabung von OpenAPI. + +Normalerweise müssen Sie diese nicht verwenden, es sei denn, Sie haben einen bestimmten fortgeschrittenen Anwendungsfall, welcher das erfordert. diff --git a/docs/de/docs/reference/openapi/models.md b/docs/de/docs/reference/openapi/models.md new file mode 100644 index 0000000000000..64306b15fd1b3 --- /dev/null +++ b/docs/de/docs/reference/openapi/models.md @@ -0,0 +1,5 @@ +# OpenAPI-`models` + +OpenAPI Pydantic-Modelle, werden zum Generieren und Validieren der generierten OpenAPI verwendet. + +::: fastapi.openapi.models diff --git a/docs/de/docs/reference/parameters.md b/docs/de/docs/reference/parameters.md new file mode 100644 index 0000000000000..2638eaf481257 --- /dev/null +++ b/docs/de/docs/reference/parameters.md @@ -0,0 +1,35 @@ +# Request-Parameter + +Hier die Referenzinformationen für die Request-Parameter. + +Dies sind die Sonderfunktionen, die Sie mittels `Annotated` in *Pfadoperation-Funktion*-Parameter oder Abhängigkeitsfunktionen einfügen können, um Daten aus dem Request abzurufen. + +Dies beinhaltet: + +* `Query()` +* `Path()` +* `Body()` +* `Cookie()` +* `Header()` +* `Form()` +* `File()` + +Sie können diese alle direkt von `fastapi` importieren: + +```python +from fastapi import Body, Cookie, File, Form, Header, Path, Query +``` + +::: fastapi.Query + +::: fastapi.Path + +::: fastapi.Body + +::: fastapi.Cookie + +::: fastapi.Header + +::: fastapi.Form + +::: fastapi.File diff --git a/docs/de/docs/reference/request.md b/docs/de/docs/reference/request.md new file mode 100644 index 0000000000000..b170c1e408270 --- /dev/null +++ b/docs/de/docs/reference/request.md @@ -0,0 +1,14 @@ +# `Request`-Klasse + +Sie können einen Parameter in einer *Pfadoperation-Funktion* oder einer Abhängigkeit als vom Typ `Request` deklarieren und dann direkt auf das Requestobjekt zugreifen, ohne jegliche Validierung, usw. + +Sie können es direkt von `fastapi` importieren: + +```python +from fastapi import Request +``` + +!!! tip "Tipp" + Wenn Sie Abhängigkeiten definieren möchten, die sowohl mit HTTP als auch mit WebSockets kompatibel sein sollen, können Sie einen Parameter definieren, der eine `HTTPConnection` anstelle eines `Request` oder eines `WebSocket` akzeptiert. + +::: fastapi.Request diff --git a/docs/de/docs/reference/response.md b/docs/de/docs/reference/response.md new file mode 100644 index 0000000000000..2159189311711 --- /dev/null +++ b/docs/de/docs/reference/response.md @@ -0,0 +1,13 @@ +# `Response`-Klasse + +Sie können einen Parameter in einer *Pfadoperation-Funktion* oder einer Abhängigkeit als `Response` deklarieren und dann Daten für die Response wie Header oder Cookies festlegen. + +Diese können Sie auch direkt verwenden, um eine Instanz davon zu erstellen und diese von Ihren *Pfadoperationen* zurückzugeben. + +Sie können sie direkt von `fastapi` importieren: + +```python +from fastapi import Response +``` + +::: fastapi.Response diff --git a/docs/de/docs/reference/responses.md b/docs/de/docs/reference/responses.md new file mode 100644 index 0000000000000..c0e9f07e75d7e --- /dev/null +++ b/docs/de/docs/reference/responses.md @@ -0,0 +1,164 @@ +# Benutzerdefinierte Responseklassen – File, HTML, Redirect, Streaming, usw. + +Es gibt mehrere benutzerdefinierte Responseklassen, von denen Sie eine Instanz erstellen und diese direkt von Ihren *Pfadoperationen* zurückgeben können. + +Lesen Sie mehr darüber in der [FastAPI-Dokumentation zu benutzerdefinierten Responses – HTML, Stream, Datei, andere](../advanced/custom-response.md). + +Sie können diese direkt von `fastapi.responses` importieren: + +```python +from fastapi.responses import ( + FileResponse, + HTMLResponse, + JSONResponse, + ORJSONResponse, + PlainTextResponse, + RedirectResponse, + Response, + StreamingResponse, + UJSONResponse, +) +``` + +## FastAPI-Responses + +Es gibt einige benutzerdefinierte FastAPI-Responseklassen, welche Sie verwenden können, um die JSON-Performanz zu optimieren. + +::: fastapi.responses.UJSONResponse + options: + members: + - charset + - status_code + - media_type + - body + - background + - raw_headers + - render + - init_headers + - headers + - set_cookie + - delete_cookie + +::: fastapi.responses.ORJSONResponse + options: + members: + - charset + - status_code + - media_type + - body + - background + - raw_headers + - render + - init_headers + - headers + - set_cookie + - delete_cookie + +## Starlette-Responses + +::: fastapi.responses.FileResponse + options: + members: + - chunk_size + - charset + - status_code + - media_type + - body + - background + - raw_headers + - render + - init_headers + - headers + - set_cookie + - delete_cookie + +::: fastapi.responses.HTMLResponse + options: + members: + - charset + - status_code + - media_type + - body + - background + - raw_headers + - render + - init_headers + - headers + - set_cookie + - delete_cookie + +::: fastapi.responses.JSONResponse + options: + members: + - charset + - status_code + - media_type + - body + - background + - raw_headers + - render + - init_headers + - headers + - set_cookie + - delete_cookie + +::: fastapi.responses.PlainTextResponse + options: + members: + - charset + - status_code + - media_type + - body + - background + - raw_headers + - render + - init_headers + - headers + - set_cookie + - delete_cookie + +::: fastapi.responses.RedirectResponse + options: + members: + - charset + - status_code + - media_type + - body + - background + - raw_headers + - render + - init_headers + - headers + - set_cookie + - delete_cookie + +::: fastapi.responses.Response + options: + members: + - charset + - status_code + - media_type + - body + - background + - raw_headers + - render + - init_headers + - headers + - set_cookie + - delete_cookie + +::: fastapi.responses.StreamingResponse + options: + members: + - body_iterator + - charset + - status_code + - media_type + - body + - background + - raw_headers + - render + - init_headers + - headers + - set_cookie + - delete_cookie diff --git a/docs/de/docs/reference/security/index.md b/docs/de/docs/reference/security/index.md new file mode 100644 index 0000000000000..4c2375f2ff667 --- /dev/null +++ b/docs/de/docs/reference/security/index.md @@ -0,0 +1,73 @@ +# Sicherheitstools + +Wenn Sie Abhängigkeiten mit OAuth2-Scopes deklarieren müssen, verwenden Sie `Security()`. + +Aber Sie müssen immer noch definieren, was das Dependable, das Callable ist, welches Sie als Parameter an `Depends()` oder `Security()` übergeben. + +Es gibt mehrere Tools, mit denen Sie diese Dependables erstellen können, und sie werden in OpenAPI integriert, sodass sie in der Oberfläche der automatischen Dokumentation angezeigt werden und von automatisch generierten Clients und SDKs, usw., verwendet werden können. + +Sie können sie von `fastapi.security` importieren: + +```python +from fastapi.security import ( + APIKeyCookie, + APIKeyHeader, + APIKeyQuery, + HTTPAuthorizationCredentials, + HTTPBasic, + HTTPBasicCredentials, + HTTPBearer, + HTTPDigest, + OAuth2, + OAuth2AuthorizationCodeBearer, + OAuth2PasswordBearer, + OAuth2PasswordRequestForm, + OAuth2PasswordRequestFormStrict, + OpenIdConnect, + SecurityScopes, +) +``` + +## API-Schlüssel-Sicherheitsschemas + +::: fastapi.security.APIKeyCookie + +::: fastapi.security.APIKeyHeader + +::: fastapi.security.APIKeyQuery + +## HTTP-Authentifizierungsschemas + +::: fastapi.security.HTTPBasic + +::: fastapi.security.HTTPBearer + +::: fastapi.security.HTTPDigest + +## HTTP-Anmeldeinformationen + +::: fastapi.security.HTTPAuthorizationCredentials + +::: fastapi.security.HTTPBasicCredentials + +## OAuth2-Authentifizierung + +::: fastapi.security.OAuth2 + +::: fastapi.security.OAuth2AuthorizationCodeBearer + +::: fastapi.security.OAuth2PasswordBearer + +## OAuth2-Passwortformulare + +::: fastapi.security.OAuth2PasswordRequestForm + +::: fastapi.security.OAuth2PasswordRequestFormStrict + +## OAuth2-Sicherheitsscopes in Abhängigkeiten + +::: fastapi.security.SecurityScopes + +## OpenID Connect + +::: fastapi.security.OpenIdConnect diff --git a/docs/de/docs/reference/staticfiles.md b/docs/de/docs/reference/staticfiles.md new file mode 100644 index 0000000000000..5629854c6521b --- /dev/null +++ b/docs/de/docs/reference/staticfiles.md @@ -0,0 +1,13 @@ +# Statische Dateien – `StaticFiles` + +Sie können die `StaticFiles`-Klasse verwenden, um statische Dateien wie JavaScript, CSS, Bilder, usw. bereitzustellen. + +Lesen Sie mehr darüber in der [FastAPI-Dokumentation zu statischen Dateien](../tutorial/static-files.md). + +Sie können sie direkt von `fastapi.staticfiles` importieren: + +```python +from fastapi.staticfiles import StaticFiles +``` + +::: fastapi.staticfiles.StaticFiles diff --git a/docs/de/docs/reference/status.md b/docs/de/docs/reference/status.md new file mode 100644 index 0000000000000..1d9458ee91424 --- /dev/null +++ b/docs/de/docs/reference/status.md @@ -0,0 +1,36 @@ +# Statuscodes + +Sie können das Modul `status` von `fastapi` importieren: + +```python +from fastapi import status +``` + +`status` wird direkt von Starlette bereitgestellt. + +Es enthält eine Gruppe benannter Konstanten (Variablen) mit ganzzahligen Statuscodes. + +Zum Beispiel: + +* 200: `status.HTTP_200_OK` +* 403: `status.HTTP_403_FORBIDDEN` +* usw. + +Es kann praktisch sein, schnell auf HTTP- (und WebSocket-)Statuscodes in Ihrer Anwendung zuzugreifen, indem Sie die automatische Vervollständigung für den Namen verwenden, ohne sich die Zahlen für die Statuscodes merken zu müssen. + +Lesen Sie mehr darüber in der [FastAPI-Dokumentation zu Response-Statuscodes](../tutorial/response-status-code.md). + +## Beispiel + +```python +from fastapi import FastAPI, status + +app = FastAPI() + + +@app.get("/items/", status_code=status.HTTP_418_IM_A_TEAPOT) +def read_items(): + return [{"name": "Plumbus"}, {"name": "Portal Gun"}] +``` + +::: fastapi.status diff --git a/docs/de/docs/reference/templating.md b/docs/de/docs/reference/templating.md new file mode 100644 index 0000000000000..c367a0179ff7d --- /dev/null +++ b/docs/de/docs/reference/templating.md @@ -0,0 +1,13 @@ +# Templating – `Jinja2Templates` + +Sie können die `Jinja2Templates`-Klasse verwenden, um Jinja-Templates zu rendern. + +Lesen Sie mehr darüber in der [FastAPI-Dokumentation zu Templates](../advanced/templates.md). + +Sie können die Klasse direkt von `fastapi.templating` importieren: + +```python +from fastapi.templating import Jinja2Templates +``` + +::: fastapi.templating.Jinja2Templates diff --git a/docs/de/docs/reference/testclient.md b/docs/de/docs/reference/testclient.md new file mode 100644 index 0000000000000..5bc089c0561ca --- /dev/null +++ b/docs/de/docs/reference/testclient.md @@ -0,0 +1,13 @@ +# Testclient – `TestClient` + +Sie können die `TestClient`-Klasse verwenden, um FastAPI-Anwendungen zu testen, ohne eine tatsächliche HTTP- und Socket-Verbindung zu erstellen, Sie kommunizieren einfach direkt mit dem FastAPI-Code. + +Lesen Sie mehr darüber in der [FastAPI-Dokumentation über Testen](../tutorial/testing.md). + +Sie können sie direkt von `fastapi.testclient` importieren: + +```python +from fastapi.testclient import TestClient +``` + +::: fastapi.testclient.TestClient diff --git a/docs/de/docs/reference/uploadfile.md b/docs/de/docs/reference/uploadfile.md new file mode 100644 index 0000000000000..8556edf828782 --- /dev/null +++ b/docs/de/docs/reference/uploadfile.md @@ -0,0 +1,22 @@ +# `UploadFile`-Klasse + +Sie können *Pfadoperation-Funktionsparameter* als Parameter vom Typ `UploadFile` definieren, um Dateien aus dem Request zu erhalten. + +Sie können es direkt von `fastapi` importieren: + +```python +from fastapi import UploadFile +``` + +::: fastapi.UploadFile + options: + members: + - file + - filename + - size + - headers + - content_type + - read + - write + - seek + - close diff --git a/docs/de/docs/reference/websockets.md b/docs/de/docs/reference/websockets.md new file mode 100644 index 0000000000000..35657172ceef2 --- /dev/null +++ b/docs/de/docs/reference/websockets.md @@ -0,0 +1,64 @@ +# WebSockets + +Bei der Definition von WebSockets deklarieren Sie normalerweise einen Parameter vom Typ `WebSocket` und können damit Daten vom Client lesen und an ihn senden. Er wird direkt von Starlette bereitgestellt, Sie können ihn aber von `fastapi` importieren: + +```python +from fastapi import WebSocket +``` + +!!! tip "Tipp" + Wenn Sie Abhängigkeiten definieren möchten, die sowohl mit HTTP als auch mit WebSockets kompatibel sein sollen, können Sie einen Parameter definieren, der eine `HTTPConnection` anstelle eines `Request` oder eines `WebSocket` akzeptiert. + +::: fastapi.WebSocket + options: + members: + - scope + - app + - url + - base_url + - headers + - query_params + - path_params + - cookies + - client + - state + - url_for + - client_state + - application_state + - receive + - send + - accept + - receive_text + - receive_bytes + - receive_json + - iter_text + - iter_bytes + - iter_json + - send_text + - send_bytes + - send_json + - close + +Wenn ein Client die Verbindung trennt, wird eine `WebSocketDisconnect`-Exception ausgelöst, die Sie abfangen können. + +Sie können diese direkt von `fastapi` importieren: + +```python +from fastapi import WebSocketDisconnect +``` + +::: fastapi.WebSocketDisconnect + +## WebSockets – zusätzliche Klassen + +Zusätzliche Klassen für die Handhabung von WebSockets. + +Werden direkt von Starlette bereitgestellt, Sie können sie jedoch von `fastapi` importieren: + +```python +from fastapi.websockets import WebSocketDisconnect, WebSocketState +``` + +::: fastapi.websockets.WebSocketDisconnect + +::: fastapi.websockets.WebSocketState diff --git a/docs/de/docs/resources/index.md b/docs/de/docs/resources/index.md new file mode 100644 index 0000000000000..abf270d9fd0b2 --- /dev/null +++ b/docs/de/docs/resources/index.md @@ -0,0 +1,3 @@ +# Ressourcen + +Zusätzliche Ressourcen, externe Links, Artikel und mehr. ✈️ diff --git a/docs/de/docs/tutorial/background-tasks.md b/docs/de/docs/tutorial/background-tasks.md new file mode 100644 index 0000000000000..a7bfd55a7dae8 --- /dev/null +++ b/docs/de/docs/tutorial/background-tasks.md @@ -0,0 +1,126 @@ +# Hintergrundtasks + +Sie können Hintergrundtasks (Hintergrund-Aufgaben) definieren, die *nach* der Rückgabe einer Response ausgeführt werden sollen. + +Das ist nützlich für Vorgänge, die nach einem Request ausgeführt werden müssen, bei denen der Client jedoch nicht unbedingt auf den Abschluss des Vorgangs warten muss, bevor er die Response erhält. + +Hierzu zählen beispielsweise: + +* E-Mail-Benachrichtigungen, die nach dem Ausführen einer Aktion gesendet werden: + * Da die Verbindung zu einem E-Mail-Server und das Senden einer E-Mail in der Regel „langsam“ ist (einige Sekunden), können Sie die Response sofort zurücksenden und die E-Mail-Benachrichtigung im Hintergrund senden. +* Daten verarbeiten: + * Angenommen, Sie erhalten eine Datei, die einen langsamen Prozess durchlaufen muss. Sie können als Response „Accepted“ (HTTP 202) zurückgeben und die Datei im Hintergrund verarbeiten. + +## `BackgroundTasks` verwenden + +Importieren Sie zunächst `BackgroundTasks` und definieren Sie einen Parameter in Ihrer *Pfadoperation-Funktion* mit der Typdeklaration `BackgroundTasks`: + +```Python hl_lines="1 13" +{!../../../docs_src/background_tasks/tutorial001.py!} +``` + +**FastAPI** erstellt für Sie das Objekt vom Typ `BackgroundTasks` und übergibt es als diesen Parameter. + +## Eine Taskfunktion erstellen + +Erstellen Sie eine Funktion, die als Hintergrundtask ausgeführt werden soll. + +Es handelt sich schlicht um eine Standard-Funktion, die Parameter empfangen kann. + +Es kann sich um eine `async def`- oder normale `def`-Funktion handeln. **FastAPI** weiß, wie damit zu verfahren ist. + +In diesem Fall schreibt die Taskfunktion in eine Datei (den Versand einer E-Mail simulierend). + +Und da der Schreibvorgang nicht `async` und `await` verwendet, definieren wir die Funktion mit normalem `def`: + +```Python hl_lines="6-9" +{!../../../docs_src/background_tasks/tutorial001.py!} +``` + +## Den Hintergrundtask hinzufügen + +Übergeben Sie innerhalb Ihrer *Pfadoperation-Funktion* Ihre Taskfunktion mit der Methode `.add_task()` an das *Hintergrundtasks*-Objekt: + +```Python hl_lines="14" +{!../../../docs_src/background_tasks/tutorial001.py!} +``` + +`.add_task()` erhält als Argumente: + +* Eine Taskfunktion, die im Hintergrund ausgeführt wird (`write_notification`). +* Eine beliebige Folge von Argumenten, die der Reihe nach an die Taskfunktion übergeben werden sollen (`email`). +* Alle Schlüsselwort-Argumente, die an die Taskfunktion übergeben werden sollen (`message="some notification"`). + +## Dependency Injection + +Die Verwendung von `BackgroundTasks` funktioniert auch mit dem Dependency Injection System. Sie können einen Parameter vom Typ `BackgroundTasks` auf mehreren Ebenen deklarieren: in einer *Pfadoperation-Funktion*, in einer Abhängigkeit (Dependable), in einer Unterabhängigkeit usw. + +**FastAPI** weiß, was jeweils zu tun ist und wie dasselbe Objekt wiederverwendet werden kann, sodass alle Hintergrundtasks zusammengeführt und anschließend im Hintergrund ausgeführt werden: + +=== "Python 3.10+" + + ```Python hl_lines="13 15 22 25" + {!> ../../../docs_src/background_tasks/tutorial002_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="13 15 22 25" + {!> ../../../docs_src/background_tasks/tutorial002_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="14 16 23 26" + {!> ../../../docs_src/background_tasks/tutorial002_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="11 13 20 23" + {!> ../../../docs_src/background_tasks/tutorial002_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="13 15 22 25" + {!> ../../../docs_src/background_tasks/tutorial002.py!} + ``` + +In obigem Beispiel werden die Nachrichten, *nachdem* die Response gesendet wurde, in die Datei `log.txt` geschrieben. + +Wenn im Request ein Query-Parameter enthalten war, wird dieser in einem Hintergrundtask in das Log geschrieben. + +Und dann schreibt ein weiterer Hintergrundtask, der in der *Pfadoperation-Funktion* erstellt wird, eine Nachricht unter Verwendung des Pfad-Parameters `email`. + +## Technische Details + +Die Klasse `BackgroundTasks` stammt direkt von `starlette.background`. + +Sie wird direkt in FastAPI importiert/inkludiert, sodass Sie sie von `fastapi` importieren können und vermeiden, versehentlich das alternative `BackgroundTask` (ohne das `s` am Ende) von `starlette.background` zu importieren. + +Indem Sie nur `BackgroundTasks` (und nicht `BackgroundTask`) verwenden, ist es dann möglich, es als *Pfadoperation-Funktion*-Parameter zu verwenden und **FastAPI** den Rest für Sie erledigen zu lassen, genau wie bei der direkten Verwendung des `Request`-Objekts. + +Es ist immer noch möglich, `BackgroundTask` allein in FastAPI zu verwenden, aber Sie müssen das Objekt in Ihrem Code erstellen und eine Starlette-`Response` zurückgeben, die es enthält. + +Weitere Details finden Sie in der offiziellen Starlette-Dokumentation für Hintergrundtasks. + +## Vorbehalt + +Wenn Sie umfangreiche Hintergrundberechnungen durchführen müssen und diese nicht unbedingt vom selben Prozess ausgeführt werden müssen (z. B. müssen Sie Speicher, Variablen, usw. nicht gemeinsam nutzen), könnte die Verwendung anderer größerer Tools wie z. B. Celery von Vorteil sein. + +Sie erfordern in der Regel komplexere Konfigurationen und einen Nachrichten-/Job-Queue-Manager wie RabbitMQ oder Redis, ermöglichen Ihnen jedoch die Ausführung von Hintergrundtasks in mehreren Prozessen und insbesondere auf mehreren Servern. + +Um ein Beispiel zu sehen, sehen Sie sich die [Projektgeneratoren](../project-generation.md){.internal-link target=_blank} an. Sie alle enthalten Celery, bereits konfiguriert. + +Wenn Sie jedoch über dieselbe **FastAPI**-Anwendung auf Variablen und Objekte zugreifen oder kleine Hintergrundtasks ausführen müssen (z. B. das Senden einer E-Mail-Benachrichtigung), können Sie einfach `BackgroundTasks` verwenden. + +## Zusammenfassung + +Importieren und verwenden Sie `BackgroundTasks` mit Parametern in *Pfadoperation-Funktionen* und Abhängigkeiten, um Hintergrundtasks hinzuzufügen. diff --git a/docs/de/docs/tutorial/bigger-applications.md b/docs/de/docs/tutorial/bigger-applications.md new file mode 100644 index 0000000000000..66dee0a9aa283 --- /dev/null +++ b/docs/de/docs/tutorial/bigger-applications.md @@ -0,0 +1,506 @@ +# Größere Anwendungen – mehrere Dateien + +Wenn Sie eine Anwendung oder eine Web-API erstellen, ist es selten der Fall, dass Sie alles in einer einzigen Datei unterbringen können. + +**FastAPI** bietet ein praktisches Werkzeug zur Strukturierung Ihrer Anwendung bei gleichzeitiger Wahrung der Flexibilität. + +!!! info + Wenn Sie von Flask kommen, wäre dies das Äquivalent zu Flasks Blueprints. + +## Eine Beispiel-Dateistruktur + +Nehmen wir an, Sie haben eine Dateistruktur wie diese: + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +│   ├── dependencies.py +│   └── routers +│   │ ├── __init__.py +│   │ ├── items.py +│   │ └── users.py +│   └── internal +│   ├── __init__.py +│   └── admin.py +``` + +!!! tip "Tipp" + Es gibt mehrere `__init__.py`-Dateien: eine in jedem Verzeichnis oder Unterverzeichnis. + + Das ermöglicht den Import von Code aus einer Datei in eine andere. + + In `app/main.py` könnten Sie beispielsweise eine Zeile wie diese haben: + + ``` + from app.routers import items + ``` + +* Das Verzeichnis `app` enthält alles. Und es hat eine leere Datei `app/__init__.py`, es handelt sich also um ein „Python-Package“ (eine Sammlung von „Python-Modulen“): `app`. +* Es enthält eine Datei `app/main.py`. Da sie sich in einem Python-Package (einem Verzeichnis mit einer Datei `__init__.py`) befindet, ist sie ein „Modul“ dieses Packages: `app.main`. +* Es gibt auch eine Datei `app/dependencies.py`, genau wie `app/main.py` ist sie ein „Modul“: `app.dependencies`. +* Es gibt ein Unterverzeichnis `app/routers/` mit einer weiteren Datei `__init__.py`, es handelt sich also um ein „Python-Subpackage“: `app.routers`. +* Die Datei `app/routers/items.py` befindet sich in einem Package, `app/routers/`, also ist sie ein Submodul: `app.routers.items`. +* Das Gleiche gilt für `app/routers/users.py`, es ist ein weiteres Submodul: `app.routers.users`. +* Es gibt auch ein Unterverzeichnis `app/internal/` mit einer weiteren Datei `__init__.py`, es handelt sich also um ein weiteres „Python-Subpackage“: `app.internal`. +* Und die Datei `app/internal/admin.py` ist ein weiteres Submodul: `app.internal.admin`. + + + +Die gleiche Dateistruktur mit Kommentaren: + +``` +. +├── app # „app“ ist ein Python-Package +│   ├── __init__.py # diese Datei macht „app“ zu einem „Python-Package“ +│   ├── main.py # „main“-Modul, z. B. import app.main +│   ├── dependencies.py # „dependencies“-Modul, z. B. import app.dependencies +│   └── routers # „routers“ ist ein „Python-Subpackage“ +│   │ ├── __init__.py # macht „routers“ zu einem „Python-Subpackage“ +│   │ ├── items.py # „items“-Submodul, z. B. import app.routers.items +│   │ └── users.py # „users“-Submodul, z. B. import app.routers.users +│   └── internal # „internal“ ist ein „Python-Subpackage“ +│   ├── __init__.py # macht „internal“ zu einem „Python-Subpackage“ +│   └── admin.py # „admin“-Submodul, z. B. import app.internal.admin +``` + +## `APIRouter` + +Nehmen wir an, die Datei, die nur für die Verwaltung von Benutzern zuständig ist, ist das Submodul unter `/app/routers/users.py`. + +Sie möchten die *Pfadoperationen* für Ihre Benutzer vom Rest des Codes trennen, um ihn organisiert zu halten. + +Aber es ist immer noch Teil derselben **FastAPI**-Anwendung/Web-API (es ist Teil desselben „Python-Packages“). + +Sie können die *Pfadoperationen* für dieses Modul mit `APIRouter` erstellen. + +### `APIRouter` importieren + +Sie importieren ihn und erstellen eine „Instanz“ auf die gleiche Weise wie mit der Klasse `FastAPI`: + +```Python hl_lines="1 3" title="app/routers/users.py" +{!../../../docs_src/bigger_applications/app/routers/users.py!} +``` + +### *Pfadoperationen* mit `APIRouter` + +Und dann verwenden Sie ihn, um Ihre *Pfadoperationen* zu deklarieren. + +Verwenden Sie ihn auf die gleiche Weise wie die Klasse `FastAPI`: + +```Python hl_lines="6 11 16" title="app/routers/users.py" +{!../../../docs_src/bigger_applications/app/routers/users.py!} +``` + +Sie können sich `APIRouter` als eine „Mini-`FastAPI`“-Klasse vorstellen. + +Alle die gleichen Optionen werden unterstützt. + +Alle die gleichen `parameters`, `responses`, `dependencies`, `tags`, usw. + +!!! tip "Tipp" + In diesem Beispiel heißt die Variable `router`, aber Sie können ihr einen beliebigen Namen geben. + +Wir werden diesen `APIRouter` in die Hauptanwendung `FastAPI` einbinden, aber zuerst kümmern wir uns um die Abhängigkeiten und einen anderen `APIRouter`. + +## Abhängigkeiten + +Wir sehen, dass wir einige Abhängigkeiten benötigen, die an mehreren Stellen der Anwendung verwendet werden. + +Also fügen wir sie in ihr eigenes `dependencies`-Modul (`app/dependencies.py`) ein. + +Wir werden nun eine einfache Abhängigkeit verwenden, um einen benutzerdefinierten `X-Token`-Header zu lesen: + +=== "Python 3.9+" + + ```Python hl_lines="3 6-8" title="app/dependencies.py" + {!> ../../../docs_src/bigger_applications/app_an_py39/dependencies.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="1 5-7" title="app/dependencies.py" + {!> ../../../docs_src/bigger_applications/app_an/dependencies.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="1 4-6" title="app/dependencies.py" + {!> ../../../docs_src/bigger_applications/app/dependencies.py!} + ``` + +!!! tip "Tipp" + Um dieses Beispiel zu vereinfachen, verwenden wir einen erfundenen Header. + + Aber in der Praxis werden Sie mit den integrierten [Sicherheits-Werkzeugen](security/index.md){.internal-link target=_blank} bessere Ergebnisse erzielen. + +## Ein weiteres Modul mit `APIRouter`. + +Nehmen wir an, Sie haben im Modul unter `app/routers/items.py` auch die Endpunkte, die für die Verarbeitung von Artikeln („Items“) aus Ihrer Anwendung vorgesehen sind. + +Sie haben *Pfadoperationen* für: + +* `/items/` +* `/items/{item_id}` + +Es ist alles die gleiche Struktur wie bei `app/routers/users.py`. + +Aber wir wollen schlauer sein und den Code etwas vereinfachen. + +Wir wissen, dass alle *Pfadoperationen* in diesem Modul folgendes haben: + +* Pfad-`prefix`: `/items`. +* `tags`: (nur ein Tag: `items`). +* Zusätzliche `responses`. +* `dependencies`: Sie alle benötigen die von uns erstellte `X-Token`-Abhängigkeit. + +Anstatt also alles zu jeder *Pfadoperation* hinzuzufügen, können wir es dem `APIRouter` hinzufügen. + +```Python hl_lines="5-10 16 21" title="app/routers/items.py" +{!../../../docs_src/bigger_applications/app/routers/items.py!} +``` + +Da der Pfad jeder *Pfadoperation* mit `/` beginnen muss, wie in: + +```Python hl_lines="1" +@router.get("/{item_id}") +async def read_item(item_id: str): + ... +``` + +... darf das Präfix kein abschließendes `/` enthalten. + +Das Präfix lautet in diesem Fall also `/items`. + +Wir können auch eine Liste von `tags` und zusätzliche `responses` hinzufügen, die auf alle in diesem Router enthaltenen *Pfadoperationen* angewendet werden. + +Und wir können eine Liste von `dependencies` hinzufügen, die allen *Pfadoperationen* im Router hinzugefügt und für jeden an sie gerichteten Request ausgeführt/aufgelöst werden. + +!!! tip "Tipp" + Beachten Sie, dass ähnlich wie bei [Abhängigkeiten in *Pfadoperation-Dekoratoren*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank} kein Wert an Ihre *Pfadoperation-Funktion* übergeben wird. + +Das Endergebnis ist, dass die Pfade für diese Artikel jetzt wie folgt lauten: + +* `/items/` +* `/items/{item_id}` + +... wie wir es beabsichtigt hatten. + +* Sie werden mit einer Liste von Tags gekennzeichnet, die einen einzelnen String `"items"` enthält. + * Diese „Tags“ sind besonders nützlich für die automatischen interaktiven Dokumentationssysteme (unter Verwendung von OpenAPI). +* Alle enthalten die vordefinierten `responses`. +* Für alle diese *Pfadoperationen* wird die Liste der `dependencies` ausgewertet/ausgeführt, bevor sie selbst ausgeführt werden. + * Wenn Sie außerdem Abhängigkeiten in einer bestimmten *Pfadoperation* deklarieren, **werden diese ebenfalls ausgeführt**. + * Zuerst werden die Router-Abhängigkeiten ausgeführt, dann die [`dependencies` im Dekorator](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank} und dann die normalen Parameterabhängigkeiten. + * Sie können auch [`Security`-Abhängigkeiten mit `scopes`](../advanced/security/oauth2-scopes.md){.internal-link target=_blank} hinzufügen. + +!!! tip "Tipp" + `dependencies` im `APIRouter` können beispielsweise verwendet werden, um eine Authentifizierung für eine ganze Gruppe von *Pfadoperationen* zu erfordern. Selbst wenn die Abhängigkeiten nicht jeder einzeln hinzugefügt werden. + +!!! check + Die Parameter `prefix`, `tags`, `responses` und `dependencies` sind (wie in vielen anderen Fällen) nur ein Feature von **FastAPI**, um Ihnen dabei zu helfen, Codeverdoppelung zu vermeiden. + +### Die Abhängigkeiten importieren + +Der folgende Code befindet sich im Modul `app.routers.items`, also in der Datei `app/routers/items.py`. + +Und wir müssen die Abhängigkeitsfunktion aus dem Modul `app.dependencies` importieren, also aus der Datei `app/dependencies.py`. + +Daher verwenden wir einen relativen Import mit `..` für die Abhängigkeiten: + +```Python hl_lines="3" title="app/routers/items.py" +{!../../../docs_src/bigger_applications/app/routers/items.py!} +``` + +#### Wie relative Importe funktionieren + +!!! tip "Tipp" + Wenn Sie genau wissen, wie Importe funktionieren, fahren Sie mit dem nächsten Abschnitt unten fort. + +Ein einzelner Punkt `.`, wie in: + +```Python +from .dependencies import get_token_header +``` + +würde bedeuten: + +* Beginnend im selben Package, in dem sich dieses Modul (die Datei `app/routers/items.py`) befindet (das Verzeichnis `app/routers/`) ... +* finde das Modul `dependencies` (eine imaginäre Datei unter `app/routers/dependencies.py`) ... +* und importiere daraus die Funktion `get_token_header`. + +Aber diese Datei existiert nicht, unsere Abhängigkeiten befinden sich in einer Datei unter `app/dependencies.py`. + +Erinnern Sie sich, wie unsere Anwendungs-/Dateistruktur aussieht: + + + +--- + +Die beiden Punkte `..`, wie in: + +```Python +from ..dependencies import get_token_header +``` + +bedeuten: + +* Beginnend im selben Package, in dem sich dieses Modul (die Datei `app/routers/items.py`) befindet (das Verzeichnis `app/routers/`) ... +* gehe zum übergeordneten Package (das Verzeichnis `app/`) ... +* und finde dort das Modul `dependencies` (die Datei unter `app/dependencies.py`) ... +* und importiere daraus die Funktion `get_token_header`. + +Das funktioniert korrekt! 🎉 + +--- + +Das Gleiche gilt, wenn wir drei Punkte `...` verwendet hätten, wie in: + +```Python +from ...dependencies import get_token_header +``` + +Das würde bedeuten: + +* Beginnend im selben Package, in dem sich dieses Modul (die Datei `app/routers/items.py`) befindet (das Verzeichnis `app/routers/`) ... +* gehe zum übergeordneten Package (das Verzeichnis `app/`) ... +* gehe dann zum übergeordneten Package dieses Packages (es gibt kein übergeordnetes Package, `app` ist die oberste Ebene 😱) ... +* und finde dort das Modul `dependencies` (die Datei unter `app/dependencies.py`) ... +* und importiere daraus die Funktion `get_token_header`. + +Das würde sich auf ein Paket oberhalb von `app/` beziehen, mit seiner eigenen Datei `__init__.py`, usw. Aber das haben wir nicht. Das würde in unserem Beispiel also einen Fehler auslösen. 🚨 + +Aber jetzt wissen Sie, wie es funktioniert, sodass Sie relative Importe in Ihren eigenen Anwendungen verwenden können, egal wie komplex diese sind. 🤓 + +### Einige benutzerdefinierte `tags`, `responses`, und `dependencies` hinzufügen + +Wir fügen weder das Präfix `/items` noch `tags=["items"]` zu jeder *Pfadoperation* hinzu, da wir sie zum `APIRouter` hinzugefügt haben. + +Aber wir können immer noch _mehr_ `tags` hinzufügen, die auf eine bestimmte *Pfadoperation* angewendet werden, sowie einige zusätzliche `responses`, die speziell für diese *Pfadoperation* gelten: + +```Python hl_lines="30-31" title="app/routers/items.py" +{!../../../docs_src/bigger_applications/app/routers/items.py!} +``` + +!!! tip "Tipp" + Diese letzte Pfadoperation wird eine Kombination von Tags haben: `["items", "custom"]`. + + Und sie wird auch beide Responses in der Dokumentation haben, eine für `404` und eine für `403`. + +## Das Haupt-`FastAPI`. + +Sehen wir uns nun das Modul unter `app/main.py` an. + +Hier importieren und verwenden Sie die Klasse `FastAPI`. + +Dies ist die Hauptdatei Ihrer Anwendung, die alles zusammen bindet. + +Und da sich der Großteil Ihrer Logik jetzt in seinem eigenen spezifischen Modul befindet, wird die Hauptdatei recht einfach sein. + +### `FastAPI` importieren + +Sie importieren und erstellen wie gewohnt eine `FastAPI`-Klasse. + +Und wir können sogar [globale Abhängigkeiten](dependencies/global-dependencies.md){.internal-link target=_blank} deklarieren, die mit den Abhängigkeiten für jeden `APIRouter` kombiniert werden: + +```Python hl_lines="1 3 7" title="app/main.py" +{!../../../docs_src/bigger_applications/app/main.py!} +``` + +### Den `APIRouter` importieren + +Jetzt importieren wir die anderen Submodule, die `APIRouter` haben: + +```Python hl_lines="4-5" title="app/main.py" +{!../../../docs_src/bigger_applications/app/main.py!} +``` + +Da es sich bei den Dateien `app/routers/users.py` und `app/routers/items.py` um Submodule handelt, die Teil desselben Python-Packages `app` sind, können wir einen einzelnen Punkt `.` verwenden, um sie mit „relativen Imports“ zu importieren. + +### Wie das Importieren funktioniert + +Die Sektion: + +```Python +from .routers import items, users +``` + +bedeutet: + +* Beginnend im selben Package, in dem sich dieses Modul (die Datei `app/main.py`) befindet (das Verzeichnis `app/`) ... +* Suche nach dem Subpackage `routers` (das Verzeichnis unter `app/routers/`) ... +* und importiere daraus die Submodule `items` (die Datei unter `app/routers/items.py`) und `users` (die Datei unter `app/routers/users.py`) ... + +Das Modul `items` verfügt über eine Variable `router` (`items.router`). Das ist dieselbe, die wir in der Datei `app/routers/items.py` erstellt haben, es ist ein `APIRouter`-Objekt. + +Und dann machen wir das gleiche für das Modul `users`. + +Wir könnten sie auch wie folgt importieren: + +```Python +from app.routers import items, users +``` + +!!! info + Die erste Version ist ein „relativer Import“: + + ```Python + from .routers import items, users + ``` + + Die zweite Version ist ein „absoluter Import“: + + ```Python + from app.routers import items, users + ``` + + Um mehr über Python-Packages und -Module zu erfahren, lesen Sie die offizielle Python-Dokumentation über Module. + +### Namenskollisionen vermeiden + +Wir importieren das Submodul `items` direkt, anstatt nur seine Variable `router` zu importieren. + +Das liegt daran, dass wir im Submodul `users` auch eine weitere Variable namens `router` haben. + +Wenn wir eine nach der anderen importiert hätten, etwa: + +```Python +from .routers.items import router +from .routers.users import router +``` + +würde der `router` von `users` den von `items` überschreiben und wir könnten sie nicht gleichzeitig verwenden. + +Um also beide in derselben Datei verwenden zu können, importieren wir die Submodule direkt: + +```Python hl_lines="5" title="app/main.py" +{!../../../docs_src/bigger_applications/app/main.py!} +``` + + +### Die `APIRouter` für `users` und `items` inkludieren + +Inkludieren wir nun die `router` aus diesen Submodulen `users` und `items`: + +```Python hl_lines="10-11" title="app/main.py" +{!../../../docs_src/bigger_applications/app/main.py!} +``` + +!!! info + `users.router` enthält den `APIRouter` in der Datei `app/routers/users.py`. + + Und `items.router` enthält den `APIRouter` in der Datei `app/routers/items.py`. + +Mit `app.include_router()` können wir jeden `APIRouter` zur Hauptanwendung `FastAPI` hinzufügen. + +Es wird alle Routen von diesem Router als Teil von dieser inkludieren. + +!!! note "Technische Details" + Tatsächlich wird intern eine *Pfadoperation* für jede *Pfadoperation* erstellt, die im `APIRouter` deklariert wurde. + + Hinter den Kulissen wird es also tatsächlich so funktionieren, als ob alles dieselbe einzige Anwendung wäre. + +!!! check + Bei der Einbindung von Routern müssen Sie sich keine Gedanken über die Performanz machen. + + Dies dauert Mikrosekunden und geschieht nur beim Start. + + Es hat also keinen Einfluss auf die Leistung. ⚡ + +### Einen `APIRouter` mit benutzerdefinierten `prefix`, `tags`, `responses` und `dependencies` einfügen + +Stellen wir uns nun vor, dass Ihre Organisation Ihnen die Datei `app/internal/admin.py` gegeben hat. + +Sie enthält einen `APIRouter` mit einigen administrativen *Pfadoperationen*, die Ihre Organisation zwischen mehreren Projekten teilt. + +In diesem Beispiel wird es ganz einfach sein. Nehmen wir jedoch an, dass wir, da sie mit anderen Projekten in der Organisation geteilt wird, sie nicht ändern und kein `prefix`, `dependencies`, `tags`, usw. direkt zum `APIRouter` hinzufügen können: + +```Python hl_lines="3" title="app/internal/admin.py" +{!../../../docs_src/bigger_applications/app/internal/admin.py!} +``` + +Aber wir möchten immer noch ein benutzerdefiniertes `prefix` festlegen, wenn wir den `APIRouter` einbinden, sodass alle seine *Pfadoperationen* mit `/admin` beginnen, wir möchten es mit den `dependencies` sichern, die wir bereits für dieses Projekt haben, und wir möchten `tags` und `responses` hinzufügen. + +Wir können das alles deklarieren, ohne den ursprünglichen `APIRouter` ändern zu müssen, indem wir diese Parameter an `app.include_router()` übergeben: + +```Python hl_lines="14-17" title="app/main.py" +{!../../../docs_src/bigger_applications/app/main.py!} +``` + +Auf diese Weise bleibt der ursprüngliche `APIRouter` unverändert, sodass wir dieselbe `app/internal/admin.py`-Datei weiterhin mit anderen Projekten in der Organisation teilen können. + +Das Ergebnis ist, dass in unserer Anwendung jede der *Pfadoperationen* aus dem Modul `admin` Folgendes haben wird: + +* Das Präfix `/admin`. +* Den Tag `admin`. +* Die Abhängigkeit `get_token_header`. +* Die Response `418`. 🍵 + +Dies wirkt sich jedoch nur auf diesen `APIRouter` in unserer Anwendung aus, nicht auf anderen Code, der ihn verwendet. + +So könnten beispielsweise andere Projekte denselben `APIRouter` mit einer anderen Authentifizierungsmethode verwenden. + +### Eine *Pfadoperation* hinzufügen + +Wir können *Pfadoperationen* auch direkt zur `FastAPI`-App hinzufügen. + +Hier machen wir es ... nur um zu zeigen, dass wir es können 🤷: + +```Python hl_lines="21-23" title="app/main.py" +{!../../../docs_src/bigger_applications/app/main.py!} +``` + +und es wird korrekt funktionieren, zusammen mit allen anderen *Pfadoperationen*, die mit `app.include_router()` hinzugefügt wurden. + +!!! info "Sehr technische Details" + **Hinweis**: Dies ist ein sehr technisches Detail, das Sie wahrscheinlich **einfach überspringen** können. + + --- + + Die `APIRouter` sind nicht „gemountet“, sie sind nicht vom Rest der Anwendung isoliert. + + Das liegt daran, dass wir deren *Pfadoperationen* in das OpenAPI-Schema und die Benutzeroberflächen einbinden möchten. + + Da wir sie nicht einfach isolieren und unabhängig vom Rest „mounten“ können, werden die *Pfadoperationen* „geklont“ (neu erstellt) und nicht direkt einbezogen. + +## Es in der automatischen API-Dokumentation ansehen + +Führen Sie nun `uvicorn` aus, indem Sie das Modul `app.main` und die Variable `app` verwenden: + +
+ +```console +$ uvicorn app.main:app --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +und öffnen Sie die Dokumentation unter http://127.0.0.1:8000/docs. + +Sie sehen die automatische API-Dokumentation, einschließlich der Pfade aller Submodule, mit den richtigen Pfaden (und Präfixen) und den richtigen Tags: + + + +## Den gleichen Router mehrmals mit unterschiedlichem `prefix` inkludieren + +Sie können `.include_router()` auch mehrmals mit *demselben* Router und unterschiedlichen Präfixen verwenden. + +Dies könnte beispielsweise nützlich sein, um dieselbe API unter verschiedenen Präfixen verfügbar zu machen, z. B. `/api/v1` und `/api/latest`. + +Dies ist eine fortgeschrittene Verwendung, die Sie möglicherweise nicht wirklich benötigen, aber für den Fall, dass Sie sie benötigen, ist sie vorhanden. + +## Einen `APIRouter` in einen anderen einfügen + +Auf die gleiche Weise, wie Sie einen `APIRouter` in eine `FastAPI`-Anwendung einbinden können, können Sie einen `APIRouter` in einen anderen `APIRouter` einbinden, indem Sie Folgendes verwenden: + +```Python +router.include_router(other_router) +``` + +Stellen Sie sicher, dass Sie dies tun, bevor Sie `router` in die `FastAPI`-App einbinden, damit auch die *Pfadoperationen* von `other_router` inkludiert werden. diff --git a/docs/de/docs/tutorial/body-fields.md b/docs/de/docs/tutorial/body-fields.md new file mode 100644 index 0000000000000..643be7489ba46 --- /dev/null +++ b/docs/de/docs/tutorial/body-fields.md @@ -0,0 +1,115 @@ +# Body – Felder + +So wie Sie zusätzliche Validation und Metadaten in Parametern der **Pfadoperation-Funktion** mittels `Query`, `Path` und `Body` deklarieren, können Sie auch innerhalb von Pydantic-Modellen zusätzliche Validation und Metadaten deklarieren, mittels Pydantics `Field`. + +## `Field` importieren + +Importieren Sie es zuerst: + +=== "Python 3.10+" + + ```Python hl_lines="4" + {!> ../../../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.8+" + + ```Python hl_lines="4" + {!> ../../../docs_src/body_fields/tutorial001_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="2" + {!> ../../../docs_src/body_fields/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="4" + {!> ../../../docs_src/body_fields/tutorial001.py!} + ``` + +!!! warning "Achtung" + Beachten Sie, dass `Field` direkt von `pydantic` importiert wird, nicht von `fastapi`, wie die anderen (`Query`, `Path`, `Body`, usw.) + +## Modellattribute deklarieren + +Dann können Sie `Field` mit Modellattributen deklarieren: + +=== "Python 3.10+" + + ```Python hl_lines="11-14" + {!> ../../../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.8+" + + ```Python hl_lines="12-15" + {!> ../../../docs_src/body_fields/tutorial001_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="9-12" + {!> ../../../docs_src/body_fields/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="11-14" + {!> ../../../docs_src/body_fields/tutorial001.py!} + ``` + +`Field` funktioniert genauso wie `Query`, `Path` und `Body`, es hat die gleichen Parameter, usw. + +!!! note "Technische Details" + Tatsächlich erstellen `Query`, `Path` und andere, die sie kennenlernen werden, Instanzen von Unterklassen einer allgemeinen Klasse `Param`, die ihrerseits eine Unterklasse von Pydantics `FieldInfo`-Klasse ist. + + Und Pydantics `Field` gibt ebenfalls eine Instanz von `FieldInfo` zurück. + + `Body` gibt auch Instanzen einer Unterklasse von `FieldInfo` zurück. Und später werden Sie andere sehen, die Unterklassen der `Body`-Klasse sind. + + Denken Sie daran, dass `Query`, `Path` und andere von `fastapi` tatsächlich Funktionen sind, die spezielle Klassen zurückgeben. + +!!! tip "Tipp" + Beachten Sie, dass jedes Modellattribut mit einem Typ, Defaultwert und `Field` die gleiche Struktur hat wie ein Parameter einer Pfadoperation-Funktion, nur mit `Field` statt `Path`, `Query`, `Body`. + +## Zusätzliche Information hinzufügen + +Sie können zusätzliche Information in `Field`, `Query`, `Body`, usw. deklarieren. Und es wird im generierten JSON-Schema untergebracht. + +Sie werden später mehr darüber lernen, wie man zusätzliche Information unterbringt, wenn Sie lernen, Beispiele zu deklarieren. + +!!! warning "Achtung" + Extra-Schlüssel, die `Field` überreicht werden, werden auch im resultierenden OpenAPI-Schema Ihrer Anwendung gelistet. Da diese Schlüssel nicht notwendigerweise Teil der OpenAPI-Spezifikation sind, könnten einige OpenAPI-Tools, wie etwa [der OpenAPI-Validator](https://validator.swagger.io/), nicht mit Ihrem generierten Schema funktionieren. + +## Zusammenfassung + +Sie können Pydantics `Field` verwenden, um zusätzliche Validierungen und Metadaten für Modellattribute zu deklarieren. + +Sie können auch Extra-Schlüssel verwenden, um zusätzliche JSON-Schema-Metadaten zu überreichen. diff --git a/docs/de/docs/tutorial/body-multiple-params.md b/docs/de/docs/tutorial/body-multiple-params.md new file mode 100644 index 0000000000000..6a237243e5f3b --- /dev/null +++ b/docs/de/docs/tutorial/body-multiple-params.md @@ -0,0 +1,308 @@ +# Body – Mehrere Parameter + +Jetzt, da wir gesehen haben, wie `Path` und `Query` verwendet werden, schauen wir uns fortgeschrittenere Verwendungsmöglichkeiten von Requestbody-Deklarationen an. + +## `Path`-, `Query`- und Body-Parameter vermischen + +Zuerst einmal, Sie können `Path`-, `Query`- und Requestbody-Parameter-Deklarationen frei mischen und **FastAPI** wird wissen, was zu tun ist. + +Und Sie können auch Body-Parameter als optional kennzeichnen, indem Sie den Defaultwert auf `None` setzen: + +=== "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.8+" + + ```Python hl_lines="19-21" + {!> ../../../docs_src/body_multiple_params/tutorial001_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="17-19" + {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="19-21" + {!> ../../../docs_src/body_multiple_params/tutorial001.py!} + ``` + +!!! note "Hinweis" + Beachten Sie, dass in diesem Fall das `item`, welches vom Body genommen wird, optional ist. Da es `None` als Defaultwert hat. + +## Mehrere Body-Parameter + +Im vorherigen Beispiel erwartete die *Pfadoperation* einen JSON-Body mit den Attributen eines `Item`s, etwa: + +```JSON +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 +} +``` + +Aber Sie können auch mehrere Body-Parameter deklarieren, z. B. `item` und `user`: + +=== "Python 3.10+" + + ```Python hl_lines="20" + {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="22" + {!> ../../../docs_src/body_multiple_params/tutorial002.py!} + ``` + +In diesem Fall wird **FastAPI** bemerken, dass es mehr als einen Body-Parameter in der Funktion gibt (zwei Parameter, die Pydantic-Modelle sind). + +Es wird deshalb die Parameternamen als Schlüssel (Feldnamen) im Body verwenden, und erwartet einen Body wie folgt: + +```JSON +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + }, + "user": { + "username": "dave", + "full_name": "Dave Grohl" + } +} +``` + +!!! note "Hinweis" + Beachten Sie, dass, obwohl `item` wie zuvor deklariert wurde, es nun unter einem Schlüssel `item` im Body erwartet wird. + +**FastAPI** wird die automatische Konvertierung des Requests übernehmen, sodass der Parameter `item` seinen spezifischen Inhalt bekommt, genau so wie der Parameter `user`. + +Es wird die Validierung dieser zusammengesetzten Daten übernehmen, und sie im OpenAPI-Schema und der automatischen Dokumentation dokumentieren. + +## Einzelne Werte im Body + +So wie `Query` und `Path` für Query- und Pfad-Parameter, hat **FastAPI** auch das Äquivalent `Body`, um Extra-Daten für Body-Parameter zu definieren. + +Zum Beispiel, das vorherige Modell erweiternd, könnten Sie entscheiden, dass Sie einen weiteren Schlüssel `importance` haben möchten, im selben Body, Seite an Seite mit `item` und `user`. + +Wenn Sie diesen Parameter einfach so hinzufügen, wird **FastAPI** annehmen, dass es ein Query-Parameter ist. + +Aber Sie können **FastAPI** instruieren, ihn als weiteren Body-Schlüssel zu erkennen, indem Sie `Body` verwenden: + +=== "Python 3.10+" + + ```Python hl_lines="23" + {!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="23" + {!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="24" + {!> ../../../docs_src/body_multiple_params/tutorial003_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="20" + {!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="22" + {!> ../../../docs_src/body_multiple_params/tutorial003.py!} + ``` + +In diesem Fall erwartet **FastAPI** einen Body wie: + +```JSON +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + }, + "user": { + "username": "dave", + "full_name": "Dave Grohl" + }, + "importance": 5 +} +``` + +Wiederum wird es die Daten konvertieren, validieren, dokumentieren, usw. + +## Mehrere Body-Parameter und Query-Parameter + +Natürlich können Sie auch, wann immer Sie das brauchen, weitere Query-Parameter hinzufügen, zusätzlich zu den Body-Parametern. + +Da einfache Werte standardmäßig als Query-Parameter interpretiert werden, müssen Sie `Query` nicht explizit hinzufügen, Sie können einfach schreiben: + +```Python +q: Union[str, None] = None +``` + +Oder in Python 3.10 und darüber: + +```Python +q: str | None = None +``` + +Zum Beispiel: + +=== "Python 3.10+" + + ```Python hl_lines="27" + {!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="27" + {!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="28" + {!> ../../../docs_src/body_multiple_params/tutorial004_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="25" + {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="27" + {!> ../../../docs_src/body_multiple_params/tutorial004.py!} + ``` + +!!! info + `Body` hat die gleichen zusätzlichen Validierungs- und Metadaten-Parameter wie `Query` und `Path` und andere, die Sie später kennenlernen. + +## Einen einzelnen Body-Parameter einbetten + +Nehmen wir an, Sie haben nur einen einzelnen `item`-Body-Parameter, ein Pydantic-Modell `Item`. + +Normalerweise wird **FastAPI** dann seinen JSON-Body direkt erwarten. + +Aber wenn Sie möchten, dass es einen JSON-Body erwartet, mit einem Schlüssel `item` und darin den Inhalt des Modells, so wie es das tut, wenn Sie mehrere Body-Parameter deklarieren, dann können Sie den speziellen `Body`-Parameter `embed` setzen: + +```Python +item: Item = Body(embed=True) +``` + +so wie in: + +=== "Python 3.10+" + + ```Python hl_lines="17" + {!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="17" + {!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="18" + {!> ../../../docs_src/body_multiple_params/tutorial005_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="15" + {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="17" + {!> ../../../docs_src/body_multiple_params/tutorial005.py!} + ``` + +In diesem Fall erwartet **FastAPI** einen Body wie: + +```JSON hl_lines="2" +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + } +} +``` + +statt: + +```JSON +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 +} +``` + +## Zusammenfassung + +Sie können mehrere Body-Parameter zu ihrer *Pfadoperation-Funktion* hinzufügen, obwohl ein Request nur einen einzigen Body enthalten kann. + +**FastAPI** wird sich darum kümmern, Ihnen korrekte Daten in Ihrer Funktion zu überreichen, und das korrekte Schema in der *Pfadoperation* zu validieren und zu dokumentieren. + +Sie können auch einzelne Werte deklarieren, die als Teil des Bodys empfangen werden. + +Und Sie können **FastAPI** instruieren, den Body in einem Schlüssel unterzubringen, selbst wenn nur ein einzelner Body-Parameter deklariert ist. diff --git a/docs/de/docs/tutorial/body-nested-models.md b/docs/de/docs/tutorial/body-nested-models.md new file mode 100644 index 0000000000000..a7a15a6c241c7 --- /dev/null +++ b/docs/de/docs/tutorial/body-nested-models.md @@ -0,0 +1,382 @@ +# Body – Verschachtelte Modelle + +Mit **FastAPI** können Sie (dank Pydantic) beliebig tief verschachtelte Modelle definieren, validieren und dokumentieren. + +## Listen als Felder + +Sie können ein Attribut als Kindtyp definieren, zum Beispiel eine Python-`list`e. + +=== "Python 3.10+" + + ```Python hl_lines="12" + {!> ../../../docs_src/body_nested_models/tutorial001_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="14" + {!> ../../../docs_src/body_nested_models/tutorial001.py!} + ``` + +Das bewirkt, dass `tags` eine Liste ist, wenngleich es nichts über den Typ der Elemente der Liste aussagt. + +## Listen mit Typ-Parametern als Felder + +Aber Python erlaubt es, Listen mit inneren Typen, auch „Typ-Parameter“ genannt, zu deklarieren. + +### `List` von `typing` importieren + +In Python 3.9 oder darüber können Sie einfach `list` verwenden, um diese Typannotationen zu deklarieren, wie wir unten sehen werden. 💡 + +In Python-Versionen vor 3.9 (3.6 und darüber), müssen Sie zuerst `List` von Pythons Standardmodul `typing` importieren. + +```Python hl_lines="1" +{!> ../../../docs_src/body_nested_models/tutorial002.py!} +``` + +### Eine `list`e mit einem Typ-Parameter deklarieren + +Um Typen wie `list`, `dict`, `tuple` mit inneren Typ-Parametern (inneren Typen) zu deklarieren: + +* Wenn Sie eine Python-Version kleiner als 3.9 verwenden, importieren Sie das Äquivalent zum entsprechenden Typ vom `typing`-Modul +* Überreichen Sie den/die inneren Typ(en) von eckigen Klammern umschlossen, `[` und `]`, als „Typ-Parameter“ + +In Python 3.9 wäre das: + +```Python +my_list: list[str] +``` + +Und in Python-Versionen vor 3.9: + +```Python +from typing import List + +my_list: List[str] +``` + +Das ist alles Standard-Python-Syntax für Typdeklarationen. + +Verwenden Sie dieselbe Standardsyntax für Modellattribute mit inneren Typen. + +In unserem Beispiel können wir also bewirken, dass `tags` spezifisch eine „Liste von Strings“ ist: + +=== "Python 3.10+" + + ```Python hl_lines="12" + {!> ../../../docs_src/body_nested_models/tutorial002_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="14" + {!> ../../../docs_src/body_nested_models/tutorial002_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="14" + {!> ../../../docs_src/body_nested_models/tutorial002.py!} + ``` + +## Set-Typen + +Aber dann denken wir darüber nach und stellen fest, dass sich die Tags nicht wiederholen sollen, es sollen eindeutige Strings sein. + +Python hat einen Datentyp speziell für Mengen eindeutiger Dinge: das `set`. + +Deklarieren wir also `tags` als Set von Strings. + +=== "Python 3.10+" + + ```Python hl_lines="12" + {!> ../../../docs_src/body_nested_models/tutorial003_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="14" + {!> ../../../docs_src/body_nested_models/tutorial003_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="1 14" + {!> ../../../docs_src/body_nested_models/tutorial003.py!} + ``` + +Jetzt, selbst wenn Sie einen Request mit duplizierten Daten erhalten, werden diese zu einem Set eindeutiger Dinge konvertiert. + +Und wann immer Sie diese Daten ausgeben, selbst wenn die Quelle Duplikate hatte, wird es als Set von eindeutigen Dingen ausgegeben. + +Und es wird entsprechend annotiert/dokumentiert. + +## Verschachtelte Modelle + +Jedes Attribut eines Pydantic-Modells hat einen Typ. + +Aber dieser Typ kann selbst ein anderes Pydantic-Modell sein. + +Sie können also tief verschachtelte JSON-„Objekte“ deklarieren, mit spezifischen Attributnamen, -typen, und -validierungen. + +Alles das beliebig tief verschachtelt. + +### Ein Kindmodell definieren + +Wir können zum Beispiel ein `Image`-Modell definieren. + +=== "Python 3.10+" + + ```Python hl_lines="7-9" + {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="9-11" + {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9-11" + {!> ../../../docs_src/body_nested_models/tutorial004.py!} + ``` + +### Das Kindmodell als Typ verwenden + +Und dann können wir es als Typ eines Attributes verwenden. + +=== "Python 3.10+" + + ```Python hl_lines="18" + {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="20" + {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="20" + {!> ../../../docs_src/body_nested_models/tutorial004.py!} + ``` + +Das würde bedeuten, dass **FastAPI** einen Body erwartet wie: + +```JSON +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2, + "tags": ["rock", "metal", "bar"], + "image": { + "url": "http://example.com/baz.jpg", + "name": "The Foo live" + } +} +``` + +Wiederum, nur mit dieser Deklaration erhalten Sie von **FastAPI**: + +* Editor-Unterstützung (Codevervollständigung, usw.), selbst für verschachtelte Modelle +* Datenkonvertierung +* Datenvalidierung +* Automatische Dokumentation + +## Spezielle Typen und Validierungen + +Abgesehen von normalen einfachen Typen, wie `str`, `int`, `float`, usw. können Sie komplexere einfache Typen verwenden, die von `str` erben. + +Um alle Optionen kennenzulernen, die Sie haben, schauen Sie sich Pydantics Typübersicht an. Sie werden im nächsten Kapitel ein paar Beispiele kennenlernen. + +Da wir zum Beispiel im `Image`-Modell ein Feld `url` haben, können wir deklarieren, dass das eine Instanz von Pydantics `HttpUrl` sein soll, anstelle eines `str`: + +=== "Python 3.10+" + + ```Python hl_lines="2 8" + {!> ../../../docs_src/body_nested_models/tutorial005_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="4 10" + {!> ../../../docs_src/body_nested_models/tutorial005_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="4 10" + {!> ../../../docs_src/body_nested_models/tutorial005.py!} + ``` + +Es wird getestet, ob der String eine gültige URL ist, und als solche wird er in JSON Schema / OpenAPI dokumentiert. + +## Attribute mit Listen von Kindmodellen + +Sie können Pydantic-Modelle auch als Typen innerhalb von `list`, `set`, usw. verwenden: + +=== "Python 3.10+" + + ```Python hl_lines="18" + {!> ../../../docs_src/body_nested_models/tutorial006_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="20" + {!> ../../../docs_src/body_nested_models/tutorial006_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="20" + {!> ../../../docs_src/body_nested_models/tutorial006.py!} + ``` + +Das wird einen JSON-Body erwarten (konvertieren, validieren, dokumentieren), wie: + +```JSON hl_lines="11" +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2, + "tags": [ + "rock", + "metal", + "bar" + ], + "images": [ + { + "url": "http://example.com/baz.jpg", + "name": "The Foo live" + }, + { + "url": "http://example.com/dave.jpg", + "name": "The Baz" + } + ] +} +``` + +!!! info + Beachten Sie, dass der `images`-Schlüssel jetzt eine Liste von Bild-Objekten hat. + +## Tief verschachtelte Modelle + +Sie können beliebig tief verschachtelte Modelle definieren: + +=== "Python 3.10+" + + ```Python hl_lines="7 12 18 21 25" + {!> ../../../docs_src/body_nested_models/tutorial007_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="9 14 20 23 27" + {!> ../../../docs_src/body_nested_models/tutorial007_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9 14 20 23 27" + {!> ../../../docs_src/body_nested_models/tutorial007.py!} + ``` + +!!! info + Beachten Sie, wie `Offer` eine Liste von `Item`s hat, von denen jedes seinerseits eine optionale Liste von `Image`s hat. + +## Bodys aus reinen Listen + +Wenn Sie möchten, dass das äußerste Element des JSON-Bodys ein JSON-`array` (eine Python-`list`e) ist, können Sie den Typ im Funktionsparameter deklarieren, mit der gleichen Syntax wie in Pydantic-Modellen: + +```Python +images: List[Image] +``` + +oder in Python 3.9 und darüber: + +```Python +images: list[Image] +``` + +so wie in: + +=== "Python 3.9+" + + ```Python hl_lines="13" + {!> ../../../docs_src/body_nested_models/tutorial008_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="15" + {!> ../../../docs_src/body_nested_models/tutorial008.py!} + ``` + +## Editor-Unterstützung überall + +Und Sie erhalten Editor-Unterstützung überall. + +Selbst für Dinge in Listen: + + + +Sie würden diese Editor-Unterstützung nicht erhalten, wenn Sie direkt mit `dict`, statt mit Pydantic-Modellen arbeiten würden. + +Aber Sie müssen sich auch nicht weiter um die Modelle kümmern, hereinkommende Dicts werden automatisch in sie konvertiert. Und was Sie zurückgeben, wird automatisch nach JSON konvertiert. + +## Bodys mit beliebigen `dict`s + +Sie können einen Body auch als `dict` deklarieren, mit Schlüsseln eines Typs und Werten eines anderen Typs. + +So brauchen Sie vorher nicht zu wissen, wie die Feld-/Attribut-Namen lauten (wie es bei Pydantic-Modellen der Fall wäre). + +Das ist nützlich, wenn Sie Schlüssel empfangen, deren Namen Sie nicht bereits kennen. + +--- + +Ein anderer nützlicher Anwendungsfall ist, wenn Sie Schlüssel eines anderen Typs haben wollen, z. B. `int`. + +Das schauen wir uns mal an. + +Im folgenden Beispiel akzeptieren Sie irgendein `dict`, solange es `int`-Schlüssel und `float`-Werte hat. + +=== "Python 3.9+" + + ```Python hl_lines="7" + {!> ../../../docs_src/body_nested_models/tutorial009_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9" + {!> ../../../docs_src/body_nested_models/tutorial009.py!} + ``` + +!!! tip "Tipp" + Bedenken Sie, dass JSON nur `str` als Schlüssel unterstützt. + + Aber Pydantic hat automatische Datenkonvertierung. + + Das bedeutet, dass Ihre API-Clients nur Strings senden können, aber solange diese Strings nur Zahlen enthalten, wird Pydantic sie konvertieren und validieren. + + Und das `dict` welches Sie als `weights` erhalten, wird `int`-Schlüssel und `float`-Werte haben. + +## Zusammenfassung + +Mit **FastAPI** haben Sie die maximale Flexibilität von Pydantic-Modellen, während Ihr Code einfach, kurz und elegant bleibt. + +Aber mit all den Vorzügen: + +* Editor-Unterstützung (Codevervollständigung überall) +* Datenkonvertierung (auch bekannt als Parsen, Serialisierung) +* Datenvalidierung +* Schema-Dokumentation +* Automatische Dokumentation diff --git a/docs/de/docs/tutorial/body-updates.md b/docs/de/docs/tutorial/body-updates.md new file mode 100644 index 0000000000000..2b3716d6f1b62 --- /dev/null +++ b/docs/de/docs/tutorial/body-updates.md @@ -0,0 +1,165 @@ +# Body – Aktualisierungen + +## Ersetzendes Aktualisieren mit `PUT` + +Um einen Artikel zu aktualisieren, können Sie die HTTP `PUT` Operation verwenden. + +Sie können den `jsonable_encoder` verwenden, um die empfangenen Daten in etwas zu konvertieren, das als JSON gespeichert werden kann (in z. B. einer NoSQL-Datenbank). Zum Beispiel, um ein `datetime` in einen `str` zu konvertieren. + +=== "Python 3.10+" + + ```Python hl_lines="28-33" + {!> ../../../docs_src/body_updates/tutorial001_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="30-35" + {!> ../../../docs_src/body_updates/tutorial001_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="30-35" + {!> ../../../docs_src/body_updates/tutorial001.py!} + ``` + +`PUT` wird verwendet, um Daten zu empfangen, die die existierenden Daten ersetzen sollen. + +### Warnung bezüglich des Ersetzens + +Das bedeutet, dass, wenn Sie den Artikel `bar` aktualisieren wollen, mittels `PUT` und folgendem Body: + +```Python +{ + "name": "Barz", + "price": 3, + "description": None, +} +``` + +das Eingabemodell nun den Defaultwert `"tax": 10.5` hat, weil Sie das bereits gespeicherte Attribut `"tax": 20.2` nicht mit übergeben haben. + +Die Daten werden darum mit einem „neuen“ `tax`-Wert von `10.5` abgespeichert. + +## Teilweises Ersetzen mit `PATCH` + +Sie können auch die HTTP `PATCH` Operation verwenden, um Daten *teilweise* zu ersetzen. + +Das bedeutet, sie senden nur die Daten, die Sie aktualisieren wollen, der Rest bleibt unverändert. + +!!! note "Hinweis" + `PATCH` wird seltener verwendet und ist weniger bekannt als `PUT`. + + Und viele Teams verwenden ausschließlich `PUT`, selbst für nur Teil-Aktualisierungen. + + Es steht Ihnen **frei**, das zu verwenden, was Sie möchten, **FastAPI** legt Ihnen keine Einschränkungen auf. + + Aber dieser Leitfaden zeigt Ihnen mehr oder weniger, wie die beiden normalerweise verwendet werden. + +### Pydantics `exclude_unset`-Parameter verwenden + +Wenn Sie Teil-Aktualisierungen entgegennehmen, ist der `exclude_unset`-Parameter in der `.model_dump()`-Methode von Pydantic-Modellen sehr nützlich. + +Wie in `item.model_dump(exclude_unset=True)`. + +!!! info + In Pydantic v1 hieß diese Methode `.dict()`, in Pydantic v2 wurde sie deprecated (aber immer noch unterstützt) und in `.model_dump()` umbenannt. + + Die Beispiele hier verwenden `.dict()` für die Kompatibilität mit Pydantic v1, Sie sollten jedoch stattdessen `.model_dump()` verwenden, wenn Sie Pydantic v2 verwenden können. + +Das wird ein `dict` erstellen, mit nur den Daten, die gesetzt wurden als das `item`-Modell erstellt wurde, Defaultwerte ausgeschlossen. + +Sie können das verwenden, um ein `dict` zu erstellen, das nur die (im Request) gesendeten Daten enthält, ohne Defaultwerte: + +=== "Python 3.10+" + + ```Python hl_lines="32" + {!> ../../../docs_src/body_updates/tutorial002_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="34" + {!> ../../../docs_src/body_updates/tutorial002_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="34" + {!> ../../../docs_src/body_updates/tutorial002.py!} + ``` + +### Pydantics `update`-Parameter verwenden + +Jetzt können Sie eine Kopie des existierenden Modells mittels `.model_copy()` erstellen, wobei Sie dem `update`-Parameter ein `dict` mit den zu ändernden Daten übergeben. + +!!! info + In Pydantic v1 hieß diese Methode `.copy()`, in Pydantic v2 wurde sie deprecated (aber immer noch unterstützt) und in `.model_copy()` umbenannt. + + Die Beispiele hier verwenden `.copy()` für die Kompatibilität mit Pydantic v1, Sie sollten jedoch stattdessen `.model_copy()` verwenden, wenn Sie Pydantic v2 verwenden können. + +Wie in `stored_item_model.model_copy(update=update_data)`: + +=== "Python 3.10+" + + ```Python hl_lines="33" + {!> ../../../docs_src/body_updates/tutorial002_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="35" + {!> ../../../docs_src/body_updates/tutorial002_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="35" + {!> ../../../docs_src/body_updates/tutorial002.py!} + ``` + +### Rekapitulation zum teilweisen Ersetzen + +Zusammengefasst, um Teil-Ersetzungen vorzunehmen: + +* (Optional) verwenden Sie `PATCH` statt `PUT`. +* Lesen Sie die bereits gespeicherten Daten aus. +* Fügen Sie diese in ein Pydantic-Modell ein. +* Erzeugen Sie aus dem empfangenen Modell ein `dict` ohne Defaultwerte (mittels `exclude_unset`). + * So ersetzen Sie nur die tatsächlich vom Benutzer gesetzten Werte, statt dass bereits gespeicherte Werte mit Defaultwerten des Modells überschrieben werden. +* Erzeugen Sie eine Kopie ihres gespeicherten Modells, wobei Sie die Attribute mit den empfangenen Teil-Ersetzungen aktualisieren (mittels des `update`-Parameters). +* Konvertieren Sie das kopierte Modell zu etwas, das in ihrer Datenbank gespeichert werden kann (indem Sie beispielsweise `jsonable_encoder` verwenden). + * Das ist vergleichbar dazu, die `.model_dump()`-Methode des Modells erneut aufzurufen, aber es wird sicherstellen, dass die Werte zu Daten konvertiert werden, die ihrerseits zu JSON konvertiert werden können, zum Beispiel `datetime` zu `str`. +* Speichern Sie die Daten in Ihrer Datenbank. +* Geben Sie das aktualisierte Modell zurück. + +=== "Python 3.10+" + + ```Python hl_lines="28-35" + {!> ../../../docs_src/body_updates/tutorial002_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="30-37" + {!> ../../../docs_src/body_updates/tutorial002_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="30-37" + {!> ../../../docs_src/body_updates/tutorial002.py!} + ``` + +!!! tip "Tipp" + Sie können tatsächlich die gleiche Technik mit einer HTTP `PUT` Operation verwenden. + + Aber dieses Beispiel verwendet `PATCH`, da dieses für solche Anwendungsfälle geschaffen wurde. + +!!! note "Hinweis" + Beachten Sie, dass das hereinkommende Modell immer noch validiert wird. + + Wenn Sie also Teil-Aktualisierungen empfangen wollen, die alle Attribute auslassen können, müssen Sie ein Modell haben, dessen Attribute alle als optional gekennzeichnet sind (mit Defaultwerten oder `None`). + + Um zu unterscheiden zwischen Modellen für **Aktualisierungen**, mit lauter optionalen Werten, und solchen für die **Erzeugung**, mit benötigten Werten, können Sie die Techniken verwenden, die in [Extramodelle](extra-models.md){.internal-link target=_blank} beschrieben wurden. diff --git a/docs/de/docs/tutorial/body.md b/docs/de/docs/tutorial/body.md new file mode 100644 index 0000000000000..6611cb51a8535 --- /dev/null +++ b/docs/de/docs/tutorial/body.md @@ -0,0 +1,213 @@ +# Requestbody + +Wenn Sie Daten von einem Client (sagen wir, einem Browser) zu Ihrer API senden, dann senden Sie diese als einen **Requestbody** (Deutsch: Anfragekörper). + +Ein **Request**body sind Daten, die vom Client zu Ihrer API gesendet werden. Ein **Response**body (Deutsch: Antwortkörper) sind Daten, die Ihre API zum Client sendet. + +Ihre API sendet fast immer einen **Response**body. Aber Clients senden nicht unbedingt immer **Request**bodys (sondern nur Metadaten). + +Um einen **Request**body zu deklarieren, verwenden Sie Pydantic-Modelle mit allen deren Fähigkeiten und Vorzügen. + +!!! info + Um Daten zu versenden, sollten Sie eines von: `POST` (meistverwendet), `PUT`, `DELETE` oder `PATCH` verwenden. + + Senden Sie einen Body mit einem `GET`-Request, dann führt das laut Spezifikation zu undefiniertem Verhalten. Trotzdem wird es von FastAPI unterstützt, für sehr komplexe/extreme Anwendungsfälle. + + Da aber davon abgeraten wird, zeigt die interaktive Dokumentation mit Swagger-Benutzeroberfläche die Dokumentation für den Body auch nicht an, wenn `GET` verwendet wird. Dazwischengeschaltete Proxys unterstützen es möglicherweise auch nicht. + +## Importieren Sie Pydantics `BaseModel` + +Zuerst müssen Sie `BaseModel` von `pydantic` importieren: + +=== "Python 3.10+" + + ```Python hl_lines="2" + {!> ../../../docs_src/body/tutorial001_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="4" + {!> ../../../docs_src/body/tutorial001.py!} + ``` + +## Erstellen Sie Ihr Datenmodell + +Dann deklarieren Sie Ihr Datenmodell als eine Klasse, die von `BaseModel` erbt. + +Verwenden Sie Standard-Python-Typen für die Klassenattribute: + +=== "Python 3.10+" + + ```Python hl_lines="5-9" + {!> ../../../docs_src/body/tutorial001_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="7-11" + {!> ../../../docs_src/body/tutorial001.py!} + ``` + +Wie auch bei Query-Parametern gilt, wenn ein Modellattribut einen Defaultwert hat, ist das Attribut nicht erforderlich. Ansonsten ist es erforderlich. Verwenden Sie `None`, um es als optional zu kennzeichnen. + +Zum Beispiel deklariert das obige Modell ein JSON "`object`" (oder Python-`dict`) wie dieses: + +```JSON +{ + "name": "Foo", + "description": "An optional description", + "price": 45.2, + "tax": 3.5 +} +``` + +Da `description` und `tax` optional sind (mit `None` als Defaultwert), wäre folgendes JSON "`object`" auch gültig: + +```JSON +{ + "name": "Foo", + "price": 45.2 +} +``` + +## Deklarieren Sie es als Parameter + +Um es zu Ihrer *Pfadoperation* hinzuzufügen, deklarieren Sie es auf die gleiche Weise, wie Sie Pfad- und Query-Parameter deklariert haben: + +=== "Python 3.10+" + + ```Python hl_lines="16" + {!> ../../../docs_src/body/tutorial001_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="18" + {!> ../../../docs_src/body/tutorial001.py!} + ``` + +... und deklarieren Sie seinen Typ als das Modell, welches Sie erstellt haben, `Item`. + +## Resultate + +Mit nur dieser Python-Typdeklaration, wird **FastAPI**: + +* Den Requestbody als JSON lesen. +* Die entsprechenden Typen konvertieren (falls nötig). +* Diese Daten validieren. + * Wenn die Daten ungültig sind, einen klar lesbaren Fehler zurückgeben, der anzeigt, wo und was die inkorrekten Daten waren. +* Ihnen die erhaltenen Daten im Parameter `item` übergeben. + * Da Sie diesen in der Funktion als vom Typ `Item` deklariert haben, erhalten Sie die ganze Editor-Unterstützung (Autovervollständigung, usw.) für alle Attribute und deren Typen. +* Eine JSON Schema Definition für Ihr Modell generieren, welche Sie überall sonst verwenden können, wenn es für Ihr Projekt Sinn macht. +* Diese Schemas werden Teil des generierten OpenAPI-Schemas und werden von den UIs der automatischen Dokumentation verwendet. + +## Automatische Dokumentation + +Die JSON-Schemas Ihrer Modelle werden Teil ihrer OpenAPI-generierten Schemas und werden in der interaktiven API Dokumentation angezeigt: + + + +Und werden auch verwendet in der API-Dokumentation innerhalb jeder *Pfadoperation*, welche sie braucht: + + + +## Editor Unterstützung + +In Ihrem Editor, innerhalb Ihrer Funktion, erhalten Sie Typhinweise und Code-Vervollständigung überall (was nicht der Fall wäre, wenn Sie ein `dict` anstelle eines Pydantic Modells erhalten hätten): + + + +Sie bekommen auch Fehler-Meldungen für inkorrekte Typoperationen: + + + +Das ist nicht zufällig so, das ganze Framework wurde um dieses Design herum aufgebaut. + +Und es wurde in der Designphase gründlich getestet, vor der Implementierung, um sicherzustellen, dass es mit jedem Editor funktioniert. + +Es gab sogar ein paar Änderungen an Pydantic selbst, um das zu unterstützen. + +Die vorherigen Screenshots zeigten Visual Studio Code. + +Aber Sie bekommen die gleiche Editor-Unterstützung in PyCharm und in den meisten anderen Python-Editoren: + + + +!!! tip "Tipp" + Wenn Sie PyCharm als Ihren Editor verwenden, probieren Sie das Pydantic PyCharm Plugin aus. + + Es verbessert die Editor-Unterstützung für Pydantic-Modelle, mit: + + * Code-Vervollständigung + * Typüberprüfungen + * Refaktorisierung + * Suchen + * Inspektionen + +## Das Modell verwenden + +Innerhalb der Funktion können Sie alle Attribute des Modells direkt verwenden: + +=== "Python 3.10+" + + ```Python hl_lines="19" + {!> ../../../docs_src/body/tutorial002_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="21" + {!> ../../../docs_src/body/tutorial002.py!} + ``` + +## Requestbody- + Pfad-Parameter + +Sie können Pfad- und Requestbody-Parameter gleichzeitig deklarieren. + +**FastAPI** erkennt, dass Funktionsparameter, die mit Pfad-Parametern übereinstimmen, **vom Pfad genommen** werden sollen, und dass Funktionsparameter, welche Pydantic-Modelle sind, **vom Requestbody genommen** werden sollen. + +=== "Python 3.10+" + + ```Python hl_lines="15-16" + {!> ../../../docs_src/body/tutorial003_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="17-18" + {!> ../../../docs_src/body/tutorial003.py!} + ``` + +## Requestbody- + Pfad- + Query-Parameter + +Sie können auch zur gleichen Zeit **Body-**, **Pfad-** und **Query-Parameter** deklarieren. + +**FastAPI** wird jeden Parameter korrekt erkennen und die Daten vom richtigen Ort holen. + +=== "Python 3.10+" + + ```Python hl_lines="16" + {!> ../../../docs_src/body/tutorial004_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="18" + {!> ../../../docs_src/body/tutorial004.py!} + ``` + +Die Funktionsparameter werden wie folgt erkannt: + +* Wenn der Parameter auch im **Pfad** deklariert wurde, wird er als Pfad-Parameter interpretiert. +* Wenn der Parameter ein **einfacher Typ** ist (wie `int`, `float`, `str`, `bool`, usw.), wird er als **Query**-Parameter interpretiert. +* Wenn der Parameter vom Typ eines **Pydantic-Modells** ist, wird er als Request**body** interpretiert. + +!!! note "Hinweis" + FastAPI weiß, dass der Wert von `q` nicht erforderlich ist, wegen des definierten Defaultwertes `= None` + + Das `Union` in `Union[str, None]` wird von FastAPI nicht verwendet, aber es erlaubt Ihrem Editor, Sie besser zu unterstützen und Fehler zu erkennen. + +## Ohne Pydantic + +Wenn Sie keine Pydantic-Modelle verwenden wollen, können Sie auch **Body**-Parameter nehmen. Siehe die Dokumentation unter [Body – Mehrere Parameter: Einfache Werte im Body](body-multiple-params.md#einzelne-werte-im-body){.internal-link target=\_blank}. diff --git a/docs/de/docs/tutorial/cookie-params.md b/docs/de/docs/tutorial/cookie-params.md new file mode 100644 index 0000000000000..c95e28c7dc6d8 --- /dev/null +++ b/docs/de/docs/tutorial/cookie-params.md @@ -0,0 +1,97 @@ +# Cookie-Parameter + +So wie `Query`- und `Path`-Parameter können Sie auch Cookie-Parameter definieren. + +## `Cookie` importieren + +Importieren Sie zuerst `Cookie`: + +=== "Python 3.10+" + + ```Python hl_lines="3" + {!> ../../../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.8+" + + ```Python hl_lines="3" + {!> ../../../docs_src/cookie_params/tutorial001_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="1" + {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="3" + {!> ../../../docs_src/cookie_params/tutorial001.py!} + ``` + +## `Cookie`-Parameter deklarieren + +Dann deklarieren Sie Ihre Cookie-Parameter, auf die gleiche Weise, wie Sie auch `Path`- und `Query`-Parameter deklarieren. + +Der erste Wert ist der Typ. Sie können `Cookie` die gehabten Extra Validierungs- und Beschreibungsparameter hinzufügen. Danach können Sie einen Defaultwert vergeben: + +=== "Python 3.10+" + + ```Python hl_lines="9" + {!> ../../../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.8+" + + ```Python hl_lines="10" + {!> ../../../docs_src/cookie_params/tutorial001_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="7" + {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="9" + {!> ../../../docs_src/cookie_params/tutorial001.py!} + ``` + +!!! note "Technische Details" + `Cookie` ist eine Schwesterklasse von `Path` und `Query`. Sie erbt von derselben gemeinsamen `Param`-Elternklasse. + + Aber erinnern Sie sich, dass, wenn Sie `Query`, `Path`, `Cookie` und andere von `fastapi` importieren, diese tatsächlich Funktionen sind, welche spezielle Klassen zurückgeben. + +!!! info + Um Cookies zu deklarieren, müssen Sie `Cookie` verwenden, da diese Parameter sonst als Query-Parameter interpretiert werden würden. + +## Zusammenfassung + +Deklarieren Sie Cookies mittels `Cookie`, auf die gleiche Weise wie bei `Query` und `Path`. diff --git a/docs/de/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/de/docs/tutorial/dependencies/classes-as-dependencies.md new file mode 100644 index 0000000000000..9faaed715c4bb --- /dev/null +++ b/docs/de/docs/tutorial/dependencies/classes-as-dependencies.md @@ -0,0 +1,481 @@ +# Klassen als Abhängigkeiten + +Bevor wir tiefer in das **Dependency Injection** System eintauchen, lassen Sie uns das vorherige Beispiel verbessern. + +## Ein `dict` aus dem vorherigen Beispiel + +Im vorherigen Beispiel haben wir ein `dict` von unserer Abhängigkeit („Dependable“) zurückgegeben: + +=== "Python 3.10+" + + ```Python hl_lines="9" + {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="11" + {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="12" + {!> ../../../docs_src/dependencies/tutorial001_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="7" + {!> ../../../docs_src/dependencies/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="11" + {!> ../../../docs_src/dependencies/tutorial001.py!} + ``` + +Aber dann haben wir ein `dict` im Parameter `commons` der *Pfadoperation-Funktion*. + +Und wir wissen, dass Editoren nicht viel Unterstützung (wie etwa Code-Vervollständigung) für `dict`s bieten können, weil sie ihre Schlüssel- und Werttypen nicht kennen. + +Das können wir besser machen ... + +## Was macht eine Abhängigkeit aus + +Bisher haben Sie Abhängigkeiten gesehen, die als Funktionen deklariert wurden. + +Das ist jedoch nicht die einzige Möglichkeit, Abhängigkeiten zu deklarieren (obwohl es wahrscheinlich die gebräuchlichste ist). + +Der springende Punkt ist, dass eine Abhängigkeit aufrufbar („callable“) sein sollte. + +Ein „**Callable**“ in Python ist etwas, das wie eine Funktion aufgerufen werden kann („to call“). + +Wenn Sie also ein Objekt `something` haben (das möglicherweise _keine_ Funktion ist) und Sie es wie folgt aufrufen (ausführen) können: + +```Python +something() +``` + +oder + +```Python +something(some_argument, some_keyword_argument="foo") +``` + +dann ist das ein „Callable“ (ein „Aufrufbares“). + +## Klassen als Abhängigkeiten + +Möglicherweise stellen Sie fest, dass Sie zum Erstellen einer Instanz einer Python-Klasse die gleiche Syntax verwenden. + +Zum Beispiel: + +```Python +class Cat: + def __init__(self, name: str): + self.name = name + + +fluffy = Cat(name="Mr Fluffy") +``` + +In diesem Fall ist `fluffy` eine Instanz der Klasse `Cat`. + +Und um `fluffy` zu erzeugen, rufen Sie `Cat` auf. + +Eine Python-Klasse ist also auch ein **Callable**. + +Darum können Sie in **FastAPI** auch eine Python-Klasse als Abhängigkeit verwenden. + +Was FastAPI tatsächlich prüft, ist, ob es sich um ein „Callable“ (Funktion, Klasse oder irgendetwas anderes) handelt und ob die Parameter definiert sind. + +Wenn Sie **FastAPI** ein „Callable“ als Abhängigkeit übergeben, analysiert es die Parameter dieses „Callables“ und verarbeitet sie auf die gleiche Weise wie die Parameter einer *Pfadoperation-Funktion*. Einschließlich Unterabhängigkeiten. + +Das gilt auch für Callables ohne Parameter. So wie es auch für *Pfadoperation-Funktionen* ohne Parameter gilt. + +Dann können wir das „Dependable“ `common_parameters` der Abhängigkeit von oben in die Klasse `CommonQueryParams` ändern: + +=== "Python 3.10+" + + ```Python hl_lines="11-15" + {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="11-15" + {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="12-16" + {!> ../../../docs_src/dependencies/tutorial002_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="9-13" + {!> ../../../docs_src/dependencies/tutorial002_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="11-15" + {!> ../../../docs_src/dependencies/tutorial002.py!} + ``` + +Achten Sie auf die Methode `__init__`, die zum Erstellen der Instanz der Klasse verwendet wird: + +=== "Python 3.10+" + + ```Python hl_lines="12" + {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="12" + {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="13" + {!> ../../../docs_src/dependencies/tutorial002_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="10" + {!> ../../../docs_src/dependencies/tutorial002_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="12" + {!> ../../../docs_src/dependencies/tutorial002.py!} + ``` + +... sie hat die gleichen Parameter wie unsere vorherige `common_parameters`: + +=== "Python 3.10+" + + ```Python hl_lines="8" + {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="9" + {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="10" + {!> ../../../docs_src/dependencies/tutorial001_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="6" + {!> ../../../docs_src/dependencies/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="9" + {!> ../../../docs_src/dependencies/tutorial001.py!} + ``` + +Diese Parameter werden von **FastAPI** verwendet, um die Abhängigkeit „aufzulösen“. + +In beiden Fällen wird sie haben: + +* Einen optionalen `q`-Query-Parameter, der ein `str` ist. +* Einen `skip`-Query-Parameter, der ein `int` ist, mit einem Defaultwert `0`. +* Einen `limit`-Query-Parameter, der ein `int` ist, mit einem Defaultwert `100`. + +In beiden Fällen werden die Daten konvertiert, validiert, im OpenAPI-Schema dokumentiert, usw. + +## Verwendung + +Jetzt können Sie Ihre Abhängigkeit mithilfe dieser Klasse deklarieren. + +=== "Python 3.10+" + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="20" + {!> ../../../docs_src/dependencies/tutorial002_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="17" + {!> ../../../docs_src/dependencies/tutorial002_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial002.py!} + ``` + +**FastAPI** ruft die Klasse `CommonQueryParams` auf. Dadurch wird eine „Instanz“ dieser Klasse erstellt und die Instanz wird als Parameter `commons` an Ihre Funktion überreicht. + +## Typannotation vs. `Depends` + +Beachten Sie, wie wir `CommonQueryParams` im obigen Code zweimal schreiben: + +=== "Python 3.8+" + + ```Python + commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python + commons: CommonQueryParams = Depends(CommonQueryParams) + ``` + +Das letzte `CommonQueryParams`, in: + +```Python +... Depends(CommonQueryParams) +``` + +... ist das, was **FastAPI** tatsächlich verwendet, um die Abhängigkeit zu ermitteln. + +Aus diesem extrahiert FastAPI die deklarierten Parameter, und dieses ist es, was FastAPI auch aufruft. + +--- + +In diesem Fall hat das erste `CommonQueryParams` in: + +=== "Python 3.8+" + + ```Python + commons: Annotated[CommonQueryParams, ... + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python + commons: CommonQueryParams ... + ``` + +... keine besondere Bedeutung für **FastAPI**. FastAPI verwendet es nicht für die Datenkonvertierung, -validierung, usw. (da es dafür `Depends(CommonQueryParams)` verwendet). + +Sie könnten tatsächlich einfach schreiben: + +=== "Python 3.8+" + + ```Python + commons: Annotated[Any, Depends(CommonQueryParams)] + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python + commons = Depends(CommonQueryParams) + ``` + +... wie in: + +=== "Python 3.10+" + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial003_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial003_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="20" + {!> ../../../docs_src/dependencies/tutorial003_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="17" + {!> ../../../docs_src/dependencies/tutorial003_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial003.py!} + ``` + +Es wird jedoch empfohlen, den Typ zu deklarieren, da Ihr Editor so weiß, was als Parameter `commons` übergeben wird, und Ihnen dann bei der Codevervollständigung, Typprüfungen, usw. helfen kann: + + + +## Abkürzung + +Aber Sie sehen, dass wir hier etwas Codeduplizierung haben, indem wir `CommonQueryParams` zweimal schreiben: + +=== "Python 3.8+" + + ```Python + commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python + commons: CommonQueryParams = Depends(CommonQueryParams) + ``` + +**FastAPI** bietet eine Abkürzung für diese Fälle, wo die Abhängigkeit *speziell* eine Klasse ist, welche **FastAPI** aufruft, um eine Instanz der Klasse selbst zu erstellen. + +In diesem speziellen Fall können Sie Folgendes tun: + +Anstatt zu schreiben: + +=== "Python 3.8+" + + ```Python + commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python + commons: CommonQueryParams = Depends(CommonQueryParams) + ``` + +... schreiben Sie: + +=== "Python 3.8+" + + ```Python + commons: Annotated[CommonQueryParams, Depends()] + ``` + +=== "Python 3.8 nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python + commons: CommonQueryParams = Depends() + ``` + +Sie deklarieren die Abhängigkeit als Typ des Parameters und verwenden `Depends()` ohne Parameter, anstatt die vollständige Klasse *erneut* in `Depends(CommonQueryParams)` schreiben zu müssen. + +Dasselbe Beispiel würde dann so aussehen: + +=== "Python 3.10+" + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial004_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial004_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="20" + {!> ../../../docs_src/dependencies/tutorial004_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="17" + {!> ../../../docs_src/dependencies/tutorial004_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial004.py!} + ``` + +... und **FastAPI** wird wissen, was zu tun ist. + +!!! tip "Tipp" + Wenn Sie das eher verwirrt, als Ihnen zu helfen, ignorieren Sie es, Sie *brauchen* es nicht. + + Es ist nur eine Abkürzung. Es geht **FastAPI** darum, Ihnen dabei zu helfen, Codeverdoppelung zu minimieren. diff --git a/docs/de/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/de/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md new file mode 100644 index 0000000000000..2919aebafe84e --- /dev/null +++ b/docs/de/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -0,0 +1,139 @@ +# Abhängigkeiten in Pfadoperation-Dekoratoren + +Manchmal benötigen Sie den Rückgabewert einer Abhängigkeit innerhalb Ihrer *Pfadoperation-Funktion* nicht wirklich. + +Oder die Abhängigkeit gibt keinen Wert zurück. + +Aber Sie müssen Sie trotzdem ausführen/auflösen. + +In diesen Fällen können Sie, anstatt einen Parameter der *Pfadoperation-Funktion* mit `Depends` zu deklarieren, eine `list`e von `dependencies` zum *Pfadoperation-Dekorator* hinzufügen. + +## `dependencies` zum *Pfadoperation-Dekorator* hinzufügen + +Der *Pfadoperation-Dekorator* erhält ein optionales Argument `dependencies`. + +Es sollte eine `list`e von `Depends()` sein: + +=== "Python 3.9+" + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="18" + {!> ../../../docs_src/dependencies/tutorial006_an.py!} + ``` + +=== "Python 3.8 nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="17" + {!> ../../../docs_src/dependencies/tutorial006.py!} + ``` + +Diese Abhängigkeiten werden auf die gleiche Weise wie normale Abhängigkeiten ausgeführt/aufgelöst. Aber ihr Wert (falls sie einen zurückgeben) wird nicht an Ihre *Pfadoperation-Funktion* übergeben. + +!!! tip "Tipp" + Einige Editoren prüfen, ob Funktionsparameter nicht verwendet werden, und zeigen das als Fehler an. + + Wenn Sie `dependencies` im *Pfadoperation-Dekorator* verwenden, stellen Sie sicher, dass sie ausgeführt werden, während gleichzeitig Ihr Editor/Ihre Tools keine Fehlermeldungen ausgeben. + + Damit wird auch vermieden, neue Entwickler möglicherweise zu verwirren, die einen nicht verwendeten Parameter in Ihrem Code sehen und ihn für unnötig halten könnten. + +!!! info + In diesem Beispiel verwenden wir zwei erfundene benutzerdefinierte Header `X-Key` und `X-Token`. + + Aber in realen Fällen würden Sie bei der Implementierung von Sicherheit mehr Vorteile durch die Verwendung der integrierten [Sicherheits-Werkzeuge (siehe nächstes Kapitel)](../security/index.md){.internal-link target=_blank} erzielen. + +## Abhängigkeitsfehler und -Rückgabewerte + +Sie können dieselben Abhängigkeits-*Funktionen* verwenden, die Sie normalerweise verwenden. + +### Abhängigkeitsanforderungen + +Sie können Anforderungen für einen Request (wie Header) oder andere Unterabhängigkeiten deklarieren: + +=== "Python 3.9+" + + ```Python hl_lines="8 13" + {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="7 12" + {!> ../../../docs_src/dependencies/tutorial006_an.py!} + ``` + +=== "Python 3.8 nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="6 11" + {!> ../../../docs_src/dependencies/tutorial006.py!} + ``` + +### Exceptions auslösen + +Die Abhängigkeiten können Exceptions `raise`n, genau wie normale Abhängigkeiten: + +=== "Python 3.9+" + + ```Python hl_lines="10 15" + {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9 14" + {!> ../../../docs_src/dependencies/tutorial006_an.py!} + ``` + +=== "Python 3.8 nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="8 13" + {!> ../../../docs_src/dependencies/tutorial006.py!} + ``` + +### Rückgabewerte + +Und sie können Werte zurückgeben oder nicht, die Werte werden nicht verwendet. + +Sie können also eine normale Abhängigkeit (die einen Wert zurückgibt), die Sie bereits an anderer Stelle verwenden, wiederverwenden, und auch wenn der Wert nicht verwendet wird, wird die Abhängigkeit ausgeführt: + +=== "Python 3.9+" + + ```Python hl_lines="11 16" + {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="10 15" + {!> ../../../docs_src/dependencies/tutorial006_an.py!} + ``` + +=== "Python 3.8 nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="9 14" + {!> ../../../docs_src/dependencies/tutorial006.py!} + ``` + +## Abhängigkeiten für eine Gruppe von *Pfadoperationen* + +Wenn Sie später lesen, wie Sie größere Anwendungen strukturieren ([Größere Anwendungen – Mehrere Dateien](../../tutorial/bigger-applications.md){.internal-link target=_blank}), möglicherweise mit mehreren Dateien, lernen Sie, wie Sie einen einzelnen `dependencies`-Parameter für eine Gruppe von *Pfadoperationen* deklarieren. + +## Globale Abhängigkeiten + +Als Nächstes werden wir sehen, wie man Abhängigkeiten zur gesamten `FastAPI`-Anwendung hinzufügt, sodass sie für jede *Pfadoperation* gelten. diff --git a/docs/de/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/de/docs/tutorial/dependencies/dependencies-with-yield.md new file mode 100644 index 0000000000000..e29e871565571 --- /dev/null +++ b/docs/de/docs/tutorial/dependencies/dependencies-with-yield.md @@ -0,0 +1,284 @@ +# Abhängigkeiten mit yield + +FastAPI unterstützt Abhängigkeiten, die nach Abschluss einige zusätzliche Schritte ausführen. + +Verwenden Sie dazu `yield` statt `return` und schreiben Sie die zusätzlichen Schritte / den zusätzlichen Code danach. + +!!! tip "Tipp" + Stellen Sie sicher, dass Sie `yield` nur einmal pro Abhängigkeit verwenden. + +!!! note "Technische Details" + Jede Funktion, die dekoriert werden kann mit: + + * `@contextlib.contextmanager` oder + * `@contextlib.asynccontextmanager` + + kann auch als gültige **FastAPI**-Abhängigkeit verwendet werden. + + Tatsächlich verwendet FastAPI diese beiden Dekoratoren intern. + +## Eine Datenbank-Abhängigkeit mit `yield`. + +Sie könnten damit beispielsweise eine Datenbanksession erstellen und diese nach Abschluss schließen. + +Nur der Code vor und einschließlich der `yield`-Anweisung wird ausgeführt, bevor eine Response erzeugt wird: + +```Python hl_lines="2-4" +{!../../../docs_src/dependencies/tutorial007.py!} +``` + +Der ge`yield`ete Wert ist das, was in *Pfadoperationen* und andere Abhängigkeiten eingefügt wird: + +```Python hl_lines="4" +{!../../../docs_src/dependencies/tutorial007.py!} +``` + +Der auf die `yield`-Anweisung folgende Code wird ausgeführt, nachdem die Response gesendet wurde: + +```Python hl_lines="5-6" +{!../../../docs_src/dependencies/tutorial007.py!} +``` + +!!! tip "Tipp" + Sie können `async`hrone oder reguläre Funktionen verwenden. + + **FastAPI** wird bei jeder das Richtige tun, so wie auch bei normalen Abhängigkeiten. + +## Eine Abhängigkeit mit `yield` und `try`. + +Wenn Sie einen `try`-Block in einer Abhängigkeit mit `yield` verwenden, empfangen Sie alle Exceptions, die bei Verwendung der Abhängigkeit geworfen wurden. + +Wenn beispielsweise ein Code irgendwann in der Mitte, in einer anderen Abhängigkeit oder in einer *Pfadoperation*, ein „Rollback“ einer Datenbanktransaktion oder einen anderen Fehler verursacht, empfangen Sie die resultierende Exception in Ihrer Abhängigkeit. + +Sie können also mit `except SomeException` diese bestimmte Exception innerhalb der Abhängigkeit handhaben. + +Auf die gleiche Weise können Sie `finally` verwenden, um sicherzustellen, dass die Exit-Schritte ausgeführt werden, unabhängig davon, ob eine Exception geworfen wurde oder nicht. + +```Python hl_lines="3 5" +{!../../../docs_src/dependencies/tutorial007.py!} +``` + +## Unterabhängigkeiten mit `yield`. + +Sie können Unterabhängigkeiten und „Bäume“ von Unterabhängigkeiten beliebiger Größe und Form haben, und einige oder alle davon können `yield` verwenden. + +**FastAPI** stellt sicher, dass der „Exit-Code“ in jeder Abhängigkeit mit `yield` in der richtigen Reihenfolge ausgeführt wird. + +Beispielsweise kann `dependency_c` von `dependency_b` und `dependency_b` von `dependency_a` abhängen: + +=== "Python 3.9+" + + ```Python hl_lines="6 14 22" + {!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="5 13 21" + {!> ../../../docs_src/dependencies/tutorial008_an.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="4 12 20" + {!> ../../../docs_src/dependencies/tutorial008.py!} + ``` + +Und alle können `yield` verwenden. + +In diesem Fall benötigt `dependency_c` zum Ausführen seines Exit-Codes, dass der Wert von `dependency_b` (hier `dep_b` genannt) verfügbar ist. + +Und wiederum benötigt `dependency_b` den Wert von `dependency_a` (hier `dep_a` genannt) für seinen Exit-Code. + +=== "Python 3.9+" + + ```Python hl_lines="18-19 26-27" + {!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="17-18 25-26" + {!> ../../../docs_src/dependencies/tutorial008_an.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="16-17 24-25" + {!> ../../../docs_src/dependencies/tutorial008.py!} + ``` + +Auf die gleiche Weise könnten Sie einige Abhängigkeiten mit `yield` und einige andere Abhängigkeiten mit `return` haben, und alle können beliebig voneinander abhängen. + +Und Sie könnten eine einzelne Abhängigkeit haben, die auf mehreren ge`yield`eten Abhängigkeiten basiert, usw. + +Sie können beliebige Kombinationen von Abhängigkeiten haben. + +**FastAPI** stellt sicher, dass alles in der richtigen Reihenfolge ausgeführt wird. + +!!! note "Technische Details" + Dieses funktioniert dank Pythons Kontextmanager. + + **FastAPI** verwendet sie intern, um das zu erreichen. + +## Abhängigkeiten mit `yield` und `HTTPException`. + +Sie haben gesehen, dass Ihre Abhängigkeiten `yield` verwenden können und `try`-Blöcke haben können, die Exceptions abfangen. + +Auf die gleiche Weise könnten Sie im Exit-Code nach dem `yield` eine `HTTPException` oder ähnliches auslösen. + +!!! tip "Tipp" + + Dies ist eine etwas fortgeschrittene Technik, die Sie in den meisten Fällen nicht wirklich benötigen, da Sie Exceptions (einschließlich `HTTPException`) innerhalb des restlichen Anwendungscodes auslösen können, beispielsweise in der *Pfadoperation-Funktion*. + + Aber es ist für Sie da, wenn Sie es brauchen. 🤓 + +=== "Python 3.9+" + + ```Python hl_lines="18-22 31" + {!> ../../../docs_src/dependencies/tutorial008b_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="17-21 30" + {!> ../../../docs_src/dependencies/tutorial008b_an.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="16-20 29" + {!> ../../../docs_src/dependencies/tutorial008b.py!} + ``` + +Eine Alternative zum Abfangen von Exceptions (und möglicherweise auch zum Auslösen einer weiteren `HTTPException`) besteht darin, einen [benutzerdefinierten Exceptionhandler](../handling-errors.md#benutzerdefinierte-exceptionhandler-definieren){.internal-link target=_blank} zu erstellen. + +## Ausführung von Abhängigkeiten mit `yield` + +Die Ausführungsreihenfolge ähnelt mehr oder weniger dem folgenden Diagramm. Die Zeit verläuft von oben nach unten. Und jede Spalte ist einer der interagierenden oder Code-ausführenden Teilnehmer. + +```mermaid +sequenceDiagram + +participant client as Client +participant handler as Exceptionhandler +participant dep as Abhängigkeit mit yield +participant operation as Pfadoperation +participant tasks as Hintergrundtasks + + Note over client,operation: Kann Exceptions auslösen, inklusive HTTPException + client ->> dep: Startet den Request + Note over dep: Führt den Code bis zum yield aus + opt Löst Exception aus + dep -->> handler: Löst Exception aus + handler -->> client: HTTP-Error-Response + end + dep ->> operation: Führt Abhängigkeit aus, z. B. DB-Session + opt Löst aus + operation -->> dep: Löst Exception aus (z. B. HTTPException) + opt Handhabt + dep -->> dep: Kann Exception abfangen, eine neue HTTPException auslösen, andere Exceptions auslösen + dep -->> handler: Leitet Exception automatisch weiter + end + handler -->> client: HTTP-Error-Response + end + operation ->> client: Sendet Response an Client + Note over client,operation: Response wurde gesendet, kann nicht mehr geändert werden + opt Tasks + operation -->> tasks: Sendet Hintergrundtasks + end + opt Löst andere Exception aus + tasks -->> tasks: Handhabt Exception im Hintergrundtask-Code + end +``` + +!!! info + Es wird nur **eine Response** an den Client gesendet. Es kann eine Error-Response oder die Response der *Pfadoperation* sein. + + Nachdem eine dieser Responses gesendet wurde, kann keine weitere Response gesendet werden. + +!!! tip "Tipp" + Obiges Diagramm verwendet `HTTPException`, aber Sie können auch jede andere Exception auslösen, die Sie in einer Abhängigkeit mit `yield` abfangen, oder mit einem [benutzerdefinierten Exceptionhandler](../handling-errors.md#benutzerdefinierte-exceptionhandler-definieren){.internal-link target=_blank} erstellt haben. + + Wenn Sie eine Exception auslösen, wird diese mit yield an die Abhängigkeiten übergeben, einschließlich `HTTPException`, und dann **erneut** an die Exceptionhandler. Wenn es für diese Exception keinen Exceptionhandler gibt, wird sie von der internen Default-`ServerErrorMiddleware` gehandhabt, was einen HTTP-Statuscode 500 zurückgibt, um den Client darüber zu informieren, dass ein Fehler auf dem Server aufgetreten ist. + +## Abhängigkeiten mit `yield`, `HTTPException` und Hintergrundtasks + +!!! warning "Achtung" + Sie benötigen diese technischen Details höchstwahrscheinlich nicht, Sie können diesen Abschnitt überspringen und weiter unten fortfahren. + + Diese Details sind vor allem dann nützlich, wenn Sie eine Version von FastAPI vor 0.106.0 verwendet haben und Ressourcen aus Abhängigkeiten mit `yield` in Hintergrundtasks verwendet haben. + +Vor FastAPI 0.106.0 war das Auslösen von Exceptions nach `yield` nicht möglich, der Exit-Code in Abhängigkeiten mit `yield` wurde ausgeführt, *nachdem* die Response gesendet wurde, die [Exceptionhandler](../handling-errors.md#benutzerdefinierte-exceptionhandler-definieren){.internal-link target=_blank} wären also bereits ausgeführt worden. + +Dies wurde hauptsächlich so konzipiert, damit die gleichen Objekte, die durch Abhängigkeiten ge`yield`et werden, innerhalb von Hintergrundtasks verwendet werden können, da der Exit-Code ausgeführt wird, nachdem die Hintergrundtasks abgeschlossen sind. + +Da dies jedoch bedeuten würde, darauf zu warten, dass die Response durch das Netzwerk reist, während eine Ressource unnötigerweise in einer Abhängigkeit mit yield gehalten wird (z. B. eine Datenbankverbindung), wurde dies in FastAPI 0.106.0 geändert. + +!!! tip "Tipp" + + Darüber hinaus handelt es sich bei einem Hintergrundtask normalerweise um einen unabhängigen Satz von Logik, der separat behandelt werden sollte, mit eigenen Ressourcen (z. B. einer eigenen Datenbankverbindung). + + Auf diese Weise erhalten Sie wahrscheinlich saubereren Code. + +Wenn Sie sich früher auf dieses Verhalten verlassen haben, sollten Sie jetzt die Ressourcen für Hintergrundtasks innerhalb des Hintergrundtasks selbst erstellen und intern nur Daten verwenden, die nicht von den Ressourcen von Abhängigkeiten mit `yield` abhängen. + +Anstatt beispielsweise dieselbe Datenbanksitzung zu verwenden, würden Sie eine neue Datenbanksitzung innerhalb des Hintergrundtasks erstellen und die Objekte mithilfe dieser neuen Sitzung aus der Datenbank abrufen. Und anstatt das Objekt aus der Datenbank als Parameter an die Hintergrundtask-Funktion zu übergeben, würden Sie die ID dieses Objekts übergeben und das Objekt dann innerhalb der Hintergrundtask-Funktion erneut laden. + +## Kontextmanager + +### Was sind „Kontextmanager“ + +„Kontextmanager“ (Englisch „Context Manager“) sind bestimmte Python-Objekte, die Sie in einer `with`-Anweisung verwenden können. + +Beispielsweise können Sie `with` verwenden, um eine Datei auszulesen: + +```Python +with open("./somefile.txt") as f: + contents = f.read() + print(contents) +``` + +Im Hintergrund erstellt das `open("./somefile.txt")` ein Objekt, das als „Kontextmanager“ bezeichnet wird. + +Dieser stellt sicher dass, wenn der `with`-Block beendet ist, die Datei geschlossen wird, auch wenn Exceptions geworfen wurden. + +Wenn Sie eine Abhängigkeit mit `yield` erstellen, erstellt **FastAPI** dafür intern einen Kontextmanager und kombiniert ihn mit einigen anderen zugehörigen Tools. + +### Kontextmanager in Abhängigkeiten mit `yield` verwenden + +!!! warning "Achtung" + Dies ist mehr oder weniger eine „fortgeschrittene“ Idee. + + Wenn Sie gerade erst mit **FastAPI** beginnen, möchten Sie das vielleicht vorerst überspringen. + +In Python können Sie Kontextmanager erstellen, indem Sie eine Klasse mit zwei Methoden erzeugen: `__enter__()` und `__exit__()`. + +Sie können solche auch innerhalb von **FastAPI**-Abhängigkeiten mit `yield` verwenden, indem Sie `with`- oder `async with`-Anweisungen innerhalb der Abhängigkeits-Funktion verwenden: + +```Python hl_lines="1-9 13" +{!../../../docs_src/dependencies/tutorial010.py!} +``` + +!!! tip "Tipp" + Andere Möglichkeiten, einen Kontextmanager zu erstellen, sind: + + * `@contextlib.contextmanager` oder + * `@contextlib.asynccontextmanager` + + Verwenden Sie diese, um eine Funktion zu dekorieren, die ein einziges `yield` hat. + + Das ist es auch, was **FastAPI** intern für Abhängigkeiten mit `yield` verwendet. + + Aber Sie müssen die Dekoratoren nicht für FastAPI-Abhängigkeiten verwenden (und das sollten Sie auch nicht). + + FastAPI erledigt das intern für Sie. diff --git a/docs/de/docs/tutorial/dependencies/global-dependencies.md b/docs/de/docs/tutorial/dependencies/global-dependencies.md new file mode 100644 index 0000000000000..8aa0899b80cb2 --- /dev/null +++ b/docs/de/docs/tutorial/dependencies/global-dependencies.md @@ -0,0 +1,34 @@ +# Globale Abhängigkeiten + +Bei einigen Anwendungstypen möchten Sie möglicherweise Abhängigkeiten zur gesamten Anwendung hinzufügen. + +Ähnlich wie Sie [`dependencies` zu den *Pfadoperation-Dekoratoren* hinzufügen](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} können, können Sie sie auch zur `FastAPI`-Anwendung hinzufügen. + +In diesem Fall werden sie auf alle *Pfadoperationen* in der Anwendung angewendet: + +=== "Python 3.9+" + + ```Python hl_lines="16" + {!> ../../../docs_src/dependencies/tutorial012_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="16" + {!> ../../../docs_src/dependencies/tutorial012_an.py!} + ``` + +=== "Python 3.8 nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="15" + {!> ../../../docs_src/dependencies/tutorial012.py!} + ``` + +Und alle Ideen aus dem Abschnitt über das [Hinzufügen von `dependencies` zu den *Pfadoperation-Dekoratoren*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} gelten weiterhin, aber in diesem Fall für alle *Pfadoperationen* in der Anwendung. + +## Abhängigkeiten für Gruppen von *Pfadoperationen* + +Wenn Sie später lesen, wie Sie größere Anwendungen strukturieren ([Bigger Applications - Multiple Files](../../tutorial/bigger-applications.md){.internal-link target=_blank}), möglicherweise mit mehreren Dateien, lernen Sie, wie Sie einen einzelnen `dependencies`-Parameter für eine Gruppe von *Pfadoperationen* deklarieren. diff --git a/docs/de/docs/tutorial/dependencies/index.md b/docs/de/docs/tutorial/dependencies/index.md new file mode 100644 index 0000000000000..6254e976d636f --- /dev/null +++ b/docs/de/docs/tutorial/dependencies/index.md @@ -0,0 +1,352 @@ +# Abhängigkeiten + +**FastAPI** hat ein sehr mächtiges, aber intuitives **Dependency Injection** System. + +Es ist so konzipiert, sehr einfach zu verwenden zu sein und es jedem Entwickler sehr leicht zu machen, andere Komponenten mit **FastAPI** zu integrieren. + +## Was ist „Dependency Injection“ + +**„Dependency Injection“** bedeutet in der Programmierung, dass es für Ihren Code (in diesem Fall Ihre *Pfadoperation-Funktionen*) eine Möglichkeit gibt, Dinge zu deklarieren, die er verwenden möchte und die er zum Funktionieren benötigt: „Abhängigkeiten“ – „Dependencies“. + +Das System (in diesem Fall **FastAPI**) kümmert sich dann darum, Ihren Code mit den erforderlichen Abhängigkeiten zu versorgen („die Abhängigkeiten einfügen“ – „inject the dependencies“). + +Das ist sehr nützlich, wenn Sie: + +* Eine gemeinsame Logik haben (die gleiche Code-Logik immer und immer wieder). +* Datenbankverbindungen teilen. +* Sicherheit, Authentifizierung, Rollenanforderungen, usw. durchsetzen. +* Und viele andere Dinge ... + +All dies, während Sie Codeverdoppelung minimieren. + +## Erste Schritte + +Sehen wir uns ein sehr einfaches Beispiel an. Es ist so einfach, dass es vorerst nicht sehr nützlich ist. + +Aber so können wir uns besser auf die Funktionsweise des **Dependency Injection** Systems konzentrieren. + +### Erstellen Sie eine Abhängigkeit („Dependable“) + +Konzentrieren wir uns zunächst auf die Abhängigkeit - die Dependency. + +Es handelt sich einfach um eine Funktion, die die gleichen Parameter entgegennimmt wie eine *Pfadoperation-Funktion*: +=== "Python 3.10+" + + ```Python hl_lines="8-9" + {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="8-11" + {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9-12" + {!> ../../../docs_src/dependencies/tutorial001_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="6-7" + {!> ../../../docs_src/dependencies/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="8-11" + {!> ../../../docs_src/dependencies/tutorial001.py!} + ``` + +Das war's schon. + +**Zwei Zeilen**. + +Und sie hat die gleiche Form und Struktur wie alle Ihre *Pfadoperation-Funktionen*. + +Sie können sie sich als *Pfadoperation-Funktion* ohne den „Dekorator“ (ohne `@app.get("/some-path")`) vorstellen. + +Und sie kann alles zurückgeben, was Sie möchten. + +In diesem Fall erwartet diese Abhängigkeit: + +* Einen optionalen Query-Parameter `q`, der ein `str` ist. +* Einen optionalen Query-Parameter `skip`, der ein `int` ist und standardmäßig `0` ist. +* Einen optionalen Query-Parameter `limit`, der ein `int` ist und standardmäßig `100` ist. + +Und dann wird einfach ein `dict` zurückgegeben, welches diese Werte enthält. + +!!! info + FastAPI unterstützt (und empfiehlt die Verwendung von) `Annotated` seit Version 0.95.0. + + Wenn Sie eine ältere Version haben, werden Sie Fehler angezeigt bekommen, wenn Sie versuchen, `Annotated` zu verwenden. + + Bitte [aktualisieren Sie FastAPI](../../deployment/versions.md#upgrade-der-fastapi-versionen){.internal-link target=_blank} daher mindestens zu Version 0.95.1, bevor Sie `Annotated` verwenden. + +### `Depends` importieren + +=== "Python 3.10+" + + ```Python hl_lines="3" + {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="3" + {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="3" + {!> ../../../docs_src/dependencies/tutorial001_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="1" + {!> ../../../docs_src/dependencies/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="3" + {!> ../../../docs_src/dependencies/tutorial001.py!} + ``` + +### Deklarieren der Abhängigkeit im „Dependant“ + +So wie auch `Body`, `Query`, usw., verwenden Sie `Depends` mit den Parametern Ihrer *Pfadoperation-Funktion*: + +=== "Python 3.10+" + + ```Python hl_lines="13 18" + {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="15 20" + {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="16 21" + {!> ../../../docs_src/dependencies/tutorial001_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="11 16" + {!> ../../../docs_src/dependencies/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="15 20" + {!> ../../../docs_src/dependencies/tutorial001.py!} + ``` + +Obwohl Sie `Depends` in den Parametern Ihrer Funktion genauso verwenden wie `Body`, `Query`, usw., funktioniert `Depends` etwas anders. + +Sie übergeben `Depends` nur einen einzigen Parameter. + +Dieser Parameter muss so etwas wie eine Funktion sein. + +Sie **rufen diese nicht direkt auf** (fügen Sie am Ende keine Klammern hinzu), sondern übergeben sie einfach als Parameter an `Depends()`. + +Und diese Funktion akzeptiert Parameter auf die gleiche Weise wie *Pfadoperation-Funktionen*. + +!!! tip "Tipp" + Im nächsten Kapitel erfahren Sie, welche anderen „Dinge“, außer Funktionen, Sie als Abhängigkeiten verwenden können. + +Immer wenn ein neuer Request eintrifft, kümmert sich **FastAPI** darum: + +* Ihre Abhängigkeitsfunktion („Dependable“) mit den richtigen Parametern aufzurufen. +* Sich das Ergebnis von dieser Funktion zu holen. +* Dieses Ergebnis dem Parameter Ihrer *Pfadoperation-Funktion* zuzuweisen. + +```mermaid +graph TB + +common_parameters(["common_parameters"]) +read_items["/items/"] +read_users["/users/"] + +common_parameters --> read_items +common_parameters --> read_users +``` + +Auf diese Weise schreiben Sie gemeinsam genutzten Code nur einmal, und **FastAPI** kümmert sich darum, ihn für Ihre *Pfadoperationen* aufzurufen. + +!!! check + Beachten Sie, dass Sie keine spezielle Klasse erstellen und diese irgendwo an **FastAPI** übergeben müssen, um sie zu „registrieren“ oder so ähnlich. + + Sie übergeben es einfach an `Depends` und **FastAPI** weiß, wie der Rest erledigt wird. + +## `Annotated`-Abhängigkeiten wiederverwenden + +In den Beispielen oben sehen Sie, dass es ein kleines bisschen **Codeverdoppelung** gibt. + +Wenn Sie die Abhängigkeit `common_parameters()` verwenden, müssen Sie den gesamten Parameter mit der Typannotation und `Depends()` schreiben: + +```Python +commons: Annotated[dict, Depends(common_parameters)] +``` + +Da wir jedoch `Annotated` verwenden, können wir diesen `Annotated`-Wert in einer Variablen speichern und an mehreren Stellen verwenden: + +=== "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.8+" + + ```Python hl_lines="15 19 24" + {!> ../../../docs_src/dependencies/tutorial001_02_an.py!} + ``` + +!!! tip "Tipp" + Das ist schlicht Standard-Python, es wird als „Typalias“ bezeichnet und ist eigentlich nicht **FastAPI**-spezifisch. + + Da **FastAPI** jedoch auf Standard-Python, einschließlich `Annotated`, basiert, können Sie diesen Trick in Ihrem Code verwenden. 😎 + +Die Abhängigkeiten funktionieren weiterhin wie erwartet, und das **Beste daran** ist, dass die **Typinformationen erhalten bleiben**, was bedeutet, dass Ihr Editor Ihnen weiterhin **automatische Vervollständigung**, **Inline-Fehler**, usw. bieten kann. Das Gleiche gilt für andere Tools wie `mypy`. + +Das ist besonders nützlich, wenn Sie es in einer **großen Codebasis** verwenden, in der Sie in **vielen *Pfadoperationen*** immer wieder **dieselben Abhängigkeiten** verwenden. + +## `async` oder nicht `async` + +Da Abhängigkeiten auch von **FastAPI** aufgerufen werden (so wie Ihre *Pfadoperation-Funktionen*), gelten beim Definieren Ihrer Funktionen die gleichen Regeln. + +Sie können `async def` oder einfach `def` verwenden. + +Und Sie können Abhängigkeiten mit `async def` innerhalb normaler `def`-*Pfadoperation-Funktionen* oder `def`-Abhängigkeiten innerhalb von `async def`-*Pfadoperation-Funktionen*, usw. deklarieren. + +Es spielt keine Rolle. **FastAPI** weiß, was zu tun ist. + +!!! note "Hinweis" + Wenn Ihnen das nichts sagt, lesen Sie den [Async: *„In Eile?“*](../../async.md#in-eile){.internal-link target=_blank}-Abschnitt über `async` und `await` in der Dokumentation. + +## Integriert in OpenAPI + +Alle Requestdeklarationen, -validierungen und -anforderungen Ihrer Abhängigkeiten (und Unterabhängigkeiten) werden in dasselbe OpenAPI-Schema integriert. + +Die interaktive Dokumentation enthält also auch alle Informationen aus diesen Abhängigkeiten: + + + +## Einfache Verwendung + +Näher betrachtet, werden *Pfadoperation-Funktionen* deklariert, um verwendet zu werden, wann immer ein *Pfad* und eine *Operation* übereinstimmen, und dann kümmert sich **FastAPI** darum, die Funktion mit den richtigen Parametern aufzurufen, die Daten aus der Anfrage extrahierend. + +Tatsächlich funktionieren alle (oder die meisten) Webframeworks auf die gleiche Weise. + +Sie rufen diese Funktionen niemals direkt auf. Sie werden von Ihrem Framework aufgerufen (in diesem Fall **FastAPI**). + +Mit dem Dependency Injection System können Sie **FastAPI** ebenfalls mitteilen, dass Ihre *Pfadoperation-Funktion* von etwas anderem „abhängt“, das vor Ihrer *Pfadoperation-Funktion* ausgeführt werden soll, und **FastAPI** kümmert sich darum, es auszuführen und die Ergebnisse zu „injizieren“. + +Andere gebräuchliche Begriffe für dieselbe Idee der „Abhängigkeitsinjektion“ sind: + +* Ressourcen +* Provider +* Services +* Injectables +* Komponenten + +## **FastAPI**-Plugins + +Integrationen und „Plugins“ können mit dem **Dependency Injection** System erstellt werden. Aber tatsächlich besteht **keine Notwendigkeit, „Plugins“ zu erstellen**, da es durch die Verwendung von Abhängigkeiten möglich ist, eine unendliche Anzahl von Integrationen und Interaktionen zu deklarieren, die dann für Ihre *Pfadoperation-Funktionen* verfügbar sind. + +Und Abhängigkeiten können auf sehr einfache und intuitive Weise erstellt werden, sodass Sie einfach die benötigten Python-Packages importieren und sie in wenigen Codezeilen, *im wahrsten Sinne des Wortes*, mit Ihren API-Funktionen integrieren. + +Beispiele hierfür finden Sie in den nächsten Kapiteln zu relationalen und NoSQL-Datenbanken, Sicherheit usw. + +## **FastAPI**-Kompatibilität + +Die Einfachheit des Dependency Injection Systems macht **FastAPI** kompatibel mit: + +* allen relationalen Datenbanken +* NoSQL-Datenbanken +* externen Packages +* externen APIs +* Authentifizierungs- und Autorisierungssystemen +* API-Nutzungs-Überwachungssystemen +* Responsedaten-Injektionssystemen +* usw. + +## Einfach und leistungsstark + +Obwohl das hierarchische Dependency Injection System sehr einfach zu definieren und zu verwenden ist, ist es dennoch sehr mächtig. + +Sie können Abhängigkeiten definieren, die selbst wiederum Abhängigkeiten definieren können. + +Am Ende wird ein hierarchischer Baum von Abhängigkeiten erstellt, und das **Dependency Injection** System kümmert sich darum, alle diese Abhängigkeiten (und deren Unterabhängigkeiten) für Sie aufzulösen und die Ergebnisse bei jedem Schritt einzubinden (zu injizieren). + +Nehmen wir zum Beispiel an, Sie haben vier API-Endpunkte (*Pfadoperationen*): + +* `/items/public/` +* `/items/private/` +* `/users/{user_id}/activate` +* `/items/pro/` + +Dann könnten Sie für jeden davon unterschiedliche Berechtigungsanforderungen hinzufügen, nur mit Abhängigkeiten und Unterabhängigkeiten: + +```mermaid +graph TB + +current_user(["current_user"]) +active_user(["active_user"]) +admin_user(["admin_user"]) +paying_user(["paying_user"]) + +public["/items/public/"] +private["/items/private/"] +activate_user["/users/{user_id}/activate"] +pro_items["/items/pro/"] + +current_user --> active_user +active_user --> admin_user +active_user --> paying_user + +current_user --> public +active_user --> private +admin_user --> activate_user +paying_user --> pro_items +``` + +## Integriert mit **OpenAPI** + +Alle diese Abhängigkeiten, während sie ihre Anforderungen deklarieren, fügen auch Parameter, Validierungen, usw. zu Ihren *Pfadoperationen* hinzu. + +**FastAPI** kümmert sich darum, alles zum OpenAPI-Schema hinzuzufügen, damit es in den interaktiven Dokumentationssystemen angezeigt wird. diff --git a/docs/de/docs/tutorial/dependencies/sub-dependencies.md b/docs/de/docs/tutorial/dependencies/sub-dependencies.md new file mode 100644 index 0000000000000..0fa2af839eddb --- /dev/null +++ b/docs/de/docs/tutorial/dependencies/sub-dependencies.md @@ -0,0 +1,194 @@ +# Unterabhängigkeiten + +Sie können Abhängigkeiten erstellen, die **Unterabhängigkeiten** haben. + +Diese können so **tief** verschachtelt sein, wie nötig. + +**FastAPI** kümmert sich darum, sie aufzulösen. + +## Erste Abhängigkeit, „Dependable“ + +Sie könnten eine erste Abhängigkeit („Dependable“) wie folgt erstellen: + +=== "Python 3.10+" + + ```Python hl_lines="8-9" + {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="8-9" + {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9-10" + {!> ../../../docs_src/dependencies/tutorial005_an.py!} + ``` + +=== "Python 3.10 nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="6-7" + {!> ../../../docs_src/dependencies/tutorial005_py310.py!} + ``` + +=== "Python 3.8 nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="8-9" + {!> ../../../docs_src/dependencies/tutorial005.py!} + ``` + +Diese deklariert einen optionalen Abfrageparameter `q` vom Typ `str` und gibt ihn dann einfach zurück. + +Das ist recht einfach (nicht sehr nützlich), hilft uns aber dabei, uns auf die Funktionsweise der Unterabhängigkeiten zu konzentrieren. + +## Zweite Abhängigkeit, „Dependable“ und „Dependant“ + +Dann können Sie eine weitere Abhängigkeitsfunktion (ein „Dependable“) erstellen, die gleichzeitig eine eigene Abhängigkeit deklariert (also auch ein „Dependant“ ist): + +=== "Python 3.10+" + + ```Python hl_lines="13" + {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="13" + {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="14" + {!> ../../../docs_src/dependencies/tutorial005_an.py!} + ``` + +=== "Python 3.10 nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="11" + {!> ../../../docs_src/dependencies/tutorial005_py310.py!} + ``` + +=== "Python 3.8 nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="13" + {!> ../../../docs_src/dependencies/tutorial005.py!} + ``` + +Betrachten wir die deklarierten Parameter: + +* Obwohl diese Funktion selbst eine Abhängigkeit ist („Dependable“, etwas hängt von ihr ab), deklariert sie auch eine andere Abhängigkeit („Dependant“, sie hängt von etwas anderem ab). + * Sie hängt von `query_extractor` ab und weist den von diesem zurückgegebenen Wert dem Parameter `q` zu. +* Sie deklariert außerdem ein optionales `last_query`-Cookie, ein `str`. + * Wenn der Benutzer keine Query `q` übermittelt hat, verwenden wir die zuletzt übermittelte Query, die wir zuvor in einem Cookie gespeichert haben. + +## Die Abhängigkeit verwenden + +Diese Abhängigkeit verwenden wir nun wie folgt: + +=== "Python 3.10+" + + ```Python hl_lines="23" + {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="23" + {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="24" + {!> ../../../docs_src/dependencies/tutorial005_an.py!} + ``` + +=== "Python 3.10 nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial005_py310.py!} + ``` + +=== "Python 3.8 nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="22" + {!> ../../../docs_src/dependencies/tutorial005.py!} + ``` + +!!! info + Beachten Sie, dass wir in der *Pfadoperation-Funktion* nur eine einzige Abhängigkeit deklarieren, den `query_or_cookie_extractor`. + + Aber **FastAPI** wird wissen, dass es zuerst `query_extractor` auflösen muss, um dessen Resultat `query_or_cookie_extractor` zu übergeben, wenn dieses aufgerufen wird. + +```mermaid +graph TB + +query_extractor(["query_extractor"]) +query_or_cookie_extractor(["query_or_cookie_extractor"]) + +read_query["/items/"] + +query_extractor --> query_or_cookie_extractor --> read_query +``` + +## Dieselbe Abhängigkeit mehrmals verwenden + +Wenn eine Ihrer Abhängigkeiten mehrmals für dieselbe *Pfadoperation* deklariert wird, beispielsweise wenn mehrere Abhängigkeiten eine gemeinsame Unterabhängigkeit haben, wird **FastAPI** diese Unterabhängigkeit nur einmal pro Request aufrufen. + +Und es speichert den zurückgegebenen Wert in einem „Cache“ und übergibt diesen gecachten Wert an alle „Dependanten“, die ihn in diesem spezifischen Request benötigen, anstatt die Abhängigkeit mehrmals für denselben Request aufzurufen. + +In einem fortgeschrittenen Szenario, bei dem Sie wissen, dass die Abhängigkeit bei jedem Schritt (möglicherweise mehrmals) in derselben Anfrage aufgerufen werden muss, anstatt den zwischengespeicherten Wert zu verwenden, können Sie den Parameter `use_cache=False` festlegen, wenn Sie `Depends` verwenden: + +=== "Python 3.8+" + + ```Python hl_lines="1" + async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]): + return {"fresh_value": fresh_value} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="1" + async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)): + return {"fresh_value": fresh_value} + ``` + +## Zusammenfassung + +Abgesehen von all den ausgefallenen Wörtern, die hier verwendet werden, ist das **Dependency Injection**-System recht simpel. + +Einfach Funktionen, die genauso aussehen wie *Pfadoperation-Funktionen*. + +Dennoch ist es sehr mächtig und ermöglicht Ihnen die Deklaration beliebig tief verschachtelter Abhängigkeits-„Graphen“ (Bäume). + +!!! tip "Tipp" + All dies scheint angesichts dieser einfachen Beispiele möglicherweise nicht so nützlich zu sein. + + Aber Sie werden in den Kapiteln über **Sicherheit** sehen, wie nützlich das ist. + + Und Sie werden auch sehen, wie viel Code Sie dadurch einsparen. diff --git a/docs/de/docs/tutorial/encoder.md b/docs/de/docs/tutorial/encoder.md new file mode 100644 index 0000000000000..12f73bd124e50 --- /dev/null +++ b/docs/de/docs/tutorial/encoder.md @@ -0,0 +1,42 @@ +# JSON-kompatibler Encoder + +Es gibt Fälle, da möchten Sie einen Datentyp (etwa ein Pydantic-Modell) in etwas konvertieren, das kompatibel mit JSON ist (etwa ein `dict`, eine `list`e, usw.). + +Zum Beispiel, wenn Sie es in einer Datenbank speichern möchten. + +Dafür bietet **FastAPI** eine Funktion `jsonable_encoder()`. + +## `jsonable_encoder` verwenden + +Stellen wir uns vor, Sie haben eine Datenbank `fake_db`, die nur JSON-kompatible Daten entgegennimmt. + +Sie akzeptiert zum Beispiel keine `datetime`-Objekte, da die nicht kompatibel mit JSON sind. + +Ein `datetime`-Objekt müsste also in einen `str` umgewandelt werden, der die Daten im ISO-Format enthält. + +Genauso würde die Datenbank kein Pydantic-Modell (ein Objekt mit Attributen) akzeptieren, sondern nur ein `dict`. + +Sie können für diese Fälle `jsonable_encoder` verwenden. + +Es nimmt ein Objekt entgegen, wie etwa ein Pydantic-Modell, und gibt eine JSON-kompatible Version zurück: + +=== "Python 3.10+" + + ```Python hl_lines="4 21" + {!> ../../../docs_src/encoder/tutorial001_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="5 22" + {!> ../../../docs_src/encoder/tutorial001.py!} + ``` + +In diesem Beispiel wird das Pydantic-Modell in ein `dict`, und das `datetime`-Objekt in ein `str` konvertiert. + +Das Resultat dieses Aufrufs ist etwas, das mit Pythons Standard-`json.dumps()` kodiert werden kann. + +Es wird also kein großer `str` zurückgegeben, der die Daten im JSON-Format (als String) enthält. Es wird eine Python-Standarddatenstruktur (z. B. ein `dict`) zurückgegeben, mit Werten und Unterwerten, die alle mit JSON kompatibel sind. + +!!! note "Hinweis" + `jsonable_encoder` wird tatsächlich von **FastAPI** intern verwendet, um Daten zu konvertieren. Aber es ist in vielen anderen Szenarien hilfreich. diff --git a/docs/de/docs/tutorial/extra-data-types.md b/docs/de/docs/tutorial/extra-data-types.md new file mode 100644 index 0000000000000..0fcb206832ee1 --- /dev/null +++ b/docs/de/docs/tutorial/extra-data-types.md @@ -0,0 +1,130 @@ +# Zusätzliche Datentypen + +Bisher haben Sie gängige Datentypen verwendet, wie zum Beispiel: + +* `int` +* `float` +* `str` +* `bool` + +Sie können aber auch komplexere Datentypen verwenden. + +Und Sie haben immer noch dieselbe Funktionalität wie bisher gesehen: + +* Großartige Editor-Unterstützung. +* Datenkonvertierung bei eingehenden Requests. +* Datenkonvertierung für Response-Daten. +* Datenvalidierung. +* Automatische Annotation und Dokumentation. + +## Andere Datentypen + +Hier sind einige der zusätzlichen Datentypen, die Sie verwenden können: + +* `UUID`: + * Ein standardmäßiger „universell eindeutiger Bezeichner“ („Universally Unique Identifier“), der in vielen Datenbanken und Systemen als ID üblich ist. + * Wird in Requests und Responses als `str` dargestellt. +* `datetime.datetime`: + * Ein Python-`datetime.datetime`. + * Wird in Requests und Responses als `str` im ISO 8601-Format dargestellt, etwa: `2008-09-15T15:53:00+05:00`. +* `datetime.date`: + * Python-`datetime.date`. + * Wird in Requests und Responses als `str` im ISO 8601-Format dargestellt, etwa: `2008-09-15`. +* `datetime.time`: + * Ein Python-`datetime.time`. + * Wird in Requests und Responses als `str` im ISO 8601-Format dargestellt, etwa: `14:23:55.003`. +* `datetime.timedelta`: + * Ein Python-`datetime.timedelta`. + * Wird in Requests und Responses als `float` der Gesamtsekunden dargestellt. + * Pydantic ermöglicht auch die Darstellung als „ISO 8601 Zeitdifferenz-Kodierung“, Weitere Informationen finden Sie in der Dokumentation. +* `frozenset`: + * Wird in Requests und Responses wie ein `set` behandelt: + * Bei Requests wird eine Liste gelesen, Duplikate entfernt und in ein `set` umgewandelt. + * Bei Responses wird das `set` in eine `list`e umgewandelt. + * Das generierte Schema zeigt an, dass die `set`-Werte eindeutig sind (unter Verwendung von JSON Schemas `uniqueItems`). +* `bytes`: + * Standard-Python-`bytes`. + * In Requests und Responses werden sie als `str` behandelt. + * Das generierte Schema wird anzeigen, dass es sich um einen `str` mit `binary` „Format“ handelt. +* `Decimal`: + * Standard-Python-`Decimal`. + * In Requests und Responses wird es wie ein `float` behandelt. +* Sie können alle gültigen Pydantic-Datentypen hier überprüfen: Pydantic data types. + +## Beispiel + +Hier ist ein Beispiel für eine *Pfadoperation* mit Parametern, die einige der oben genannten Typen verwenden. + +=== "Python 3.10+" + + ```Python hl_lines="1 3 12-16" + {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="1 3 12-16" + {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="1 3 13-17" + {!> ../../../docs_src/extra_data_types/tutorial001_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="1 2 11-15" + {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="1 2 12-16" + {!> ../../../docs_src/extra_data_types/tutorial001.py!} + ``` + +Beachten Sie, dass die Parameter innerhalb der Funktion ihren natürlichen Datentyp haben und Sie beispielsweise normale Datumsmanipulationen durchführen können, wie zum Beispiel: + +=== "Python 3.10+" + + ```Python hl_lines="18-19" + {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="18-19" + {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="19-20" + {!> ../../../docs_src/extra_data_types/tutorial001_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="17-18" + {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="18-19" + {!> ../../../docs_src/extra_data_types/tutorial001.py!} + ``` diff --git a/docs/de/docs/tutorial/extra-models.md b/docs/de/docs/tutorial/extra-models.md new file mode 100644 index 0000000000000..cdf16c4bab90b --- /dev/null +++ b/docs/de/docs/tutorial/extra-models.md @@ -0,0 +1,257 @@ +# Extramodelle + +Fahren wir beim letzten Beispiel fort. Es gibt normalerweise mehrere zusammengehörende Modelle. + +Insbesondere Benutzermodelle, denn: + +* Das **hereinkommende Modell** sollte ein Passwort haben können. +* Das **herausgehende Modell** sollte kein Passwort haben. +* Das **Datenbankmodell** sollte wahrscheinlich ein gehashtes Passwort haben. + +!!! danger "Gefahr" + Speichern Sie niemals das Klartext-Passwort eines Benutzers. Speichern Sie immer den „sicheren Hash“, den Sie verifizieren können. + + Falls Ihnen das nichts sagt, in den [Sicherheits-Kapiteln](security/simple-oauth2.md#passwort-hashing){.internal-link target=_blank} werden Sie lernen, was ein „Passwort-Hash“ ist. + +## Mehrere Modelle + +Hier der generelle Weg, wie die Modelle mit ihren Passwort-Feldern aussehen könnten, und an welchen Orten sie verwendet werden würden. + +=== "Python 3.10+" + + ```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" + {!> ../../../docs_src/extra_models/tutorial001_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" + {!> ../../../docs_src/extra_models/tutorial001.py!} + ``` + +!!! info + In Pydantic v1 hieß diese Methode `.dict()`, in Pydantic v2 wurde sie deprecated (aber immer noch unterstützt) und in `.model_dump()` umbenannt. + + Die Beispiele hier verwenden `.dict()` für die Kompatibilität mit Pydantic v1, Sie sollten jedoch stattdessen `.model_dump()` verwenden, wenn Sie Pydantic v2 verwenden können. + +### Über `**user_in.dict()` + +#### Pydantic's `.dict()` + +`user_in` ist ein Pydantic-Modell der Klasse `UserIn`. + +Pydantic-Modelle haben eine `.dict()`-Methode, die ein `dict` mit den Daten des Modells zurückgibt. + +Wenn wir also ein Pydantic-Objekt `user_in` erstellen, etwa so: + +```Python +user_in = UserIn(username="john", password="secret", email="john.doe@example.com") +``` + +und wir rufen seine `.dict()`-Methode auf: + +```Python +user_dict = user_in.dict() +``` + +dann haben wir jetzt in der Variable `user_dict` ein `dict` mit den gleichen Daten (es ist ein `dict` statt eines Pydantic-Modellobjekts). + +Wenn wir es ausgeben: + +```Python +print(user_dict) +``` + +bekommen wir ein Python-`dict`: + +```Python +{ + 'username': 'john', + 'password': 'secret', + 'email': 'john.doe@example.com', + 'full_name': None, +} +``` + +#### Ein `dict` entpacken + +Wenn wir ein `dict` wie `user_dict` nehmen, und es einer Funktion (oder Klassenmethode) mittels `**user_dict` übergeben, wird Python es „entpacken“. Es wird die Schlüssel und Werte von `user_dict` direkt als Schlüsselwort-Argumente übergeben. + +Wenn wir also das `user_dict` von oben nehmen und schreiben: + +```Python +UserInDB(**user_dict) +``` + +dann ist das ungefähr äquivalent zu: + +```Python +UserInDB( + username="john", + password="secret", + email="john.doe@example.com", + full_name=None, +) +``` + +Oder, präziser, `user_dict` wird direkt verwendet, welche Werte es auch immer haben mag: + +```Python +UserInDB( + username = user_dict["username"], + password = user_dict["password"], + email = user_dict["email"], + full_name = user_dict["full_name"], +) +``` + +#### Ein Pydantic-Modell aus den Inhalten eines anderen erstellen. + +Da wir in obigem Beispiel `user_dict` mittels `user_in.dict()` erzeugt haben, ist dieser Code: + +```Python +user_dict = user_in.dict() +UserInDB(**user_dict) +``` + +äquivalent zu: + +```Python +UserInDB(**user_in.dict()) +``` + +... weil `user_in.dict()` ein `dict` ist, und dann lassen wir Python es „entpacken“, indem wir es `UserInDB` übergeben, mit vorangestelltem `**`. + +Wir erhalten also ein Pydantic-Modell aus den Daten eines anderen Pydantic-Modells. + +#### Ein `dict` entpacken und zusätzliche Schlüsselwort-Argumente + +Und dann fügen wir ein noch weiteres Schlüsselwort-Argument hinzu, `hashed_password=hashed_password`: + +```Python +UserInDB(**user_in.dict(), hashed_password=hashed_password) +``` + +... was am Ende ergibt: + +```Python +UserInDB( + username = user_dict["username"], + password = user_dict["password"], + email = user_dict["email"], + full_name = user_dict["full_name"], + hashed_password = hashed_password, +) +``` + +!!! warning "Achtung" + Die Hilfsfunktionen `fake_password_hasher` und `fake_save_user` demonstrieren nur den möglichen Fluss der Daten und bieten natürlich keine echte Sicherheit. + +## Verdopplung vermeiden + +Reduzierung von Code-Verdoppelung ist eine der Kern-Ideen von **FastAPI**. + +Weil Verdoppelung von Code die Wahrscheinlichkeit von Fehlern, Sicherheitsproblemen, Desynchronisation (Code wird nur an einer Stelle verändert, aber nicht an einer anderen), usw. erhöht. + +Unsere Modelle teilen alle eine Menge der Daten und verdoppeln Attribut-Namen und -Typen. + +Das können wir besser machen. + +Wir deklarieren ein `UserBase`-Modell, das als Basis für unsere anderen Modelle dient. Dann können wir Unterklassen erstellen, die seine Attribute (Typdeklarationen, Validierungen, usw.) erben. + +Die ganze Datenkonvertierung, -validierung, -dokumentation, usw. wird immer noch wie gehabt funktionieren. + +Auf diese Weise beschreiben wir nur noch die Unterschiede zwischen den Modellen (mit Klartext-`password`, mit `hashed_password`, und ohne Passwort): + +=== "Python 3.10+" + + ```Python hl_lines="7 13-14 17-18 21-22" + {!> ../../../docs_src/extra_models/tutorial002_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9 15-16 19-20 23-24" + {!> ../../../docs_src/extra_models/tutorial002.py!} + ``` + +## `Union`, oder `anyOf` + +Sie können deklarieren, dass eine Response eine `Union` mehrerer Typen ist, sprich, einer dieser Typen. + +Das wird in OpenAPI mit `anyOf` angezeigt. + +Um das zu tun, verwenden Sie Pythons Standard-Typhinweis `typing.Union`: + +!!! note "Hinweis" + Listen Sie, wenn Sie eine `Union` definieren, denjenigen Typ zuerst, der am spezifischsten ist, gefolgt von den weniger spezifischen Typen. Im Beispiel oben, in `Union[PlaneItem, CarItem]` also den spezifischeren `PlaneItem` vor dem weniger spezifischen `CarItem`. + +=== "Python 3.10+" + + ```Python hl_lines="1 14-15 18-20 33" + {!> ../../../docs_src/extra_models/tutorial003_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="1 14-15 18-20 33" + {!> ../../../docs_src/extra_models/tutorial003.py!} + ``` + +### `Union` in Python 3.10 + +In diesem Beispiel übergeben wir dem Argument `response_model` den Wert `Union[PlaneItem, CarItem]`. + +Da wir es als **Wert einem Argument überreichen**, statt es als **Typannotation** zu verwenden, müssen wir `Union` verwenden, selbst in Python 3.10. + +Wenn es eine Typannotation gewesen wäre, hätten wir auch den vertikalen Trennstrich verwenden können, wie in: + +```Python +some_variable: PlaneItem | CarItem +``` + +Aber wenn wir das in der Zuweisung `response_model=PlaneItem | CarItem` machen, erhalten wir eine Fehlermeldung, da Python versucht, eine **ungültige Operation** zwischen `PlaneItem` und `CarItem` durchzuführen, statt es als Typannotation zu interpretieren. + +## Listen von Modellen + +Genauso können Sie eine Response deklarieren, die eine Liste von Objekten ist. + +Verwenden Sie dafür Pythons Standard `typing.List` (oder nur `list` in Python 3.9 und darüber): + +=== "Python 3.9+" + + ```Python hl_lines="18" + {!> ../../../docs_src/extra_models/tutorial004_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="1 20" + {!> ../../../docs_src/extra_models/tutorial004.py!} + ``` + +## Response mit beliebigem `dict` + +Sie könne auch eine Response deklarieren, die ein beliebiges `dict` zurückgibt, bei dem nur die Typen der Schlüssel und der Werte bekannt sind, ohne ein Pydantic-Modell zu verwenden. + +Das ist nützlich, wenn Sie die gültigen Feld-/Attribut-Namen von vorneherein nicht wissen (was für ein Pydantic-Modell notwendig ist). + +In diesem Fall können Sie `typing.Dict` verwenden (oder nur `dict` in Python 3.9 und darüber): + +=== "Python 3.9+" + + ```Python hl_lines="6" + {!> ../../../docs_src/extra_models/tutorial005_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="1 8" + {!> ../../../docs_src/extra_models/tutorial005.py!} + ``` + +## Zusammenfassung + +Verwenden Sie gerne mehrere Pydantic-Modelle und vererben Sie je nach Bedarf. + +Sie brauchen kein einzelnes Datenmodell pro Einheit, wenn diese Einheit verschiedene Zustände annehmen kann. So wie unsere Benutzer-„Einheit“, welche einen Zustand mit `password`, einen mit `password_hash` und einen ohne Passwort hatte. diff --git a/docs/de/docs/tutorial/first-steps.md b/docs/de/docs/tutorial/first-steps.md new file mode 100644 index 0000000000000..27ba3ec16795e --- /dev/null +++ b/docs/de/docs/tutorial/first-steps.md @@ -0,0 +1,333 @@ +# Erste Schritte + +Die einfachste FastAPI-Datei könnte wie folgt aussehen: + +```Python +{!../../../docs_src/first_steps/tutorial001.py!} +``` + +Kopieren Sie dies in eine Datei `main.py`. + +Starten Sie den Live-Server: + +
+ +```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 "Hinweis" + Der Befehl `uvicorn main:app` bezieht sich auf: + + * `main`: die Datei `main.py` (das sogenannte Python-„Modul“). + * `app`: das Objekt, welches in der Datei `main.py` mit der Zeile `app = FastAPI()` erzeugt wurde. + * `--reload`: lässt den Server nach Codeänderungen neu starten. Verwenden Sie das nur während der Entwicklung. + +In der Konsolenausgabe sollte es eine Zeile geben, die ungefähr so aussieht: + +```hl_lines="4" +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +Diese Zeile zeigt die URL, unter der Ihre Anwendung auf Ihrem lokalen Computer bereitgestellt wird. + +### Testen Sie es + +Öffnen Sie Ihren Browser unter http://127.0.0.1:8000. + +Sie werden folgende JSON-Response sehen: + +```JSON +{"message": "Hello World"} +``` + +### Interaktive API-Dokumentation + +Gehen Sie als Nächstes auf http://127.0.0.1:8000/docs . + +Sie werden die automatisch erzeugte, interaktive API-Dokumentation sehen (bereitgestellt durch Swagger UI): + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +### Alternative API-Dokumentation + +Gehen Sie nun auf http://127.0.0.1:8000/redoc. + +Dort sehen Sie die alternative, automatische Dokumentation (bereitgestellt durch ReDoc): + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +### OpenAPI + +**FastAPI** generiert ein „Schema“ mit all Ihren APIs unter Verwendung des **OpenAPI**-Standards zur Definition von APIs. + +#### „Schema“ + +Ein „Schema“ ist eine Definition oder Beschreibung von etwas. Nicht der eigentliche Code, der es implementiert, sondern lediglich eine abstrakte Beschreibung. + +#### API-„Schema“ + +In diesem Fall ist OpenAPI eine Spezifikation, die vorschreibt, wie ein Schema für Ihre API zu definieren ist. + +Diese Schemadefinition enthält Ihre API-Pfade, die möglichen Parameter, welche diese entgegennehmen, usw. + +#### Daten-„Schema“ + +Der Begriff „Schema“ kann sich auch auf die Form von Daten beziehen, wie z. B. einen JSON-Inhalt. + +In diesem Fall sind die JSON-Attribute und deren Datentypen, usw. gemeint. + +#### OpenAPI und JSON Schema + +OpenAPI definiert ein API-Schema für Ihre API. Dieses Schema enthält Definitionen (oder „Schemas“) der Daten, die von Ihrer API unter Verwendung von **JSON Schema**, dem Standard für JSON-Datenschemata, gesendet und empfangen werden. + +#### Überprüfen Sie die `openapi.json` + +Falls Sie wissen möchten, wie das rohe OpenAPI-Schema aussieht: FastAPI generiert automatisch ein JSON (Schema) mit den Beschreibungen Ihrer gesamten API. + +Sie können es direkt einsehen unter: http://127.0.0.1:8000/openapi.json. + +Es wird ein JSON angezeigt, welches ungefähr so aussieht: + +```JSON +{ + "openapi": "3.1.0", + "info": { + "title": "FastAPI", + "version": "0.1.0" + }, + "paths": { + "/items/": { + "get": { + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + + + +... +``` + +#### Wofür OpenAPI gedacht ist + +Das OpenAPI-Schema ist die Grundlage für die beiden enthaltenen interaktiven Dokumentationssysteme. + +Es gibt dutzende Alternativen, die alle auf OpenAPI basieren. Sie können jede dieser Alternativen problemlos zu Ihrer mit **FastAPI** erstellten Anwendung hinzufügen. + +Ebenfalls können Sie es verwenden, um automatisch Code für Clients zu generieren, die mit Ihrer API kommunizieren. Zum Beispiel für Frontend-, Mobile- oder IoT-Anwendungen. + +## Rückblick, Schritt für Schritt + +### Schritt 1: Importieren von `FastAPI` + +```Python hl_lines="1" +{!../../../docs_src/first_steps/tutorial001.py!} +``` + +`FastAPI` ist eine Python-Klasse, die die gesamte Funktionalität für Ihre API bereitstellt. + +!!! note "Technische Details" + `FastAPI` ist eine Klasse, die direkt von `Starlette` erbt. + + Sie können alle Starlette-Funktionalitäten auch mit `FastAPI` nutzen. + +### Schritt 2: Erzeugen einer `FastAPI`-„Instanz“ + +```Python hl_lines="3" +{!../../../docs_src/first_steps/tutorial001.py!} +``` + +In diesem Beispiel ist die Variable `app` eine „Instanz“ der Klasse `FastAPI`. + +Dies wird der Hauptinteraktionspunkt für die Erstellung all Ihrer APIs sein. + +Die Variable `app` ist dieselbe, auf die sich der Befehl `uvicorn` bezieht: + +
+ +```console +$ uvicorn main:app --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Wenn Sie Ihre Anwendung wie folgt erstellen: + +```Python hl_lines="3" +{!../../../docs_src/first_steps/tutorial002.py!} +``` + +Und in eine Datei `main.py` einfügen, dann würden Sie `uvicorn` wie folgt aufrufen: + +
+ +```console +$ uvicorn main:my_awesome_api --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +### Schritt 3: Erstellen einer *Pfadoperation* + +#### Pfad + +„Pfad“ bezieht sich hier auf den letzten Teil der URL, beginnend mit dem ersten `/`. + +In einer URL wie: + +``` +https://example.com/items/foo +``` + +... wäre der Pfad folglich: + +``` +/items/foo +``` + +!!! info + Ein „Pfad“ wird häufig auch als „Endpunkt“ oder „Route“ bezeichnet. + +Bei der Erstellung einer API ist der „Pfad“ die wichtigste Möglichkeit zur Trennung von „Anliegen“ und „Ressourcen“. + +#### Operation + +„Operation“ bezieht sich hier auf eine der HTTP-„Methoden“. + +Eine von diesen: + +* `POST` +* `GET` +* `PUT` +* `DELETE` + +... und die etwas Exotischeren: + +* `OPTIONS` +* `HEAD` +* `PATCH` +* `TRACE` + +Im HTTP-Protokoll können Sie mit jedem Pfad über eine (oder mehrere) dieser „Methoden“ kommunizieren. + +--- + +Bei der Erstellung von APIs verwenden Sie normalerweise diese spezifischen HTTP-Methoden, um eine bestimmte Aktion durchzuführen. + +Normalerweise verwenden Sie: + +* `POST`: um Daten zu erzeugen (create). +* `GET`: um Daten zu lesen (read). +* `PUT`: um Daten zu aktualisieren (update). +* `DELETE`: um Daten zu löschen (delete). + +In OpenAPI wird folglich jede dieser HTTP-Methoden als „Operation“ bezeichnet. + +Wir werden sie auch „**Operationen**“ nennen. + +#### Definieren eines *Pfadoperation-Dekorators* + +```Python hl_lines="6" +{!../../../docs_src/first_steps/tutorial001.py!} +``` + +Das `@app.get("/")` sagt **FastAPI**, dass die Funktion direkt darunter für die Bearbeitung von Anfragen zuständig ist, die an: + + * den Pfad `/` + * unter der Verwendung der get-Operation gehen + +!!! info "`@decorator` Information" + Diese `@something`-Syntax wird in Python „Dekorator“ genannt. + + Sie platzieren ihn über einer Funktion. Wie ein hübscher, dekorativer Hut (daher kommt wohl der Begriff). + + Ein „Dekorator“ nimmt die darunter stehende Funktion und macht etwas damit. + + In unserem Fall teilt dieser Dekorator **FastAPI** mit, dass die folgende Funktion mit dem **Pfad** `/` und der **Operation** `get` zusammenhängt. + + Dies ist der „**Pfadoperation-Dekorator**“. + +Sie können auch die anderen Operationen verwenden: + +* `@app.post()` +* `@app.put()` +* `@app.delete()` + +Oder die exotischeren: + +* `@app.options()` +* `@app.head()` +* `@app.patch()` +* `@app.trace()` + +!!! tip "Tipp" + Es steht Ihnen frei, jede Operation (HTTP-Methode) so zu verwenden, wie Sie es möchten. + + **FastAPI** erzwingt keine bestimmte Bedeutung. + + Die hier aufgeführten Informationen dienen als Leitfaden und sind nicht verbindlich. + + Wenn Sie beispielsweise GraphQL verwenden, führen Sie normalerweise alle Aktionen nur mit „POST“-Operationen durch. + +### Schritt 4: Definieren der **Pfadoperation-Funktion** + +Das ist unsere „**Pfadoperation-Funktion**“: + +* **Pfad**: ist `/`. +* **Operation**: ist `get`. +* **Funktion**: ist die Funktion direkt unter dem „Dekorator“ (unter `@app.get("/")`). + +```Python hl_lines="7" +{!../../../docs_src/first_steps/tutorial001.py!} +``` + +Dies ist eine Python-Funktion. + +Sie wird von **FastAPI** immer dann aufgerufen, wenn sie eine Anfrage an die URL "`/`" mittels einer `GET`-Operation erhält. + +In diesem Fall handelt es sich um eine `async`-Funktion. + +--- + +Sie könnten sie auch als normale Funktion anstelle von `async def` definieren: + +```Python hl_lines="7" +{!../../../docs_src/first_steps/tutorial003.py!} +``` + +!!! note "Hinweis" + Wenn Sie den Unterschied nicht kennen, lesen Sie [Async: *„In Eile?“*](../async.md#in-eile){.internal-link target=_blank}. + +### Schritt 5: den Inhalt zurückgeben + +```Python hl_lines="8" +{!../../../docs_src/first_steps/tutorial001.py!} +``` + +Sie können ein `dict`, eine `list`, einzelne Werte wie `str`, `int`, usw. zurückgeben. + +Sie können auch Pydantic-Modelle zurückgeben (dazu später mehr). + +Es gibt viele andere Objekte und Modelle, die automatisch zu JSON konvertiert werden (einschließlich ORMs usw.). Versuchen Sie, Ihre Lieblingsobjekte zu verwenden. Es ist sehr wahrscheinlich, dass sie bereits unterstützt werden. + +## Zusammenfassung + +* Importieren Sie `FastAPI`. +* Erstellen Sie eine `app` Instanz. +* Schreiben Sie einen **Pfadoperation-Dekorator** (wie z. B. `@app.get("/")`). +* Schreiben Sie eine **Pfadoperation-Funktion** (wie z. B. oben `def root(): ...`). +* Starten Sie den Entwicklungsserver (z. B. `uvicorn main:app --reload`). diff --git a/docs/de/docs/tutorial/handling-errors.md b/docs/de/docs/tutorial/handling-errors.md new file mode 100644 index 0000000000000..af658b9715093 --- /dev/null +++ b/docs/de/docs/tutorial/handling-errors.md @@ -0,0 +1,259 @@ +# Fehlerbehandlung + +Es gibt viele Situationen, in denen Sie einem Client, der Ihre API benutzt, einen Fehler zurückgeben müssen. + +Dieser Client könnte ein Browser mit einem Frontend, Code von jemand anderem, ein IoT-Gerät, usw., sein. + +Sie müssten beispielsweise einem Client sagen: + +* Dass er nicht die notwendigen Berechtigungen hat, eine Aktion auszuführen. +* Dass er zu einer Ressource keinen Zugriff hat. +* Dass die Ressource, auf die er zugreifen möchte, nicht existiert. +* usw. + +In diesen Fällen geben Sie normalerweise einen **HTTP-Statuscode** im Bereich **400** (400 bis 499) zurück. + +Das ist vergleichbar mit den HTTP-Statuscodes im Bereich 200 (von 200 bis 299). Diese „200“er Statuscodes bedeuten, dass der Request in einem bestimmten Aspekt ein „Success“ („Erfolg“) war. + +Die Statuscodes im 400er-Bereich bedeuten hingegen, dass es einen Fehler gab. + +Erinnern Sie sich an all diese **404 Not Found** Fehler (und Witze)? + +## `HTTPException` verwenden + +Um HTTP-Responses mit Fehlern zum Client zurückzugeben, verwenden Sie `HTTPException`. + +### `HTTPException` importieren + +```Python hl_lines="1" +{!../../../docs_src/handling_errors/tutorial001.py!} +``` + +### Eine `HTTPException` in Ihrem Code auslösen + +`HTTPException` ist eine normale Python-Exception mit einigen zusätzlichen Daten, die für APIs relevant sind. + +Weil es eine Python-Exception ist, geben Sie sie nicht zurück, (`return`), sondern Sie lösen sie aus (`raise`). + +Das bedeutet auch, wenn Sie in einer Hilfsfunktion sind, die Sie von ihrer *Pfadoperation-Funktion* aus aufrufen, und Sie lösen eine `HTTPException` von innerhalb dieser Hilfsfunktion aus, dann wird der Rest der *Pfadoperation-Funktion* nicht ausgeführt, sondern der Request wird sofort abgebrochen und der HTTP-Error der `HTTP-Exception` wird zum Client gesendet. + +Der Vorteil, eine Exception auszulösen (`raise`), statt sie zurückzugeben (`return`) wird im Abschnitt über Abhängigkeiten und Sicherheit klarer werden. + +Im folgenden Beispiel lösen wir, wenn der Client eine ID anfragt, die nicht existiert, eine Exception mit dem Statuscode `404` aus. + +```Python hl_lines="11" +{!../../../docs_src/handling_errors/tutorial001.py!} +``` + +### Die resultierende Response + +Wenn der Client `http://example.com/items/foo` anfragt (ein `item_id` `"foo"`), erhält dieser Client einen HTTP-Statuscode 200 und folgende JSON-Response: + +```JSON +{ + "item": "The Foo Wrestlers" +} +``` + +Aber wenn der Client `http://example.com/items/bar` anfragt (ein nicht-existierendes `item_id` `"bar"`), erhält er einen HTTP-Statuscode 404 (der „Not Found“-Fehler), und eine JSON-Response wie folgt: + +```JSON +{ + "detail": "Item not found" +} +``` + +!!! tip "Tipp" + Wenn Sie eine `HTTPException` auslösen, können Sie dem Parameter `detail` jeden Wert übergeben, der nach JSON konvertiert werden kann, nicht nur `str`. + + Zum Beispiel ein `dict`, eine `list`, usw. + + Das wird automatisch von **FastAPI** gehandhabt und der Wert nach JSON konvertiert. + +## Benutzerdefinierte Header hinzufügen + +Es gibt Situationen, da ist es nützlich, dem HTTP-Error benutzerdefinierte Header hinzufügen zu können, etwa in einigen Sicherheitsszenarien. + +Sie müssen das wahrscheinlich nicht direkt in ihrem Code verwenden. + +Aber falls es in einem fortgeschrittenen Szenario notwendig ist, können Sie benutzerdefinierte Header wie folgt hinzufügen: + +```Python hl_lines="14" +{!../../../docs_src/handling_errors/tutorial002.py!} +``` + +## Benutzerdefinierte Exceptionhandler definieren + +Sie können benutzerdefinierte Exceptionhandler hinzufügen, mithilfe derselben Werkzeuge für Exceptions von Starlette. + +Nehmen wir an, Sie haben eine benutzerdefinierte Exception `UnicornException`, die Sie (oder eine Bibliothek, die Sie verwenden) `raise`n könnten. + +Und Sie möchten diese Exception global mit FastAPI handhaben. + +Sie könnten einen benutzerdefinierten Exceptionhandler mittels `@app.exception_handler()` hinzufügen: + +```Python hl_lines="5-7 13-18 24" +{!../../../docs_src/handling_errors/tutorial003.py!} +``` + +Wenn Sie nun `/unicorns/yolo` anfragen, `raise`d die *Pfadoperation* eine `UnicornException`. + +Aber diese wird von `unicorn_exception_handler` gehandhabt. + +Sie erhalten also einen sauberen Error mit einem Statuscode `418` und dem JSON-Inhalt: + +```JSON +{"message": "Oops! yolo did something. There goes a rainbow..."} +``` + +!!! note "Technische Details" + Sie können auch `from starlette.requests import Request` und `from starlette.responses import JSONResponse` verwenden. + + **FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. Das Gleiche gilt für `Request`. + +## Die Default-Exceptionhandler überschreiben + +**FastAPI** hat einige Default-Exceptionhandler. + +Diese Handler kümmern sich darum, Default-JSON-Responses zurückzugeben, wenn Sie eine `HTTPException` `raise`n, und wenn der Request ungültige Daten enthält. + +Sie können diese Exceptionhandler mit ihren eigenen überschreiben. + +### Requestvalidierung-Exceptions überschreiben + +Wenn ein Request ungültige Daten enthält, löst **FastAPI** intern einen `RequestValidationError` aus. + +Und bietet auch einen Default-Exceptionhandler dafür. + +Um diesen zu überschreiben, importieren Sie den `RequestValidationError` und verwenden Sie ihn in `@app.exception_handler(RequestValidationError)`, um Ihren Exceptionhandler zu dekorieren. + +Der Exceptionhandler wird einen `Request` und die Exception entgegennehmen. + +```Python hl_lines="2 14-16" +{!../../../docs_src/handling_errors/tutorial004.py!} +``` + +Wenn Sie nun `/items/foo` besuchen, erhalten Sie statt des Default-JSON-Errors: + +```JSON +{ + "detail": [ + { + "loc": [ + "path", + "item_id" + ], + "msg": "value is not a valid integer", + "type": "type_error.integer" + } + ] +} +``` + +eine Textversion: + +``` +1 validation error +path -> item_id + value is not a valid integer (type=type_error.integer) +``` + +#### `RequestValidationError` vs. `ValidationError` + +!!! warning "Achtung" + Das folgende sind technische Details, die Sie überspringen können, wenn sie für Sie nicht wichtig sind. + +`RequestValidationError` ist eine Unterklasse von Pydantics `ValidationError`. + +**FastAPI** verwendet diesen, sodass Sie, wenn Sie ein Pydantic-Modell für `response_model` verwenden, und ihre Daten fehlerhaft sind, einen Fehler in ihrem Log sehen. + +Aber der Client/Benutzer sieht ihn nicht. Stattdessen erhält der Client einen „Internal Server Error“ mit einem HTTP-Statuscode `500`. + +Das ist, wie es sein sollte, denn wenn Sie einen Pydantic-`ValidationError` in Ihrer *Response* oder irgendwo sonst in ihrem Code haben (es sei denn, im *Request* des Clients), ist das tatsächlich ein Bug in ihrem Code. + +Und während Sie den Fehler beheben, sollten ihre Clients/Benutzer keinen Zugriff auf interne Informationen über den Fehler haben, da das eine Sicherheitslücke aufdecken könnte. + +### den `HTTPException`-Handler überschreiben + +Genauso können Sie den `HTTPException`-Handler überschreiben. + +Zum Beispiel könnten Sie eine Klartext-Response statt JSON für diese Fehler zurückgeben wollen: + +```Python hl_lines="3-4 9-11 22" +{!../../../docs_src/handling_errors/tutorial004.py!} +``` + +!!! note "Technische Details" + Sie können auch `from starlette.responses import PlainTextResponse` verwenden. + + **FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. + +### Den `RequestValidationError`-Body verwenden + +Der `RequestValidationError` enthält den empfangenen `body` mit den ungültigen Daten. + +Sie könnten diesen verwenden, während Sie Ihre Anwendung entwickeln, um den Body zu loggen und zu debuggen, ihn zum Benutzer zurückzugeben, usw. + +```Python hl_lines="14" +{!../../../docs_src/handling_errors/tutorial005.py!} +``` + +Jetzt versuchen Sie, einen ungültigen Artikel zu senden: + +```JSON +{ + "title": "towel", + "size": "XL" +} +``` + +Sie erhalten eine Response, die Ihnen sagt, dass die Daten ungültig sind, und welche den empfangenen Body enthält. + +```JSON hl_lines="12-15" +{ + "detail": [ + { + "loc": [ + "body", + "size" + ], + "msg": "value is not a valid integer", + "type": "type_error.integer" + } + ], + "body": { + "title": "towel", + "size": "XL" + } +} +``` + +#### FastAPIs `HTTPException` vs. Starlettes `HTTPException` + +**FastAPI** hat seine eigene `HTTPException`. + +Und **FastAPI**s `HTTPException`-Fehlerklasse erbt von Starlettes `HTTPException`-Fehlerklasse. + +Der einzige Unterschied besteht darin, dass **FastAPIs** `HTTPException` alles für das Feld `detail` akzeptiert, was nach JSON konvertiert werden kann, während Starlettes `HTTPException` nur Strings zulässt. + +Sie können also weiterhin **FastAPI**s `HTTPException` wie üblich in Ihrem Code auslösen. + +Aber wenn Sie einen Exceptionhandler registrieren, registrieren Sie ihn für Starlettes `HTTPException`. + +Auf diese Weise wird Ihr Handler, wenn irgendein Teil von Starlettes internem Code, oder eine Starlette-Erweiterung, oder -Plugin eine Starlette-`HTTPException` auslöst, in der Lage sein, diese zu fangen und zu handhaben. + +Damit wir in diesem Beispiel beide `HTTPException`s im selben Code haben können, benennen wir Starlettes Exception um zu `StarletteHTTPException`: + +```Python +from starlette.exceptions import HTTPException as StarletteHTTPException +``` + +### **FastAPI**s Exceptionhandler wiederverwenden + +Wenn Sie die Exception zusammen mit denselben Default-Exceptionhandlern von **FastAPI** verwenden möchten, können Sie die Default-Exceptionhandler von `fastapi.Exception_handlers` importieren und wiederverwenden: + +```Python hl_lines="2-5 15 21" +{!../../../docs_src/handling_errors/tutorial006.py!} +``` + +In diesem Beispiel `print`en Sie nur den Fehler mit einer sehr ausdrucksstarken Nachricht, aber Sie sehen, worauf wir hinauswollen. Sie können mit der Exception etwas machen und dann einfach die Default-Exceptionhandler wiederverwenden. diff --git a/docs/de/docs/tutorial/header-params.md b/docs/de/docs/tutorial/header-params.md new file mode 100644 index 0000000000000..3c9807f47ba83 --- /dev/null +++ b/docs/de/docs/tutorial/header-params.md @@ -0,0 +1,227 @@ +# Header-Parameter + +So wie `Query`-, `Path`-, und `Cookie`-Parameter können Sie auch Header-Parameter definieren. + +## `Header` importieren + +Importieren Sie zuerst `Header`: + +=== "Python 3.10+" + + ```Python hl_lines="3" + {!> ../../../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.8+" + + ```Python hl_lines="3" + {!> ../../../docs_src/header_params/tutorial001_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="1" + {!> ../../../docs_src/header_params/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="3" + {!> ../../../docs_src/header_params/tutorial001.py!} + ``` + +## `Header`-Parameter deklarieren + +Dann deklarieren Sie Ihre Header-Parameter, auf die gleiche Weise, wie Sie auch `Path`-, `Query`-, und `Cookie`-Parameter deklarieren. + +Der erste Wert ist der Typ. Sie können `Header` die gehabten Extra Validierungs- und Beschreibungsparameter hinzufügen. Danach können Sie einen Defaultwert vergeben: + +=== "Python 3.10+" + + ```Python hl_lines="9" + {!> ../../../docs_src/header_params/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="9" + {!> ../../../docs_src/header_params/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="10" + {!> ../../../docs_src/header_params/tutorial001_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="7" + {!> ../../../docs_src/header_params/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="9" + {!> ../../../docs_src/header_params/tutorial001.py!} + ``` + +!!! note "Technische Details" + `Header` ist eine Schwesterklasse von `Path`, `Query` und `Cookie`. Sie erbt von derselben gemeinsamen `Param`-Elternklasse. + + Aber erinnern Sie sich, dass, wenn Sie `Query`, `Path`, `Header` und andere von `fastapi` importieren, diese tatsächlich Funktionen sind, welche spezielle Klassen zurückgeben. + +!!! info + Um Header zu deklarieren, müssen Sie `Header` verwenden, da diese Parameter sonst als Query-Parameter interpretiert werden würden. + +## Automatische Konvertierung + +`Header` hat weitere Funktionalität, zusätzlich zu der, die `Path`, `Query` und `Cookie` bereitstellen. + +Die meisten Standard-Header benutzen als Trennzeichen einen Bindestrich, auch bekannt als das „Minus-Symbol“ (`-`). + +Aber eine Variable wie `user-agent` ist in Python nicht gültig. + +Darum wird `Header` standardmäßig in Parameternamen den Unterstrich (`_`) zu einem Bindestrich (`-`) konvertieren. + +HTTP-Header sind außerdem unabhängig von Groß-/Kleinschreibung, darum können Sie sie mittels der Standard-Python-Schreibweise deklarieren (auch bekannt als "snake_case"). + +Sie können also `user_agent` schreiben, wie Sie es normalerweise in Python-Code machen würden, statt etwa die ersten Buchstaben groß zu schreiben, wie in `User_Agent`. + +Wenn Sie aus irgendeinem Grund das automatische Konvertieren von Unterstrichen zu Bindestrichen abschalten möchten, setzen Sie den Parameter `convert_underscores` auf `False`. + +=== "Python 3.10+" + + ```Python hl_lines="10" + {!> ../../../docs_src/header_params/tutorial002_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="11" + {!> ../../../docs_src/header_params/tutorial002_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="12" + {!> ../../../docs_src/header_params/tutorial002_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="8" + {!> ../../../docs_src/header_params/tutorial002_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="10" + {!> ../../../docs_src/header_params/tutorial002.py!} + ``` + +!!! warning "Achtung" + Bevor Sie `convert_underscores` auf `False` setzen, bedenken Sie, dass manche HTTP-Proxys und Server die Verwendung von Headern mit Unterstrichen nicht erlauben. + +## Doppelte Header + +Es ist möglich, doppelte Header zu empfangen. Also den gleichen Header mit unterschiedlichen Werten. + +Sie können solche Fälle deklarieren, indem Sie in der Typdeklaration eine Liste verwenden. + +Sie erhalten dann alle Werte von diesem doppelten Header als Python-`list`e. + +Um zum Beispiel einen Header `X-Token` zu deklarieren, der mehrmals vorkommen kann, schreiben Sie: + +=== "Python 3.10+" + + ```Python hl_lines="9" + {!> ../../../docs_src/header_params/tutorial003_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="9" + {!> ../../../docs_src/header_params/tutorial003_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="10" + {!> ../../../docs_src/header_params/tutorial003_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="7" + {!> ../../../docs_src/header_params/tutorial003_py310.py!} + ``` + +=== "Python 3.9+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="9" + {!> ../../../docs_src/header_params/tutorial003_py39.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="9" + {!> ../../../docs_src/header_params/tutorial003.py!} + ``` + +Wenn Sie mit einer *Pfadoperation* kommunizieren, die zwei HTTP-Header sendet, wie: + +``` +X-Token: foo +X-Token: bar +``` + +Dann wäre die Response: + +```JSON +{ + "X-Token values": [ + "bar", + "foo" + ] +} +``` + +## Zusammenfassung + +Deklarieren Sie Header mittels `Header`, auf die gleiche Weise wie bei `Query`, `Path` und `Cookie`. + +Machen Sie sich keine Sorgen um Unterstriche in ihren Variablen, **FastAPI** wird sich darum kümmern, diese zu konvertieren. diff --git a/docs/de/docs/tutorial/index.md b/docs/de/docs/tutorial/index.md new file mode 100644 index 0000000000000..93a30d1b37898 --- /dev/null +++ b/docs/de/docs/tutorial/index.md @@ -0,0 +1,80 @@ +# Tutorial – Benutzerhandbuch + +Dieses Tutorial zeigt Ihnen Schritt für Schritt, wie Sie **FastAPI** und die meisten seiner Funktionen verwenden können. + +Jeder Abschnitt baut schrittweise auf den vorhergehenden auf. Diese Abschnitte sind aber nach einzelnen Themen gegliedert, sodass Sie direkt zu einem bestimmten Thema übergehen können, um Ihre speziellen API-Anforderungen zu lösen. + +Außerdem dienen diese als zukünftige Referenz. + +Dadurch können Sie jederzeit zurückkommen und sehen genau das, was Sie benötigen. + +## Den Code ausführen + +Alle Codeblöcke können kopiert und direkt verwendet werden (da es sich um getestete Python-Dateien handelt). + +Um eines der Beispiele auszuführen, kopieren Sie den Code in eine Datei `main.py`, und starten Sie `uvicorn` mit: + +
+ +```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. +``` + +
+ +Es wird **ausdrücklich empfohlen**, dass Sie den Code schreiben oder kopieren, ihn bearbeiten und lokal ausführen. + +Die Verwendung in Ihrem eigenen Editor zeigt Ihnen die Vorteile von FastAPI am besten, wenn Sie sehen, wie wenig Code Sie schreiben müssen, all die Typprüfungen, die automatische Vervollständigung usw. + +--- + +## FastAPI installieren + +Der erste Schritt besteht aus der Installation von FastAPI. + +Für dieses Tutorial empfiehlt es sich, FastAPI mit allen optionalen Abhängigkeiten und Funktionen zu installieren: + +
+ +```console +$ pip install "fastapi[all]" + +---> 100% +``` + +
+ +... das beinhaltet auch `uvicorn`, welchen Sie als Server verwenden können, der ihren Code ausführt. + +!!! note "Hinweis" + Sie können die einzelnen Teile auch separat installieren. + + Das folgende würden Sie wahrscheinlich tun, wenn Sie Ihre Anwendung in der Produktion einsetzen: + + ``` + pip install fastapi + ``` + + Installieren Sie auch `uvicorn` als Server: + + ``` + pip install "uvicorn[standard]" + ``` + + Das gleiche gilt für jede der optionalen Abhängigkeiten, die Sie verwenden möchten. + +## Handbuch für fortgeschrittene Benutzer + +Es gibt auch ein **Handbuch für fortgeschrittene Benutzer**, welches Sie später nach diesem **Tutorial – Benutzerhandbuch** lesen können. + +Das **Handbuch für fortgeschrittene Benutzer** baut auf diesem Tutorial auf, verwendet dieselben Konzepte und bringt Ihnen einige zusätzliche Funktionen bei. + +Allerdings sollten Sie zuerst das **Tutorial – Benutzerhandbuch** lesen (was Sie hier gerade tun). + +Die Dokumentation ist so konzipiert, dass Sie mit dem **Tutorial – Benutzerhandbuch** eine vollständige Anwendung erstellen können und diese dann je nach Bedarf mit einigen der zusätzlichen Ideen aus dem **Handbuch für fortgeschrittene Benutzer** vervollständigen können. diff --git a/docs/de/docs/tutorial/metadata.md b/docs/de/docs/tutorial/metadata.md new file mode 100644 index 0000000000000..2061e2a5b15bf --- /dev/null +++ b/docs/de/docs/tutorial/metadata.md @@ -0,0 +1,123 @@ +# Metadaten und URLs der Dokumentationen + +Sie können mehrere Metadaten-Einstellungen für Ihre **FastAPI**-Anwendung konfigurieren. + +## Metadaten für die API + +Sie können die folgenden Felder festlegen, welche in der OpenAPI-Spezifikation und den Benutzeroberflächen der automatischen API-Dokumentation verwendet werden: + +| Parameter | Typ | Beschreibung | +|------------|------|-------------| +| `title` | `str` | Der Titel der API. | +| `summary` | `str` | Eine kurze Zusammenfassung der API. Verfügbar seit OpenAPI 3.1.0, FastAPI 0.99.0. | +| `description` | `str` | Eine kurze Beschreibung der API. Kann Markdown verwenden. | +| `version` | `string` | Die Version der API. Das ist die Version Ihrer eigenen Anwendung, nicht die von OpenAPI. Zum Beispiel `2.5.0`. | +| `terms_of_service` | `str` | Eine URL zu den Nutzungsbedingungen für die API. Falls angegeben, muss es sich um eine URL handeln. | +| `contact` | `dict` | Die Kontaktinformationen für die verfügbar gemachte API. Kann mehrere Felder enthalten.
contact-Felder
ParameterTypBeschreibung
namestrDer identifizierende Name der Kontaktperson/Organisation.
urlstrDie URL, die auf die Kontaktinformationen verweist. MUSS im Format einer URL vorliegen.
emailstrDie E-Mail-Adresse der Kontaktperson/Organisation. MUSS im Format einer E-Mail-Adresse vorliegen.
| +| `license_info` | `dict` | Die Lizenzinformationen für die verfügbar gemachte API. Kann mehrere Felder enthalten.
license_info-Felder
ParameterTypBeschreibung
namestrERFORDERLICH (wenn eine license_info festgelegt ist). Der für die API verwendete Lizenzname.
identifierstrEin SPDX-Lizenzausdruck für die API. Das Feld identifier und das Feld url schließen sich gegenseitig aus. Verfügbar seit OpenAPI 3.1.0, FastAPI 0.99.0.
urlstrEine URL zur Lizenz, die für die API verwendet wird. MUSS im Format einer URL vorliegen.
| + +Sie können diese wie folgt setzen: + +```Python hl_lines="3-16 19-32" +{!../../../docs_src/metadata/tutorial001.py!} +``` + +!!! tip "Tipp" + Sie können Markdown in das Feld `description` schreiben und es wird in der Ausgabe gerendert. + +Mit dieser Konfiguration würde die automatische API-Dokumentation wie folgt aussehen: + + + +## Lizenz-ID + +Seit OpenAPI 3.1.0 und FastAPI 0.99.0 können Sie die `license_info` auch mit einem `identifier` anstelle einer `url` festlegen. + +Zum Beispiel: + +```Python hl_lines="31" +{!../../../docs_src/metadata/tutorial001_1.py!} +``` + +## Metadaten für Tags + +Sie können mit dem Parameter `openapi_tags` auch zusätzliche Metadaten für die verschiedenen Tags hinzufügen, die zum Gruppieren Ihrer Pfadoperationen verwendet werden. + +Es wird eine Liste benötigt, die für jedes Tag ein Dict enthält. + +Jedes Dict kann Folgendes enthalten: + +* `name` (**erforderlich**): ein `str` mit demselben Tag-Namen, den Sie im Parameter `tags` in Ihren *Pfadoperationen* und `APIRouter`n verwenden. +* `description`: ein `str` mit einer kurzen Beschreibung für das Tag. Sie kann Markdown enthalten und wird in der Benutzeroberfläche der Dokumentation angezeigt. +* `externalDocs`: ein `dict`, das externe Dokumentation beschreibt mit: + * `description`: ein `str` mit einer kurzen Beschreibung für die externe Dokumentation. + * `url` (**erforderlich**): ein `str` mit der URL für die externe Dokumentation. + +### Metadaten für Tags erstellen + +Versuchen wir das an einem Beispiel mit Tags für `users` und `items`. + +Erstellen Sie Metadaten für Ihre Tags und übergeben Sie sie an den Parameter `openapi_tags`: + +```Python hl_lines="3-16 18" +{!../../../docs_src/metadata/tutorial004.py!} +``` + +Beachten Sie, dass Sie Markdown in den Beschreibungen verwenden können. Beispielsweise wird „login“ in Fettschrift (**login**) und „fancy“ in Kursivschrift (_fancy_) angezeigt. + +!!! tip "Tipp" + Sie müssen nicht für alle von Ihnen verwendeten Tags Metadaten hinzufügen. + +### Ihre Tags verwenden + +Verwenden Sie den Parameter `tags` mit Ihren *Pfadoperationen* (und `APIRouter`n), um diese verschiedenen Tags zuzuweisen: + +```Python hl_lines="21 26" +{!../../../docs_src/metadata/tutorial004.py!} +``` + +!!! info + Lesen Sie mehr zu Tags unter [Pfadoperation-Konfiguration](path-operation-configuration.md#tags){.internal-link target=_blank}. + +### Die Dokumentation anschauen + +Wenn Sie nun die Dokumentation ansehen, werden dort alle zusätzlichen Metadaten angezeigt: + + + +### Reihenfolge der Tags + +Die Reihenfolge der Tag-Metadaten-Dicts definiert auch die Reihenfolge, in der diese in der Benutzeroberfläche der Dokumentation angezeigt werden. + +Auch wenn beispielsweise `users` im Alphabet nach `items` kommt, wird es vor diesen angezeigt, da wir seine Metadaten als erstes Dict der Liste hinzugefügt haben. + +## OpenAPI-URL + +Standardmäßig wird das OpenAPI-Schema unter `/openapi.json` bereitgestellt. + +Sie können das aber mit dem Parameter `openapi_url` konfigurieren. + +Um beispielsweise festzulegen, dass es unter `/api/v1/openapi.json` bereitgestellt wird: + +```Python hl_lines="3" +{!../../../docs_src/metadata/tutorial002.py!} +``` + +Wenn Sie das OpenAPI-Schema vollständig deaktivieren möchten, können Sie `openapi_url=None` festlegen, wodurch auch die Dokumentationsbenutzeroberflächen deaktiviert werden, die es verwenden. + +## URLs der Dokumentationen + +Sie können die beiden enthaltenen Dokumentationsbenutzeroberflächen konfigurieren: + +* **Swagger UI**: bereitgestellt unter `/docs`. + * Sie können deren URL mit dem Parameter `docs_url` festlegen. + * Sie können sie deaktivieren, indem Sie `docs_url=None` festlegen. +* **ReDoc**: bereitgestellt unter `/redoc`. + * Sie können deren URL mit dem Parameter `redoc_url` festlegen. + * Sie können sie deaktivieren, indem Sie `redoc_url=None` festlegen. + +Um beispielsweise Swagger UI so einzustellen, dass sie unter `/documentation` bereitgestellt wird, und ReDoc zu deaktivieren: + +```Python hl_lines="3" +{!../../../docs_src/metadata/tutorial003.py!} +``` diff --git a/docs/de/docs/tutorial/middleware.md b/docs/de/docs/tutorial/middleware.md new file mode 100644 index 0000000000000..7d6e6b71a36b2 --- /dev/null +++ b/docs/de/docs/tutorial/middleware.md @@ -0,0 +1,61 @@ +# Middleware + +Sie können Middleware zu **FastAPI**-Anwendungen hinzufügen. + +Eine „Middleware“ ist eine Funktion, die mit jedem **Request** arbeitet, bevor er von einer bestimmten *Pfadoperation* verarbeitet wird. Und auch mit jeder **Response**, bevor sie zurückgegeben wird. + +* Sie nimmt jeden **Request** entgegen, der an Ihre Anwendung gesendet wird. +* Sie kann dann etwas mit diesem **Request** tun oder beliebigen Code ausführen. +* Dann gibt sie den **Request** zur Verarbeitung durch den Rest der Anwendung weiter (durch eine bestimmte *Pfadoperation*). +* Sie nimmt dann die **Response** entgegen, die von der Anwendung generiert wurde (durch eine bestimmte *Pfadoperation*). +* Sie kann etwas mit dieser **Response** tun oder beliebigen Code ausführen. +* Dann gibt sie die **Response** zurück. + +!!! note "Technische Details" + Wenn Sie Abhängigkeiten mit `yield` haben, wird der Exit-Code *nach* der Middleware ausgeführt. + + Wenn es Hintergrundaufgaben gab (später dokumentiert), werden sie *nach* allen Middlewares ausgeführt. + +## Erstellung einer Middleware + +Um eine Middleware zu erstellen, verwenden Sie den Dekorator `@app.middleware("http")` über einer Funktion. + +Die Middleware-Funktion erhält: + +* Den `request`. +* Eine Funktion `call_next`, die den `request` als Parameter erhält. + * Diese Funktion gibt den `request` an die entsprechende *Pfadoperation* weiter. + * Dann gibt es die von der entsprechenden *Pfadoperation* generierte `response` zurück. +* Sie können die `response` dann weiter modifizieren, bevor Sie sie zurückgeben. + +```Python hl_lines="8-9 11 14" +{!../../../docs_src/middleware/tutorial001.py!} +``` + +!!! tip "Tipp" + Beachten Sie, dass benutzerdefinierte proprietäre Header hinzugefügt werden können. Verwenden Sie dafür das Präfix 'X-'. + + Wenn Sie jedoch benutzerdefinierte Header haben, die ein Client in einem Browser sehen soll, müssen Sie sie zu Ihrer CORS-Konfigurationen ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) hinzufügen, indem Sie den Parameter `expose_headers` verwenden, der in der Starlette-CORS-Dokumentation dokumentiert ist. + +!!! note "Technische Details" + Sie könnten auch `from starlette.requests import Request` verwenden. + + **FastAPI** bietet es als Komfort für Sie, den Entwickler, an. Aber es stammt direkt von Starlette. + +### Vor und nach der `response` + +Sie können Code hinzufügen, der mit dem `request` ausgeführt wird, bevor dieser von einer beliebigen *Pfadoperation* empfangen wird. + +Und auch nachdem die `response` generiert wurde, bevor sie zurückgegeben wird. + +Sie könnten beispielsweise einen benutzerdefinierten Header `X-Process-Time` hinzufügen, der die Zeit in Sekunden enthält, die benötigt wurde, um den Request zu verarbeiten und eine Response zu generieren: + +```Python hl_lines="10 12-13" +{!../../../docs_src/middleware/tutorial001.py!} +``` + +## Andere Middlewares + +Sie können später mehr über andere Middlewares in [Handbuch für fortgeschrittene Benutzer: Fortgeschrittene Middleware](../advanced/middleware.md){.internal-link target=_blank} lesen. + +In der nächsten Sektion erfahren Sie, wie Sie CORS mit einer Middleware behandeln können. diff --git a/docs/de/docs/tutorial/path-operation-configuration.md b/docs/de/docs/tutorial/path-operation-configuration.md new file mode 100644 index 0000000000000..80a4fadc90115 --- /dev/null +++ b/docs/de/docs/tutorial/path-operation-configuration.md @@ -0,0 +1,179 @@ +# Pfadoperation-Konfiguration + +Es gibt mehrere Konfigurations-Parameter, die Sie Ihrem *Pfadoperation-Dekorator* übergeben können. + +!!! warning "Achtung" + Beachten Sie, dass diese Parameter direkt dem *Pfadoperation-Dekorator* übergeben werden, nicht der *Pfadoperation-Funktion*. + +## Response-Statuscode + +Sie können den (HTTP-)`status_code` definieren, den die Response Ihrer *Pfadoperation* verwenden soll. + +Sie können direkt den `int`-Code übergeben, etwa `404`. + +Aber falls Sie sich nicht mehr erinnern, wofür jede Nummer steht, können Sie die Abkürzungs-Konstanten in `status` verwenden: + +=== "Python 3.10+" + + ```Python hl_lines="1 15" + {!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="3 17" + {!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="3 17" + {!> ../../../docs_src/path_operation_configuration/tutorial001.py!} + ``` + +Dieser Statuscode wird in der Response verwendet und zum OpenAPI-Schema hinzugefügt. + +!!! note "Technische Details" + Sie können auch `from starlette import status` verwenden. + + **FastAPI** bietet dieselben `starlette.status`-Codes auch via `fastapi.status` an, als Annehmlichkeit für Sie, den Entwickler. Sie kommen aber direkt von Starlette. + +## Tags + +Sie können Ihrer *Pfadoperation* Tags hinzufügen, mittels des Parameters `tags`, dem eine `list`e von `str`s übergeben wird (in der Regel nur ein `str`): + +=== "Python 3.10+" + + ```Python hl_lines="15 20 25" + {!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="17 22 27" + {!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="17 22 27" + {!> ../../../docs_src/path_operation_configuration/tutorial002.py!} + ``` + +Diese werden zum OpenAPI-Schema hinzugefügt und von den automatischen Dokumentations-Benutzeroberflächen verwendet: + + + +### Tags mittels Enumeration + +Wenn Sie eine große Anwendung haben, können sich am Ende **viele Tags** anhäufen, und Sie möchten sicherstellen, dass Sie für verwandte *Pfadoperationen* immer den **gleichen Tag** nehmen. + +In diesem Fall macht es Sinn, die Tags in einem `Enum` zu speichern. + +**FastAPI** unterstützt diese genauso wie einfache Strings: + +```Python hl_lines="1 8-10 13 18" +{!../../../docs_src/path_operation_configuration/tutorial002b.py!} +``` + +## Zusammenfassung und Beschreibung + +Sie können eine Zusammenfassung (`summary`) und eine Beschreibung (`description`) hinzufügen: + +=== "Python 3.10+" + + ```Python hl_lines="18-19" + {!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="20-21" + {!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="20-21" + {!> ../../../docs_src/path_operation_configuration/tutorial003.py!} + ``` + +## Beschreibung mittels Docstring + +Da Beschreibungen oft mehrere Zeilen lang sind, können Sie die Beschreibung der *Pfadoperation* im Docstring der Funktion deklarieren, und **FastAPI** wird sie daraus auslesen. + +Sie können im Docstring Markdown schreiben, es wird korrekt interpretiert und angezeigt (die Einrückung des Docstring beachtend). + +=== "Python 3.10+" + + ```Python hl_lines="17-25" + {!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="19-27" + {!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="19-27" + {!> ../../../docs_src/path_operation_configuration/tutorial004.py!} + ``` + +In der interaktiven Dokumentation sieht das dann so aus: + + + +## Beschreibung der Response + +Die Response können Sie mit dem Parameter `response_description` beschreiben: + +=== "Python 3.10+" + + ```Python hl_lines="19" + {!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="21" + {!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="21" + {!> ../../../docs_src/path_operation_configuration/tutorial005.py!} + ``` + +!!! info + beachten Sie, dass sich `response_description` speziell auf die Response bezieht, während `description` sich generell auf die *Pfadoperation* bezieht. + +!!! check + OpenAPI verlangt, dass jede *Pfadoperation* über eine Beschreibung der Response verfügt. + + Daher, wenn Sie keine vergeben, wird **FastAPI** automatisch eine für „Erfolgreiche Response“ erstellen. + + + +## Eine *Pfadoperation* deprecaten + +Wenn Sie eine *Pfadoperation* als deprecated kennzeichnen möchten, ohne sie zu entfernen, fügen Sie den Parameter `deprecated` hinzu: + +```Python hl_lines="16" +{!../../../docs_src/path_operation_configuration/tutorial006.py!} +``` + +Sie wird in der interaktiven Dokumentation gut sichtbar als deprecated markiert werden: + + + +Vergleichen Sie, wie deprecatete und nicht-deprecatete *Pfadoperationen* aussehen: + + + +## Zusammenfassung + +Sie können auf einfache Weise Metadaten für Ihre *Pfadoperationen* definieren, indem Sie den *Pfadoperation-Dekoratoren* Parameter hinzufügen. diff --git a/docs/de/docs/tutorial/path-params-numeric-validations.md b/docs/de/docs/tutorial/path-params-numeric-validations.md new file mode 100644 index 0000000000000..aa3b59b8b2586 --- /dev/null +++ b/docs/de/docs/tutorial/path-params-numeric-validations.md @@ -0,0 +1,293 @@ +# Pfad-Parameter und Validierung von Zahlen + +So wie Sie mit `Query` für Query-Parameter zusätzliche Validierungen und Metadaten hinzufügen können, können Sie das mittels `Path` auch für Pfad-Parameter tun. + +## `Path` importieren + +Importieren Sie zuerst `Path` von `fastapi`, und importieren Sie `Annotated`. + +=== "Python 3.10+" + + ```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.8+" + + ```Python hl_lines="3-4" + {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="1" + {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="3" + {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} + ``` + +!!! info + FastAPI unterstützt (und empfiehlt die Verwendung von) `Annotated` seit Version 0.95.0. + + Wenn Sie eine ältere Version haben, werden Sie Fehler angezeigt bekommen, wenn Sie versuchen, `Annotated` zu verwenden. + + Bitte [aktualisieren Sie FastAPI](../deployment/versions.md#upgrade-der-fastapi-versionen){.internal-link target=_blank} daher mindestens zu Version 0.95.1, bevor Sie `Annotated` verwenden. + +## Metadaten deklarieren + +Sie können die gleichen Parameter deklarieren wie für `Query`. + +Um zum Beispiel einen `title`-Metadaten-Wert für den Pfad-Parameter `item_id` zu deklarieren, schreiben Sie: + +=== "Python 3.10+" + + ```Python hl_lines="10" + {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="10" + {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="11" + {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="8" + {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="10" + {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} + ``` + +!!! note "Hinweis" + Ein Pfad-Parameter ist immer erforderlich, weil er Teil des Pfads sein muss. + + Sie sollten ihn daher mit `...` deklarieren, um ihn als erforderlich auszuzeichnen. + + Doch selbst wenn Sie ihn mit `None` deklarieren, oder einen Defaultwert setzen, bewirkt das nichts, er bleibt immer erforderlich. + +## Sortieren Sie die Parameter, wie Sie möchten + +!!! tip "Tipp" + Wenn Sie `Annotated` verwenden, ist das folgende nicht so wichtig / nicht notwendig. + +Nehmen wir an, Sie möchten den Query-Parameter `q` als erforderlichen `str` deklarieren. + +Und Sie müssen sonst nichts anderes für den Parameter deklarieren, Sie brauchen also nicht wirklich `Query`. + +Aber Sie brauchen `Path` für den `item_id`-Pfad-Parameter. Und Sie möchten aus irgendeinem Grund nicht `Annotated` verwenden. + +Python wird sich beschweren, wenn Sie einen Parameter mit Defaultwert vor einen Parameter ohne Defaultwert setzen. + +Aber Sie können die Reihenfolge der Parameter ändern, den Query-Parameter ohne Defaultwert zuerst. + +Für **FastAPI** ist es nicht wichtig. Es erkennt die Parameter anhand ihres Namens, ihrer Typen, und ihrer Defaultwerte (`Query`, `Path`, usw.). Es kümmert sich nicht um die Reihenfolge. + +Sie können Ihre Funktion also so deklarieren: + +=== "Python 3.8 nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="7" + {!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!} + ``` + +Aber bedenken Sie, dass Sie dieses Problem nicht haben, wenn Sie `Annotated` verwenden, da Sie nicht die Funktions-Parameter-Defaultwerte für `Query()` oder `Path()` verwenden. + +=== "Python 3.9+" + + ```Python hl_lines="10" + {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9" + {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!} + ``` + +## Sortieren Sie die Parameter wie Sie möchten: Tricks + +!!! tip "Tipp" + Wenn Sie `Annotated` verwenden, ist das folgende nicht so wichtig / nicht notwendig. + +Hier ein **kleiner Trick**, der nützlich sein kann, aber Sie werden ihn nicht oft brauchen. + +Wenn Sie eines der folgenden Dinge tun möchten: + +* den `q`-Parameter ohne `Query` oder irgendeinem Defaultwert deklarieren +* den Pfad-Parameter `item_id` mittels `Path` deklarieren +* die Parameter in einer unterschiedlichen Reihenfolge haben +* `Annotated` nicht verwenden + +... dann hat Python eine kleine Spezial-Syntax für Sie. + +Übergeben Sie der Funktion `*` als ersten Parameter. + +Python macht nichts mit diesem `*`, aber es wird wissen, dass alle folgenden Parameter als Keyword-Argumente (Schlüssel-Wert-Paare), auch bekannt als kwargs, verwendet werden. Selbst wenn diese keinen Defaultwert haben. + +```Python hl_lines="7" +{!../../../docs_src/path_params_numeric_validations/tutorial003.py!} +``` + +### Besser mit `Annotated` + +Bedenken Sie, dass Sie, wenn Sie `Annotated` verwenden, dieses Problem nicht haben, weil Sie keine Defaultwerte für Ihre Funktionsparameter haben. Sie müssen daher wahrscheinlich auch nicht `*` verwenden. + +=== "Python 3.9+" + + ```Python hl_lines="10" + {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9" + {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!} + ``` + +## Validierung von Zahlen: Größer oder gleich + +Mit `Query` und `Path` (und anderen, die Sie später kennenlernen), können Sie Zahlenbeschränkungen deklarieren. + +Hier, mit `ge=1`, wird festgelegt, dass `item_id` eine Ganzzahl benötigt, die größer oder gleich `1` ist (`g`reater than or `e`qual). +=== "Python 3.9+" + + ```Python hl_lines="10" + {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9" + {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="8" + {!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!} + ``` + +## Validierung von Zahlen: Größer und kleiner oder gleich + +Das Gleiche trifft zu auf: + +* `gt`: `g`reater `t`han – größer als +* `le`: `l`ess than or `e`qual – kleiner oder gleich + +=== "Python 3.9+" + + ```Python hl_lines="10" + {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9" + {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="9" + {!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!} + ``` + +## Validierung von Zahlen: Floats, größer und kleiner + +Zahlenvalidierung funktioniert auch für `float`-Werte. + +Hier wird es wichtig, in der Lage zu sein, gt zu deklarieren, und nicht nur ge, da Sie hiermit bestimmen können, dass ein Wert, zum Beispiel, größer als `0` sein muss, obwohl er kleiner als `1` ist. + +`0.5` wäre also ein gültiger Wert, aber nicht `0.0` oder `0`. + +Das gleiche gilt für lt. + +=== "Python 3.9+" + + ```Python hl_lines="13" + {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="12" + {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="11" + {!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!} + ``` + +## Zusammenfassung + +Mit `Query` und `Path` (und anderen, die Sie noch nicht gesehen haben) können Sie Metadaten und Stringvalidierungen deklarieren, so wie in [Query-Parameter und Stringvalidierungen](query-params-str-validations.md){.internal-link target=_blank} beschrieben. + +Und Sie können auch Validierungen für Zahlen deklarieren: + +* `gt`: `g`reater `t`han – größer als +* `ge`: `g`reater than or `e`qual – größer oder gleich +* `lt`: `l`ess `t`han – kleiner als +* `le`: `l`ess than or `e`qual – kleiner oder gleich + +!!! info + `Query`, `Path`, und andere Klassen, die Sie später kennenlernen, sind Unterklassen einer allgemeinen `Param`-Klasse. + + Sie alle teilen die gleichen Parameter für zusätzliche Validierung und Metadaten, die Sie gesehen haben. + +!!! note "Technische Details" + `Query`, `Path` und andere, die Sie von `fastapi` importieren, sind tatsächlich Funktionen. + + Die, wenn sie aufgerufen werden, Instanzen der Klassen mit demselben Namen zurückgeben. + + Sie importieren also `Query`, welches eine Funktion ist. Aber wenn Sie es aufrufen, gibt es eine Instanz der Klasse zurück, die auch `Query` genannt wird. + + Diese Funktionen existieren (statt die Klassen direkt zu verwenden), damit Ihr Editor keine Fehlermeldungen über ihre Typen ausgibt. + + Auf diese Weise können Sie Ihren Editor und Ihre Programmier-Tools verwenden, ohne besondere Einstellungen vornehmen zu müssen, um diese Fehlermeldungen stummzuschalten. diff --git a/docs/de/docs/tutorial/path-params.md b/docs/de/docs/tutorial/path-params.md new file mode 100644 index 0000000000000..8c8f2e00865c7 --- /dev/null +++ b/docs/de/docs/tutorial/path-params.md @@ -0,0 +1,254 @@ +# Pfad-Parameter + +Sie können Pfad-„Parameter“ oder -„Variablen“ mit der gleichen Syntax deklarieren, welche in Python-Format-Strings verwendet wird: + +```Python hl_lines="6-7" +{!../../../docs_src/path_params/tutorial001.py!} +``` + +Der Wert des Pfad-Parameters `item_id` wird Ihrer Funktion als das Argument `item_id` übergeben. + +Wenn Sie dieses Beispiel ausführen und auf http://127.0.0.1:8000/items/foo gehen, sehen Sie als Response: + +```JSON +{"item_id":"foo"} +``` + +## Pfad-Parameter mit Typen + +Sie können den Typ eines Pfad-Parameters in der Argumentliste der Funktion deklarieren, mit Standard-Python-Typannotationen: + +```Python hl_lines="7" +{!../../../docs_src/path_params/tutorial002.py!} +``` + +In diesem Fall wird `item_id` als `int` deklariert, also als Ganzzahl. + +!!! check + Dadurch erhalten Sie Editor-Unterstützung innerhalb Ihrer Funktion, mit Fehlerprüfungen, Codevervollständigung, usw. + +## Daten-Konversion + +Wenn Sie dieses Beispiel ausführen und Ihren Browser unter http://127.0.0.1:8000/items/3 öffnen, sehen Sie als Response: + +```JSON +{"item_id":3} +``` + +!!! check + Beachten Sie, dass der Wert, den Ihre Funktion erhält und zurückgibt, die Zahl `3` ist, also ein `int`. Nicht der String `"3"`, also ein `str`. + + Sprich, mit dieser Typdeklaration wird **FastAPI** die Anfrage automatisch „parsen“. + +## Datenvalidierung + +Wenn Sie aber im Browser http://127.0.0.1:8000/items/foo besuchen, erhalten Sie eine hübsche HTTP-Fehlermeldung: + +```JSON +{ + "detail": [ + { + "type": "int_parsing", + "loc": [ + "path", + "item_id" + ], + "msg": "Input should be a valid integer, unable to parse string as an integer", + "input": "foo", + "url": "https://errors.pydantic.dev/2.1/v/int_parsing" + } + ] +} +``` + +Der Pfad-Parameter `item_id` hatte den Wert `"foo"`, was kein `int` ist. + +Die gleiche Fehlermeldung würde angezeigt werden, wenn Sie ein `float` (also eine Kommazahl) statt eines `int`s übergeben würden, wie etwa in: http://127.0.0.1:8000/items/4.2 + +!!! check + Sprich, mit der gleichen Python-Typdeklaration gibt Ihnen **FastAPI** Datenvalidierung. + + Beachten Sie, dass die Fehlermeldung auch direkt die Stelle anzeigt, wo die Validierung nicht erfolgreich war. + + Das ist unglaublich hilfreich, wenn Sie Code entwickeln und debuggen, welcher mit ihrer API interagiert. + +## Dokumentation + +Wenn Sie die Seite http://127.0.0.1:8000/docs in Ihrem Browser öffnen, sehen Sie eine automatische, interaktive API-Dokumentation: + + + +!!! check + Wiederum, mit dieser gleichen Python-Typdeklaration gibt Ihnen **FastAPI** eine automatische, interaktive Dokumentation (verwendet die Swagger-Benutzeroberfläche). + + Beachten Sie, dass der Pfad-Parameter dort als Ganzzahl deklariert ist. + +## Nützliche Standards. Alternative Dokumentation + +Und weil das generierte Schema vom OpenAPI-Standard kommt, gibt es viele kompatible Tools. + +Zum Beispiel bietet **FastAPI** selbst eine alternative API-Dokumentation (verwendet ReDoc), welche Sie unter http://127.0.0.1:8000/redoc einsehen können: + + + +Und viele weitere kompatible Tools. Inklusive Codegenerierung für viele Sprachen. + +## Pydantic + +Die ganze Datenvalidierung wird hinter den Kulissen von Pydantic durchgeführt, Sie profitieren also von dessen Vorteilen. Und Sie wissen, dass Sie in guten Händen sind. + +Sie können für Typ Deklarationen auch `str`, `float`, `bool` und viele andere komplexe Datentypen verwenden. + +Mehrere davon werden wir in den nächsten Kapiteln erkunden. + +## Die Reihenfolge ist wichtig + +Wenn Sie *Pfadoperationen* erstellen, haben Sie manchmal einen fixen Pfad. + +Etwa `/users/me`, um Daten über den aktuellen Benutzer zu erhalten. + +Und Sie haben auch einen Pfad `/users/{user_id}`, um Daten über einen spezifischen Benutzer zu erhalten, mittels einer Benutzer-ID. + +Weil *Pfadoperationen* in ihrer Reihenfolge ausgewertet werden, müssen Sie sicherstellen, dass der Pfad `/users/me` vor `/users/{user_id}` deklariert wurde: + +```Python hl_lines="6 11" +{!../../../docs_src/path_params/tutorial003.py!} +``` + +Ansonsten würde der Pfad für `/users/{user_id}` auch `/users/me` auswerten, und annehmen, dass ein Parameter `user_id` mit dem Wert `"me"` übergeben wurde. + +Sie können eine Pfadoperation auch nicht erneut definieren: + +```Python hl_lines="6 11" +{!../../../docs_src/path_params/tutorial003b.py!} +``` + +Die erste Definition wird immer verwendet werden, da ihr Pfad zuerst übereinstimmt. + +## Vordefinierte Parameterwerte + +Wenn Sie eine *Pfadoperation* haben, welche einen *Pfad-Parameter* hat, aber Sie wollen, dass dessen gültige Werte vordefiniert sind, können Sie ein Standard-Python `Enum` verwenden. + +### Erstellen Sie eine `Enum`-Klasse + +Importieren Sie `Enum` und erstellen Sie eine Unterklasse, die von `str` und `Enum` erbt. + +Indem Sie von `str` erben, weiß die API Dokumentation, dass die Werte des Enums vom Typ `str` sein müssen, und wird in der Lage sein, korrekt zu rendern. + +Erstellen Sie dann Klassen-Attribute mit festgelegten Werten, welches die erlaubten Werte sein werden: + +```Python hl_lines="1 6-9" +{!../../../docs_src/path_params/tutorial005.py!} +``` + +!!! info + Enumerationen (oder kurz Enums) gibt es in Python seit Version 3.4. + +!!! tip "Tipp" + Falls Sie sich fragen, was „AlexNet“, „ResNet“ und „LeNet“ ist, das sind Namen von Modellen für maschinelles Lernen. + +### Deklarieren Sie einen *Pfad-Parameter* + +Dann erstellen Sie einen *Pfad-Parameter*, der als Typ die gerade erstellte Enum-Klasse hat (`ModelName`): + +```Python hl_lines="16" +{!../../../docs_src/path_params/tutorial005.py!} +``` + +### Testen Sie es in der API-Dokumentation + +Weil die erlaubten Werte für den *Pfad-Parameter* nun vordefiniert sind, kann die interaktive Dokumentation sie als Auswahl-Drop-Down anzeigen: + + + +### Mit Python-*Enums* arbeiten + +Der *Pfad-Parameter* wird ein *Member eines Enums* sein. + +#### *Enum-Member* vergleichen + +Sie können ihn mit einem Member Ihres Enums `ModelName` vergleichen: + +```Python hl_lines="17" +{!../../../docs_src/path_params/tutorial005.py!} +``` + +#### *Enum-Wert* erhalten + +Den tatsächlichen Wert (in diesem Fall ein `str`) erhalten Sie via `model_name.value`, oder generell, `ihr_enum_member.value`: + +```Python hl_lines="20" +{!../../../docs_src/path_params/tutorial005.py!} +``` + +!!! tip "Tipp" + Sie können den Wert `"lenet"` außerdem mittels `ModelName.lenet.value` abrufen. + +#### *Enum-Member* zurückgeben + +Sie können *Enum-Member* in ihrer *Pfadoperation* zurückgeben, sogar verschachtelt in einem JSON-Body (z. B. als `dict`). + +Diese werden zu ihren entsprechenden Werten konvertiert (in diesem Fall Strings), bevor sie zum Client übertragen werden: + +```Python hl_lines="18 21 23" +{!../../../docs_src/path_params/tutorial005.py!} +``` + +In Ihrem Client erhalten Sie eine JSON-Response, wie etwa: + +```JSON +{ + "model_name": "alexnet", + "message": "Deep Learning FTW!" +} +``` + +## Pfad Parameter die Pfade enthalten + +Angenommen, Sie haben eine *Pfadoperation* mit einem Pfad `/files/{file_path}`. + +Aber `file_path` soll selbst einen *Pfad* enthalten, etwa `home/johndoe/myfile.txt`. + +Sprich, die URL für diese Datei wäre etwas wie: `/files/home/johndoe/myfile.txt`. + +### OpenAPI Unterstützung + +OpenAPI bietet nicht die Möglichkeit, dass ein *Pfad-Parameter* seinerseits einen *Pfad* enthalten kann, das würde zu Szenarios führen, die schwierig zu testen und zu definieren sind. + +Trotzdem können Sie das in **FastAPI** tun, indem Sie eines der internen Tools von Starlette verwenden. + +Die Dokumentation würde weiterhin funktionieren, allerdings wird nicht dokumentiert werden, dass der Parameter ein Pfad sein sollte. + +### Pfad Konverter + +Mittels einer Option direkt von Starlette können Sie einen *Pfad-Parameter* deklarieren, der einen Pfad enthalten soll, indem Sie eine URL wie folgt definieren: + +``` +/files/{file_path:path} +``` + +In diesem Fall ist der Name des Parameters `file_path`. Der letzte Teil, `:path`, sagt aus, dass der Parameter ein *Pfad* sein soll. + +Sie verwenden das also wie folgt: + +```Python hl_lines="6" +{!../../../docs_src/path_params/tutorial004.py!} +``` + +!!! tip "Tipp" + Der Parameter könnte einen führenden Schrägstrich (`/`) haben, wie etwa in `/home/johndoe/myfile.txt`. + + In dem Fall wäre die URL: `/files//home/johndoe/myfile.txt`, mit einem doppelten Schrägstrich (`//`) zwischen `files` und `home`. + +## Zusammenfassung + +In **FastAPI** erhalten Sie mittels kurzer, intuitiver Typdeklarationen: + +* Editor-Unterstützung: Fehlerprüfungen, Codevervollständigung, usw. +* Daten "parsen" +* Datenvalidierung +* API-Annotationen und automatische Dokumentation + +Und Sie müssen sie nur einmal deklarieren. + +Das ist wahrscheinlich der sichtbarste Unterschied zwischen **FastAPI** und alternativen Frameworks (abgesehen von der reinen Performanz). diff --git a/docs/de/docs/tutorial/query-params-str-validations.md b/docs/de/docs/tutorial/query-params-str-validations.md new file mode 100644 index 0000000000000..92f2bbe7c3214 --- /dev/null +++ b/docs/de/docs/tutorial/query-params-str-validations.md @@ -0,0 +1,914 @@ +# Query-Parameter und Stringvalidierung + +**FastAPI** erlaubt es Ihnen, Ihre Parameter zusätzlich zu validieren, und zusätzliche Informationen hinzuzufügen. + +Nehmen wir als Beispiel die folgende Anwendung: + +=== "Python 3.10+" + + ```Python hl_lines="7" + {!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9" + {!> ../../../docs_src/query_params_str_validations/tutorial001.py!} + ``` + +Der Query-Parameter `q` hat den Typ `Union[str, None]` (oder `str | None` in Python 3.10), was bedeutet, er ist entweder ein `str` oder `None`. Der Defaultwert ist `None`, also weiß FastAPI, der Parameter ist nicht erforderlich. + +!!! note "Hinweis" + FastAPI weiß nur dank des definierten Defaultwertes `=None`, dass der Wert von `q` nicht erforderlich ist + + `Union[str, None]` hingegen erlaubt ihren Editor, Sie besser zu unterstützen und Fehler zu erkennen. + +## Zusätzliche Validierung + +Wir werden bewirken, dass, obwohl `q` optional ist, wenn es gegeben ist, **seine Länge 50 Zeichen nicht überschreitet**. + +### `Query` und `Annotated` importieren + +Importieren Sie zuerst: + +* `Query` von `fastapi` +* `Annotated` von `typing` (oder von `typing_extensions` in Python unter 3.9) + +=== "Python 3.10+" + + In Python 3.9 oder darüber, ist `Annotated` Teil der Standardbibliothek, also können Sie es von `typing` importieren. + + ```Python hl_lines="1 3" + {!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} + ``` + +=== "Python 3.8+" + + In Versionen unter Python 3.9 importieren Sie `Annotated` von `typing_extensions`. + + Es wird bereits mit FastAPI installiert sein. + + ```Python hl_lines="3-4" + {!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!} + ``` + +!!! info + FastAPI unterstützt (und empfiehlt die Verwendung von) `Annotated` seit Version 0.95.0. + + Wenn Sie eine ältere Version haben, werden Sie Fehler angezeigt bekommen, wenn Sie versuchen, `Annotated` zu verwenden. + + Bitte [aktualisieren Sie FastAPI](../deployment/versions.md#upgrade-der-fastapi-versionen){.internal-link target=_blank} daher mindestens zu Version 0.95.1, bevor Sie `Annotated` verwenden. + +## `Annotated` im Typ des `q`-Parameters verwenden + +Erinnern Sie sich, wie ich in [Einführung in Python-Typen](../python-types.md#typhinweise-mit-metadaten-annotationen){.internal-link target=_blank} sagte, dass Sie mittels `Annotated` Metadaten zu Ihren Parametern hinzufügen können? + +Jetzt ist es an der Zeit, das mit FastAPI auszuprobieren. 🚀 + +Wir hatten diese Typannotation: + +=== "Python 3.10+" + + ```Python + q: str | None = None + ``` + +=== "Python 3.8+" + + ```Python + q: Union[str, None] = None + ``` + +Wir wrappen das nun in `Annotated`, sodass daraus wird: + +=== "Python 3.10+" + + ```Python + q: Annotated[str | None] = None + ``` + +=== "Python 3.8+" + + ```Python + q: Annotated[Union[str, None]] = None + ``` + +Beide Versionen bedeuten dasselbe: `q` ist ein Parameter, der `str` oder `None` sein kann. Standardmäßig ist er `None`. + +Wenden wir uns jetzt den spannenden Dingen zu. 🎉 + +## `Query` zu `Annotated` im `q`-Parameter hinzufügen + +Jetzt, da wir `Annotated` für unsere Metadaten deklariert haben, fügen Sie `Query` hinzu, und setzen Sie den Parameter `max_length` auf `50`: + +=== "Python 3.10+" + + ```Python hl_lines="9" + {!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="10" + {!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!} + ``` + +Beachten Sie, dass der Defaultwert immer noch `None` ist, sodass der Parameter immer noch optional ist. + +Aber jetzt, mit `Query(max_length=50)` innerhalb von `Annotated`, sagen wir FastAPI, dass es diesen Wert aus den Query-Parametern extrahieren soll (das hätte es sowieso gemacht 🤷) und dass wir eine **zusätzliche Validierung** für diesen Wert haben wollen (darum machen wir das, um die zusätzliche Validierung zu bekommen). 😎 + +FastAPI wird nun: + +* Die Daten **validieren** und sicherstellen, dass sie nicht länger als 50 Zeichen sind +* Dem Client einen **verständlichen Fehler** anzeigen, wenn die Daten ungültig sind +* Den Parameter in der OpenAPI-Schema-*Pfadoperation* **dokumentieren** (sodass er in der **automatischen Dokumentation** angezeigt wird) + +## Alternativ (alt): `Query` als Defaultwert + +Frühere Versionen von FastAPI (vor 0.95.0) benötigten `Query` als Defaultwert des Parameters, statt es innerhalb von `Annotated` unterzubringen. Die Chance ist groß, dass Sie Quellcode sehen, der das immer noch so macht, darum erkläre ich es Ihnen. + +!!! tip "Tipp" + Verwenden Sie für neuen Code, und wann immer möglich, `Annotated`, wie oben erklärt. Es gibt mehrere Vorteile (unten erläutert) und keine Nachteile. 🍰 + +So würden Sie `Query()` als Defaultwert Ihres Funktionsparameters verwenden, den Parameter `max_length` auf 50 gesetzt: + +=== "Python 3.10+" + + ```Python hl_lines="7" + {!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9" + {!> ../../../docs_src/query_params_str_validations/tutorial002.py!} + ``` + +Da wir in diesem Fall (ohne die Verwendung von `Annotated`) den Parameter-Defaultwert `None` mit `Query()` ersetzen, müssen wir nun dessen Defaultwert mit dem Parameter `Query(default=None)` deklarieren. Das dient demselben Zweck, `None` als Defaultwert für den Funktionsparameter zu setzen (zumindest für FastAPI). + +Sprich: + +```Python +q: Union[str, None] = Query(default=None) +``` + +... macht den Parameter optional, mit dem Defaultwert `None`, genauso wie: + +```Python +q: Union[str, None] = None +``` + +Und in Python 3.10 und darüber macht: + +```Python +q: str | None = Query(default=None) +``` + +... den Parameter optional, mit dem Defaultwert `None`, genauso wie: + +```Python +q: str | None = None +``` + +Nur, dass die `Query`-Versionen den Parameter explizit als Query-Parameter deklarieren. + +!!! info + Bedenken Sie, dass: + + ```Python + = None + ``` + + oder: + + ```Python + = Query(default=None) + ``` + + der wichtigste Teil ist, um einen Parameter optional zu machen, da dieses `None` der Defaultwert ist, und das ist es, was diesen Parameter **nicht erforderlich** macht. + + Der Teil mit `Union[str, None]` erlaubt es Ihrem Editor, Sie besser zu unterstützen, aber er sagt FastAPI nicht, dass dieser Parameter optional ist. + +Jetzt können wir `Query` weitere Parameter übergeben. Fangen wir mit dem `max_length` Parameter an, der auf Strings angewendet wird: + +```Python +q: Union[str, None] = Query(default=None, max_length=50) +``` + +Das wird die Daten validieren, einen verständlichen Fehler ausgeben, wenn die Daten nicht gültig sind, und den Parameter in der OpenAPI-Schema-*Pfadoperation* dokumentieren. + +### `Query` als Defaultwert oder in `Annotated` + +Bedenken Sie, dass wenn Sie `Query` innerhalb von `Annotated` benutzen, Sie den `default`-Parameter für `Query` nicht verwenden dürfen. + +Setzen Sie stattdessen den Defaultwert des Funktionsparameters, sonst wäre es inkonsistent. + +Zum Beispiel ist das nicht erlaubt: + +```Python +q: Annotated[str, Query(default="rick")] = "morty" +``` + +... denn es wird nicht klar, ob der Defaultwert `"rick"` oder `"morty"` sein soll. + +Sie würden also (bevorzugt) schreiben: + +```Python +q: Annotated[str, Query()] = "rick" +``` + +In älterem Code werden Sie auch finden: + +```Python +q: str = Query(default="rick") +``` + +### Vorzüge von `Annotated` + +**Es wird empfohlen, `Annotated` zu verwenden**, statt des Defaultwertes im Funktionsparameter, das ist aus mehreren Gründen **besser**: 🤓 + +Der **Default**wert des **Funktionsparameters** ist der **tatsächliche Default**wert, das spielt generell intuitiver mit Python zusammen. 😌 + +Sie können die Funktion ohne FastAPI an **anderen Stellen aufrufen**, und es wird **wie erwartet funktionieren**. Wenn es einen **erforderlichen** Parameter gibt (ohne Defaultwert), und Sie führen die Funktion ohne den benötigten Parameter aus, dann wird Ihr **Editor** Sie das mit einem Fehler wissen lassen, und **Python** wird sich auch beschweren. + +Wenn Sie aber nicht `Annotated` benutzen und stattdessen die **(alte) Variante mit einem Defaultwert**, dann müssen Sie, wenn Sie die Funktion ohne FastAPI an **anderen Stellen** aufrufen, sich daran **erinnern**, die Argumente der Funktion zu übergeben, damit es richtig funktioniert. Ansonsten erhalten Sie unerwartete Werte (z. B. `QueryInfo` oder etwas Ähnliches, statt `str`). Ihr Editor kann ihnen nicht helfen, und Python wird die Funktion ohne Beschwerden ausführen, es sei denn, die Operationen innerhalb lösen einen Fehler aus. + +Da `Annotated` mehrere Metadaten haben kann, können Sie dieselbe Funktion auch mit anderen Tools verwenden, wie etwa Typer. 🚀 + +## Mehr Validierungen hinzufügen + +Sie können auch einen Parameter `min_length` hinzufügen: + +=== "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.8+" + + ```Python hl_lines="11" + {!> ../../../docs_src/query_params_str_validations/tutorial003_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="7" + {!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="10" + {!> ../../../docs_src/query_params_str_validations/tutorial003.py!} + ``` + +## Reguläre Ausdrücke hinzufügen + +Sie können einen Regulären Ausdruck `pattern` definieren, mit dem der Parameter übereinstimmen muss: + +=== "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.8+" + + ```Python hl_lines="12" + {!> ../../../docs_src/query_params_str_validations/tutorial004_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="9" + {!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="11" + {!> ../../../docs_src/query_params_str_validations/tutorial004.py!} + ``` + +Dieses bestimmte reguläre Suchmuster prüft, ob der erhaltene Parameter-Wert: + +* `^`: mit den nachfolgenden Zeichen startet, keine Zeichen davor hat. +* `fixedquery`: den exakten Text `fixedquery` hat. +* `$`: danach endet, keine weiteren Zeichen hat als `fixedquery`. + +Wenn Sie sich verloren fühlen bei all diesen **„Regulärer Ausdruck“**-Konzepten, keine Sorge. Reguläre Ausdrücke sind für viele Menschen ein schwieriges Thema. Sie können auch ohne reguläre Ausdrücke eine ganze Menge machen. + +Aber wenn Sie sie brauchen und sie lernen, wissen Sie, dass Sie sie bereits direkt in **FastAPI** verwenden können. + +### Pydantic v1 `regex` statt `pattern` + +Vor Pydantic Version 2 und vor FastAPI Version 0.100.0, war der Name des Parameters `regex` statt `pattern`, aber das ist jetzt deprecated. + +Sie könnten immer noch Code sehen, der den alten Namen verwendet: + +=== "Python 3.10+ Pydantic v1" + + ```Python hl_lines="11" + {!> ../../../docs_src/query_params_str_validations/tutorial004_an_py310_regex.py!} + ``` + +Beachten Sie aber, dass das deprecated ist, und zum neuen Namen `pattern` geändert werden sollte. 🤓 + +## Defaultwerte + +Sie können natürlich andere Defaultwerte als `None` verwenden. + +Beispielsweise könnten Sie den `q` Query-Parameter so deklarieren, dass er eine `min_length` von `3` hat, und den Defaultwert `"fixedquery"`: + +=== "Python 3.9+" + + ```Python hl_lines="9" + {!> ../../../docs_src/query_params_str_validations/tutorial005_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="8" + {!> ../../../docs_src/query_params_str_validations/tutorial005_an.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="7" + {!> ../../../docs_src/query_params_str_validations/tutorial005.py!} + ``` + +!!! note "Hinweis" + Ein Parameter ist optional (nicht erforderlich), wenn er irgendeinen Defaultwert, auch `None`, hat. + +## Erforderliche Parameter + +Wenn wir keine Validierungen oder Metadaten haben, können wir den `q` Query-Parameter erforderlich machen, indem wir einfach keinen Defaultwert deklarieren, wie in: + +```Python +q: str +``` + +statt: + +```Python +q: Union[str, None] = None +``` + +Aber jetzt deklarieren wir den Parameter mit `Query`, wie in: + +=== "Annotiert" + + ```Python + q: Annotated[Union[str, None], Query(min_length=3)] = None + ``` + +=== "Nicht annotiert" + + ```Python + q: Union[str, None] = Query(default=None, min_length=3) + ``` + +Wenn Sie einen Parameter erforderlich machen wollen, während Sie `Query` verwenden, deklarieren Sie ebenfalls einfach keinen Defaultwert: + +=== "Python 3.9+" + + ```Python hl_lines="9" + {!> ../../../docs_src/query_params_str_validations/tutorial006_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="8" + {!> ../../../docs_src/query_params_str_validations/tutorial006_an.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="7" + {!> ../../../docs_src/query_params_str_validations/tutorial006.py!} + ``` + + !!! tip "Tipp" + Beachten Sie, dass, obwohl in diesem Fall `Query()` der Funktionsparameter-Defaultwert ist, wir nicht `default=None` zu `Query()` hinzufügen. + + Verwenden Sie bitte trotzdem die `Annotated`-Version. 😉 + +### Erforderlich mit Ellipse (`...`) + +Es gibt eine Alternative, die explizit deklariert, dass ein Wert erforderlich ist. Sie können als Default das Literal `...` setzen: + +=== "Python 3.9+" + + ```Python hl_lines="9" + {!> ../../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="8" + {!> ../../../docs_src/query_params_str_validations/tutorial006b_an.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="7" + {!> ../../../docs_src/query_params_str_validations/tutorial006b.py!} + ``` + +!!! info + Falls Sie das `...` bisher noch nicht gesehen haben: Es ist ein spezieller einzelner Wert, Teil von Python und wird „Ellipsis“ genannt (Deutsch: Ellipse). + + Es wird von Pydantic und FastAPI verwendet, um explizit zu deklarieren, dass ein Wert erforderlich ist. + +Dies wird **FastAPI** wissen lassen, dass dieser Parameter erforderlich ist. + +### Erforderlich, kann `None` sein + +Sie können deklarieren, dass ein Parameter `None` akzeptiert, aber dennoch erforderlich ist. Das zwingt Clients, den Wert zu senden, selbst wenn er `None` ist. + +Um das zu machen, deklarieren Sie, dass `None` ein gültiger Typ ist, aber verwenden Sie dennoch `...` als 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.8+" + + ```Python hl_lines="10" + {!> ../../../docs_src/query_params_str_validations/tutorial006c_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="7" + {!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="9" + {!> ../../../docs_src/query_params_str_validations/tutorial006c.py!} + ``` + +!!! tip "Tipp" + Pydantic, welches die gesamte Datenvalidierung und Serialisierung in FastAPI antreibt, hat ein spezielles Verhalten, wenn Sie `Optional` oder `Union[Something, None]` ohne Defaultwert verwenden, Sie können mehr darüber in der Pydantic-Dokumentation unter Required fields erfahren. + +!!! tip "Tipp" + Denken Sie daran, dass Sie in den meisten Fällen, wenn etwas erforderlich ist, einfach den Defaultwert weglassen können. Sie müssen also normalerweise `...` nicht verwenden. + +## Query-Parameter-Liste / Mehrere Werte + +Wenn Sie einen Query-Parameter explizit mit `Query` auszeichnen, können Sie ihn auch eine Liste von Werten empfangen lassen, oder anders gesagt, mehrere Werte. + +Um zum Beispiel einen Query-Parameter `q` zu deklarieren, der mehrere Male in der URL vorkommen kann, schreiben Sie: + +=== "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.8+" + + ```Python hl_lines="10" + {!> ../../../docs_src/query_params_str_validations/tutorial011_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="7" + {!> ../../../docs_src/query_params_str_validations/tutorial011_py310.py!} + ``` + +=== "Python 3.9+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="9" + {!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="9" + {!> ../../../docs_src/query_params_str_validations/tutorial011.py!} + ``` + +Dann, mit einer URL wie: + +``` +http://localhost:8000/items/?q=foo&q=bar +``` + +bekommen Sie alle `q`-*Query-Parameter*-Werte (`foo` und `bar`) in einer Python-Liste – `list` – in ihrer *Pfadoperation-Funktion*, im Funktionsparameter `q`, überreicht. + +Die Response für diese URL wäre also: + +```JSON +{ + "q": [ + "foo", + "bar" + ] +} +``` + +!!! tip "Tipp" + Um einen Query-Parameter vom Typ `list` zu deklarieren, wie im Beispiel oben, müssen Sie explizit `Query` verwenden, sonst würde der Parameter als Requestbody interpretiert werden. + +Die interaktive API-Dokumentation wird entsprechend aktualisiert und erlaubt jetzt mehrere Werte. + + + +### Query-Parameter-Liste / Mehrere Werte mit Defaults + +Und Sie können auch eine Default-`list`e von Werten definieren, wenn keine übergeben werden: + +=== "Python 3.9+" + + ```Python hl_lines="9" + {!> ../../../docs_src/query_params_str_validations/tutorial012_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="10" + {!> ../../../docs_src/query_params_str_validations/tutorial012_an.py!} + ``` + +=== "Python 3.9+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="7" + {!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="9" + {!> ../../../docs_src/query_params_str_validations/tutorial012.py!} + ``` + +Wenn Sie auf: + +``` +http://localhost:8000/items/ +``` + +gehen, wird der Default für `q` verwendet: `["foo", "bar"]`, und als Response erhalten Sie: + +```JSON +{ + "q": [ + "foo", + "bar" + ] +} +``` + +#### `list` alleine verwenden + +Sie können auch `list` direkt verwenden, anstelle von `List[str]` (oder `list[str]` in Python 3.9+): + +=== "Python 3.9+" + + ```Python hl_lines="9" + {!> ../../../docs_src/query_params_str_validations/tutorial013_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="8" + {!> ../../../docs_src/query_params_str_validations/tutorial013_an.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="7" + {!> ../../../docs_src/query_params_str_validations/tutorial013.py!} + ``` + +!!! note "Hinweis" + Beachten Sie, dass FastAPI in diesem Fall den Inhalt der Liste nicht überprüft. + + Zum Beispiel würde `List[int]` überprüfen (und dokumentieren) dass die Liste Ganzzahlen enthält. `list` alleine macht das nicht. + +## Deklarieren von mehr Metadaten + +Sie können mehr Informationen zum Parameter hinzufügen. + +Diese Informationen werden zur generierten OpenAPI hinzugefügt, und von den Dokumentations-Oberflächen und von externen Tools verwendet. + +!!! note "Hinweis" + Beachten Sie, dass verschiedene Tools OpenAPI möglicherweise unterschiedlich gut unterstützen. + + Einige könnten noch nicht alle zusätzlichen Informationen anzeigen, die Sie deklariert haben, obwohl in den meisten Fällen geplant ist, das fehlende Feature zu implementieren. + +Sie können einen Titel hinzufügen – `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.8+" + + ```Python hl_lines="11" + {!> ../../../docs_src/query_params_str_validations/tutorial007_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="8" + {!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="10" + {!> ../../../docs_src/query_params_str_validations/tutorial007.py!} + ``` + +Und eine Beschreibung – `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.8+" + + ```Python hl_lines="15" + {!> ../../../docs_src/query_params_str_validations/tutorial008_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="11" + {!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="13" + {!> ../../../docs_src/query_params_str_validations/tutorial008.py!} + ``` + +## Alias-Parameter + +Stellen Sie sich vor, der Parameter soll `item-query` sein. + +Wie in: + +``` +http://127.0.0.1:8000/items/?item-query=foobaritems +``` + +Aber `item-query` ist kein gültiger Name für eine Variable in Python. + +Am ähnlichsten wäre `item_query`. + +Aber Sie möchten dennoch exakt `item-query` verwenden. + +Dann können Sie einen `alias` deklarieren, und dieser Alias wird verwendet, um den Parameter-Wert zu finden: + +=== "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.8+" + + ```Python hl_lines="10" + {!> ../../../docs_src/query_params_str_validations/tutorial009_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="7" + {!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="9" + {!> ../../../docs_src/query_params_str_validations/tutorial009.py!} + ``` + +## Parameter als deprecated ausweisen + +Nehmen wir an, Sie mögen diesen Parameter nicht mehr. + +Sie müssen ihn eine Weile dort belassen, weil Clients ihn benutzen, aber Sie möchten, dass die Dokumentation klar anzeigt, dass er deprecated ist. + +In diesem Fall fügen Sie den Parameter `deprecated=True` zu `Query` hinzu. + +=== "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.8+" + + ```Python hl_lines="20" + {!> ../../../docs_src/query_params_str_validations/tutorial010_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="16" + {!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="18" + {!> ../../../docs_src/query_params_str_validations/tutorial010.py!} + ``` + +Die Dokumentation wird das so anzeigen: + + + +## Parameter von OpenAPI ausschließen + +Um einen Query-Parameter vom generierten OpenAPI-Schema auszuschließen (und daher von automatischen Dokumentations-Systemen), setzen Sie den Parameter `include_in_schema` in `Query` auf `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.8+" + + ```Python hl_lines="11" + {!> ../../../docs_src/query_params_str_validations/tutorial014_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="8" + {!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="10" + {!> ../../../docs_src/query_params_str_validations/tutorial014.py!} + ``` + +## Zusammenfassung + +Sie können zusätzliche Validierungen und Metadaten zu ihren Parametern hinzufügen. + +Allgemeine Validierungen und Metadaten: + +* `alias` +* `title` +* `description` +* `deprecated` + +Validierungen spezifisch für Strings: + +* `min_length` +* `max_length` +* `pattern` + +In diesen Beispielen haben Sie gesehen, wie Sie Validierungen für Strings hinzufügen. + +In den nächsten Kapiteln sehen wir, wie man Validierungen für andere Typen hinzufügt, etwa für Zahlen. diff --git a/docs/de/docs/tutorial/query-params.md b/docs/de/docs/tutorial/query-params.md new file mode 100644 index 0000000000000..1b9b56bea8fee --- /dev/null +++ b/docs/de/docs/tutorial/query-params.md @@ -0,0 +1,226 @@ +# Query-Parameter + +Wenn Sie in ihrer Funktion Parameter deklarieren, die nicht Teil der Pfad-Parameter sind, dann werden diese automatisch als „Query“-Parameter interpretiert. + +```Python hl_lines="9" +{!../../../docs_src/query_params/tutorial001.py!} +``` + +Query-Parameter (Deutsch: Abfrage-Parameter) sind die Schlüssel-Wert-Paare, die nach dem `?` in einer URL aufgelistet sind, getrennt durch `&`-Zeichen. + +Zum Beispiel sind in der URL: + +``` +http://127.0.0.1:8000/items/?skip=0&limit=10 +``` + +... die Query-Parameter: + +* `skip`: mit dem Wert `0` +* `limit`: mit dem Wert `10` + +Da sie Teil der URL sind, sind sie „naturgemäß“ Strings. + +Aber wenn Sie sie mit Python-Typen deklarieren (im obigen Beispiel als `int`), werden sie zu diesem Typ konvertiert, und gegen diesen validiert. + +Die gleichen Prozesse, die für Pfad-Parameter stattfinden, werden auch auf Query-Parameter angewendet: + +* Editor Unterstützung (natürlich) +* „Parsen“ der Daten +* Datenvalidierung +* Automatische Dokumentation + +## Defaultwerte + +Da Query-Parameter nicht ein festgelegter Teil des Pfades sind, können sie optional sein und Defaultwerte haben. + +Im obigen Beispiel haben sie die Defaultwerte `skip=0` und `limit=10`. + +Wenn Sie also zur URL: + +``` +http://127.0.0.1:8000/items/ +``` + +gehen, so ist das das gleiche wie die URL: + +``` +http://127.0.0.1:8000/items/?skip=0&limit=10 +``` + +Aber wenn Sie zum Beispiel zu: + +``` +http://127.0.0.1:8000/items/?skip=20 +``` + +gehen, werden die Parameter-Werte Ihrer Funktion sein: + +* `skip=20`: da Sie das in der URL gesetzt haben +* `limit=10`: weil das der Defaultwert ist + +## Optionale Parameter + +Auf die gleiche Weise können Sie optionale Query-Parameter deklarieren, indem Sie deren Defaultwert auf `None` setzen: + +=== "Python 3.10+" + + ```Python hl_lines="7" + {!> ../../../docs_src/query_params/tutorial002_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9" + {!> ../../../docs_src/query_params/tutorial002.py!} + ``` + +In diesem Fall wird der Funktionsparameter `q` optional, und standardmäßig `None` sein. + +!!! check + Beachten Sie auch, dass **FastAPI** intelligent genug ist, um zu erkennen, dass `item_id` ein Pfad-Parameter ist und `q` keiner, daher muss letzteres ein Query-Parameter sein. + +## Query-Parameter Typkonvertierung + +Sie können auch `bool`-Typen deklarieren und sie werden konvertiert: + +=== "Python 3.10+" + + ```Python hl_lines="7" + {!> ../../../docs_src/query_params/tutorial003_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9" + {!> ../../../docs_src/query_params/tutorial003.py!} + ``` + +Wenn Sie nun zu: + +``` +http://127.0.0.1:8000/items/foo?short=1 +``` + +oder + +``` +http://127.0.0.1:8000/items/foo?short=True +``` + +oder + +``` +http://127.0.0.1:8000/items/foo?short=true +``` + +oder + +``` +http://127.0.0.1:8000/items/foo?short=on +``` + +oder + +``` +http://127.0.0.1:8000/items/foo?short=yes +``` + +gehen, oder zu irgendeiner anderen Variante der Groß-/Kleinschreibung (Alles groß, Anfangsbuchstabe groß, usw.), dann wird Ihre Funktion den Parameter `short` mit dem `bool`-Wert `True` sehen, ansonsten mit dem Wert `False`. + +## Mehrere Pfad- und Query-Parameter + +Sie können mehrere Pfad-Parameter und Query-Parameter gleichzeitig deklarieren, **FastAPI** weiß, was welches ist. + +Und Sie müssen sie auch nicht in einer spezifischen Reihenfolge deklarieren. + +Parameter werden anhand ihres Namens erkannt: + +=== "Python 3.10+" + + ```Python hl_lines="6 8" + {!> ../../../docs_src/query_params/tutorial004_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="8 10" + {!> ../../../docs_src/query_params/tutorial004.py!} + ``` + +## Erforderliche Query-Parameter + +Wenn Sie einen Defaultwert für Nicht-Pfad-Parameter deklarieren (Bis jetzt haben wir nur Query-Parameter gesehen), dann ist der Parameter nicht erforderlich. + +Wenn Sie keinen spezifischen Wert haben wollen, sondern der Parameter einfach optional sein soll, dann setzen Sie den Defaultwert auf `None`. + +Aber wenn Sie wollen, dass ein Query-Parameter erforderlich ist, vergeben Sie einfach keinen Defaultwert: + +```Python hl_lines="6-7" +{!../../../docs_src/query_params/tutorial005.py!} +``` + +Hier ist `needy` ein erforderlicher Query-Parameter vom Typ `str`. + +Wenn Sie in Ihrem Browser eine URL wie: + +``` +http://127.0.0.1:8000/items/foo-item +``` + +... öffnen, ohne den benötigten Parameter `needy`, dann erhalten Sie einen Fehler wie den folgenden: + +```JSON +{ + "detail": [ + { + "type": "missing", + "loc": [ + "query", + "needy" + ], + "msg": "Field required", + "input": null, + "url": "https://errors.pydantic.dev/2.1/v/missing" + } + ] +} +``` + +Da `needy` ein erforderlicher Parameter ist, müssen Sie ihn in der URL setzen: + +``` +http://127.0.0.1:8000/items/foo-item?needy=sooooneedy +``` + +... Das funktioniert: + +```JSON +{ + "item_id": "foo-item", + "needy": "sooooneedy" +} +``` + +Und natürlich können Sie einige Parameter als erforderlich, einige mit Defaultwert, und einige als vollständig optional definieren: + +=== "Python 3.10+" + + ```Python hl_lines="8" + {!> ../../../docs_src/query_params/tutorial006_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="10" + {!> ../../../docs_src/query_params/tutorial006.py!} + ``` + +In diesem Fall gibt es drei Query-Parameter: + +* `needy`, ein erforderlicher `str`. +* `skip`, ein `int` mit einem Defaultwert `0`. +* `limit`, ein optionales `int`. + +!!! tip "Tipp" + Sie können auch `Enum`s verwenden, auf die gleiche Weise wie mit [Pfad-Parametern](path-params.md#vordefinierte-parameterwerte){.internal-link target=_blank}. diff --git a/docs/de/docs/tutorial/request-files.md b/docs/de/docs/tutorial/request-files.md new file mode 100644 index 0000000000000..67b5e3a87973a --- /dev/null +++ b/docs/de/docs/tutorial/request-files.md @@ -0,0 +1,314 @@ +# Dateien im Request + +Mit `File` können sie vom Client hochzuladende Dateien definieren. + +!!! info + Um hochgeladene Dateien zu empfangen, installieren Sie zuerst `python-multipart`. + + Z. B. `pip install python-multipart`. + + Das, weil hochgeladene Dateien als „Formulardaten“ gesendet werden. + +## `File` importieren + +Importieren Sie `File` und `UploadFile` von `fastapi`: + +=== "Python 3.9+" + + ```Python hl_lines="3" + {!> ../../../docs_src/request_files/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="1" + {!> ../../../docs_src/request_files/tutorial001_an.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="1" + {!> ../../../docs_src/request_files/tutorial001.py!} + ``` + +## `File`-Parameter definieren + +Erstellen Sie Datei-Parameter, so wie Sie es auch mit `Body` und `Form` machen würden: + +=== "Python 3.9+" + + ```Python hl_lines="9" + {!> ../../../docs_src/request_files/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="8" + {!> ../../../docs_src/request_files/tutorial001_an.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="7" + {!> ../../../docs_src/request_files/tutorial001.py!} + ``` + +!!! info + `File` ist eine Klasse, die direkt von `Form` erbt. + + Aber erinnern Sie sich, dass, wenn Sie `Query`, `Path`, `File` und andere von `fastapi` importieren, diese tatsächlich Funktionen sind, welche spezielle Klassen zurückgeben + +!!! tip "Tipp" + Um Dateibodys zu deklarieren, müssen Sie `File` verwenden, da diese Parameter sonst als Query-Parameter oder Body(-JSON)-Parameter interpretiert werden würden. + +Die Dateien werden als „Formulardaten“ hochgeladen. + +Wenn Sie den Typ Ihrer *Pfadoperation-Funktion* als `bytes` deklarieren, wird **FastAPI** die Datei für Sie auslesen, und Sie erhalten den Inhalt als `bytes`. + +Bedenken Sie, dass das bedeutet, dass sich der gesamte Inhalt der Datei im Arbeitsspeicher befindet. Das wird für kleinere Dateien gut funktionieren. + +Aber es gibt viele Fälle, in denen Sie davon profitieren, `UploadFile` zu verwenden. + +## Datei-Parameter mit `UploadFile` + +Definieren Sie einen Datei-Parameter mit dem Typ `UploadFile`: + +=== "Python 3.9+" + + ```Python hl_lines="14" + {!> ../../../docs_src/request_files/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="13" + {!> ../../../docs_src/request_files/tutorial001_an.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="12" + {!> ../../../docs_src/request_files/tutorial001.py!} + ``` + +`UploadFile` zu verwenden, hat mehrere Vorzüge gegenüber `bytes`: + +* Sie müssen `File()` nicht als Parameter-Defaultwert verwenden. +* Es wird eine „Spool“-Datei verwendet: + * Eine Datei, die bis zu einem bestimmten Größen-Limit im Arbeitsspeicher behalten wird, und wenn das Limit überschritten wird, auf der Festplatte gespeichert wird. +* Das bedeutet, es wird für große Dateien wie Bilder, Videos, große Binärdateien, usw. gut funktionieren, ohne den ganzen Arbeitsspeicher aufzubrauchen. +* Sie können Metadaten aus der hochgeladenen Datei auslesen. +* Es hat eine file-like `async`hrone Schnittstelle. +* Es stellt ein tatsächliches Python-`SpooledTemporaryFile`-Objekt bereit, welches Sie direkt anderen Bibliotheken übergeben können, die ein dateiartiges Objekt erwarten. + +### `UploadFile` + +`UploadFile` hat die folgenden Attribute: + +* `filename`: Ein `str` mit dem ursprünglichen Namen der hochgeladenen Datei (z. B. `meinbild.jpg`). +* `content_type`: Ein `str` mit dem Inhaltstyp (MIME-Typ / Medientyp) (z. B. `image/jpeg`). +* `file`: Ein `SpooledTemporaryFile` (ein file-like Objekt). Das ist das tatsächliche Python-Objekt, das Sie direkt anderen Funktionen oder Bibliotheken übergeben können, welche ein „file-like“-Objekt erwarten. + +`UploadFile` hat die folgenden `async`hronen Methoden. Sie alle rufen die entsprechenden Methoden des darunterliegenden Datei-Objekts auf (wobei intern `SpooledTemporaryFile` verwendet wird). + +* `write(daten)`: Schreibt `daten` (`str` oder `bytes`) in die Datei. +* `read(anzahl)`: Liest `anzahl` (`int`) bytes/Zeichen aus der Datei. +* `seek(versatz)`: Geht zur Position `versatz` (`int`) in der Datei. + * Z. B. würde `await myfile.seek(0)` zum Anfang der Datei gehen. + * Das ist besonders dann nützlich, wenn Sie `await myfile.read()` einmal ausführen und dann diese Inhalte erneut auslesen müssen. +* `close()`: Schließt die Datei. + +Da alle diese Methoden `async`hron sind, müssen Sie sie `await`en („erwarten“). + +Zum Beispiel können Sie innerhalb einer `async` *Pfadoperation-Funktion* den Inhalt wie folgt auslesen: + +```Python +contents = await myfile.read() +``` + +Wenn Sie sich innerhalb einer normalen `def`-*Pfadoperation-Funktion* befinden, können Sie direkt auf `UploadFile.file` zugreifen, zum Beispiel: + +```Python +contents = myfile.file.read() +``` + +!!! note "Technische Details zu `async`" + Wenn Sie die `async`-Methoden verwenden, führt **FastAPI** die Datei-Methoden in einem Threadpool aus und erwartet sie. + +!!! note "Technische Details zu Starlette" + **FastAPI**s `UploadFile` erbt direkt von **Starlette**s `UploadFile`, fügt aber ein paar notwendige Teile hinzu, um es kompatibel mit **Pydantic** und anderen Teilen von FastAPI zu machen. + +## Was sind „Formulardaten“ + +HTML-Formulare (`
`) senden die Daten in einer „speziellen“ Kodierung zum Server, welche sich von JSON unterscheidet. + +**FastAPI** stellt sicher, dass diese Daten korrekt ausgelesen werden, statt JSON zu erwarten. + +!!! note "Technische Details" + Daten aus Formularen werden, wenn es keine Dateien sind, normalerweise mit dem „media type“ `application/x-www-form-urlencoded` kodiert. + + Sollte das Formular aber Dateien enthalten, dann werden diese mit `multipart/form-data` kodiert. Wenn Sie `File` verwenden, wird **FastAPI** wissen, dass es die Dateien vom korrekten Teil des Bodys holen muss. + + Wenn Sie mehr über Formularfelder und ihre Kodierungen lesen möchten, besuchen Sie die MDN-Webdokumentation für POST. + +!!! warning "Achtung" + Sie können mehrere `File`- und `Form`-Parameter in einer *Pfadoperation* deklarieren, aber Sie können nicht gleichzeitig auch `Body`-Felder deklarieren, welche Sie als JSON erwarten, da der Request den Body mittels `multipart/form-data` statt `application/json` kodiert. + + Das ist keine Limitation von **FastAPI**, sondern Teil des HTTP-Protokolls. + +## Optionaler Datei-Upload + +Sie können eine Datei optional machen, indem Sie Standard-Typannotationen verwenden und den Defaultwert auf `None` setzen: + +=== "Python 3.10+" + + ```Python hl_lines="9 17" + {!> ../../../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.8+" + + ```Python hl_lines="10 18" + {!> ../../../docs_src/request_files/tutorial001_02_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="7 15" + {!> ../../../docs_src/request_files/tutorial001_02_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="9 17" + {!> ../../../docs_src/request_files/tutorial001_02.py!} + ``` + +## `UploadFile` mit zusätzlichen Metadaten + +Sie können auch `File()` zusammen mit `UploadFile` verwenden, um zum Beispiel zusätzliche Metadaten zu setzen: + +=== "Python 3.9+" + + ```Python hl_lines="9 15" + {!> ../../../docs_src/request_files/tutorial001_03_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="8 14" + {!> ../../../docs_src/request_files/tutorial001_03_an.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="7 13" + {!> ../../../docs_src/request_files/tutorial001_03.py!} + ``` + +## Mehrere Datei-Uploads + +Es ist auch möglich, mehrere Dateien gleichzeitig hochzuladen. + +Diese werden demselben Formularfeld zugeordnet, welches mit den Formulardaten gesendet wird. + +Um das zu machen, deklarieren Sie eine Liste von `bytes` oder `UploadFile`s: + +=== "Python 3.9+" + + ```Python hl_lines="10 15" + {!> ../../../docs_src/request_files/tutorial002_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="11 16" + {!> ../../../docs_src/request_files/tutorial002_an.py!} + ``` + +=== "Python 3.9+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="8 13" + {!> ../../../docs_src/request_files/tutorial002_py39.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="10 15" + {!> ../../../docs_src/request_files/tutorial002.py!} + ``` + +Sie erhalten, wie deklariert, eine `list`e von `bytes` oder `UploadFile`s. + +!!! note "Technische Details" + Sie können auch `from starlette.responses import HTMLResponse` verwenden. + + **FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. + +### Mehrere Datei-Uploads mit zusätzlichen Metadaten + +Und so wie zuvor können Sie `File()` verwenden, um zusätzliche Parameter zu setzen, sogar für `UploadFile`: + +=== "Python 3.9+" + + ```Python hl_lines="11 18-20" + {!> ../../../docs_src/request_files/tutorial003_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="12 19-21" + {!> ../../../docs_src/request_files/tutorial003_an.py!} + ``` + +=== "Python 3.9+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="9 16" + {!> ../../../docs_src/request_files/tutorial003_py39.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="11 18" + {!> ../../../docs_src/request_files/tutorial003.py!} + ``` + +## Zusammenfassung + +Verwenden Sie `File`, `bytes` und `UploadFile`, um hochladbare Dateien im Request zu deklarieren, die als Formulardaten gesendet werden. diff --git a/docs/de/docs/tutorial/request-forms-and-files.md b/docs/de/docs/tutorial/request-forms-and-files.md new file mode 100644 index 0000000000000..86b1406e6116c --- /dev/null +++ b/docs/de/docs/tutorial/request-forms-and-files.md @@ -0,0 +1,69 @@ +# Formulardaten und Dateien im Request + +Sie können gleichzeitig Dateien und Formulardaten mit `File` und `Form` definieren. + +!!! info + Um hochgeladene Dateien und/oder Formulardaten zu empfangen, installieren Sie zuerst `python-multipart`. + + Z. B. `pip install python-multipart`. + +## `File` und `Form` importieren + +=== "Python 3.9+" + + ```Python hl_lines="3" + {!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="1" + {!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="1" + {!> ../../../docs_src/request_forms_and_files/tutorial001.py!} + ``` + +## `File` und `Form`-Parameter definieren + +Erstellen Sie Datei- und Formularparameter, so wie Sie es auch mit `Body` und `Query` machen würden: + +=== "Python 3.9+" + + ```Python hl_lines="10-12" + {!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9-11" + {!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="8" + {!> ../../../docs_src/request_forms_and_files/tutorial001.py!} + ``` + +Die Datei- und Formularfelder werden als Formulardaten hochgeladen, und Sie erhalten diese Dateien und Formularfelder. + +Und Sie können einige der Dateien als `bytes` und einige als `UploadFile` deklarieren. + +!!! warning "Achtung" + Sie können mehrere `File`- und `Form`-Parameter in einer *Pfadoperation* deklarieren, aber Sie können nicht gleichzeitig auch `Body`-Felder deklarieren, welche Sie als JSON erwarten, da der Request den Body mittels `multipart/form-data` statt `application/json` kodiert. + + Das ist keine Limitation von **FastAPI**, sondern Teil des HTTP-Protokolls. + +## Zusammenfassung + +Verwenden Sie `File` und `Form` zusammen, wenn Sie Daten und Dateien zusammen im selben Request empfangen müssen. diff --git a/docs/de/docs/tutorial/request-forms.md b/docs/de/docs/tutorial/request-forms.md new file mode 100644 index 0000000000000..6c029b5fe29e3 --- /dev/null +++ b/docs/de/docs/tutorial/request-forms.md @@ -0,0 +1,92 @@ +# Formulardaten + +Wenn Sie Felder aus Formularen statt JSON empfangen müssen, können Sie `Form` verwenden. + +!!! info + Um Formulare zu verwenden, installieren Sie zuerst `python-multipart`. + + Z. B. `pip install python-multipart`. + +## `Form` importieren + +Importieren Sie `Form` von `fastapi`: + +=== "Python 3.9+" + + ```Python hl_lines="3" + {!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="1" + {!> ../../../docs_src/request_forms/tutorial001_an.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="1" + {!> ../../../docs_src/request_forms/tutorial001.py!} + ``` + +## `Form`-Parameter definieren + +Erstellen Sie Formular-Parameter, so wie Sie es auch mit `Body` und `Query` machen würden: + +=== "Python 3.9+" + + ```Python hl_lines="9" + {!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="8" + {!> ../../../docs_src/request_forms/tutorial001_an.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="7" + {!> ../../../docs_src/request_forms/tutorial001.py!} + ``` + +Zum Beispiel stellt eine der Möglichkeiten, die OAuth2 Spezifikation zu verwenden (genannt „password flow“), die Bedingung, einen `username` und ein `password` als Formularfelder zu senden. + +Die Spec erfordert, dass die Felder exakt `username` und `password` genannt werden und als Formularfelder, nicht JSON, gesendet werden. + +Mit `Form` haben Sie die gleichen Konfigurationsmöglichkeiten wie mit `Body` (und `Query`, `Path`, `Cookie`), inklusive Validierung, Beispielen, einem Alias (z. B. `user-name` statt `username`), usw. + +!!! info + `Form` ist eine Klasse, die direkt von `Body` erbt. + +!!! tip "Tipp" + Um Formularbodys zu deklarieren, verwenden Sie explizit `Form`, da diese Parameter sonst als Query-Parameter oder Body(-JSON)-Parameter interpretiert werden würden. + +## Über „Formularfelder“ + +HTML-Formulare (`
`) senden die Daten in einer „speziellen“ Kodierung zum Server, welche sich von JSON unterscheidet. + +**FastAPI** stellt sicher, dass diese Daten korrekt ausgelesen werden, statt JSON zu erwarten. + +!!! note "Technische Details" + Daten aus Formularen werden normalerweise mit dem „media type“ `application/x-www-form-urlencoded` kodiert. + + Wenn das Formular stattdessen Dateien enthält, werden diese mit `multipart/form-data` kodiert. Im nächsten Kapitel erfahren Sie mehr über die Handhabung von Dateien. + + Wenn Sie mehr über Formularfelder und ihre Kodierungen lesen möchten, besuchen Sie die MDN-Webdokumentation für POST. + +!!! warning "Achtung" + Sie können mehrere `Form`-Parameter in einer *Pfadoperation* deklarieren, aber Sie können nicht gleichzeitig auch `Body`-Felder deklarieren, welche Sie als JSON erwarten, da der Request den Body mittels `application/x-www-form-urlencoded` statt `application/json` kodiert. + + Das ist keine Limitation von **FastAPI**, sondern Teil des HTTP-Protokolls. + +## Zusammenfassung + +Verwenden Sie `Form`, um Eingabe-Parameter für Formulardaten zu deklarieren. diff --git a/docs/de/docs/tutorial/response-model.md b/docs/de/docs/tutorial/response-model.md new file mode 100644 index 0000000000000..d5b92e0f9803f --- /dev/null +++ b/docs/de/docs/tutorial/response-model.md @@ -0,0 +1,486 @@ +# Responsemodell – Rückgabetyp + +Sie können den Typ der Response deklarieren, indem Sie den **Rückgabetyp** der *Pfadoperation* annotieren. + +Hierbei können Sie **Typannotationen** genauso verwenden, wie Sie es bei Werten von Funktions-**Parametern** machen; verwenden Sie Pydantic-Modelle, Listen, Dicts und skalare Werte wie Nummern, Booleans, usw. + +=== "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.8+" + + ```Python hl_lines="18 23" + {!> ../../../docs_src/response_model/tutorial001_01.py!} + ``` + +FastAPI wird diesen Rückgabetyp verwenden, um: + +* Die zurückzugebenden Daten zu **validieren**. + * Wenn die Daten ungültig sind (Sie haben z. B. ein Feld vergessen), bedeutet das, *Ihr* Anwendungscode ist fehlerhaft, er gibt nicht zurück, was er sollte, und daher wird ein Server-Error ausgegeben, statt falscher Daten. So können Sie und ihre Clients sicher sein, dass diese die erwarteten Daten, in der richtigen Form erhalten. +* In der OpenAPI *Pfadoperation* ein **JSON-Schema** für die Response hinzuzufügen. + * Dieses wird von der **automatischen Dokumentation** verwendet. + * Es wird auch von automatisch Client-Code-generierenden Tools verwendet. + +Aber am wichtigsten: + +* Es wird die Ausgabedaten auf das **limitieren und filtern**, was im Rückgabetyp definiert ist. + * Das ist insbesondere für die **Sicherheit** wichtig, mehr dazu unten. + +## `response_model`-Parameter + +Es gibt Fälle, da möchten oder müssen Sie Daten zurückgeben, die nicht genau dem entsprechen, was der Typ deklariert. + +Zum Beispiel könnten Sie **ein Dict zurückgeben** wollen, oder ein Datenbank-Objekt, aber **es als Pydantic-Modell deklarieren**. Auf diese Weise übernimmt das Pydantic-Modell alle Datendokumentation, -validierung, usw. für das Objekt, welches Sie zurückgeben (z. B. ein Dict oder ein Datenbank-Objekt). + +Würden Sie eine hierfür eine Rückgabetyp-Annotation verwenden, dann würden Tools und Editoren (korrekterweise) Fehler ausgeben, die Ihnen sagen, dass Ihre Funktion einen Typ zurückgibt (z. B. ein Dict), der sich unterscheidet von dem, was Sie deklariert haben (z. B. ein Pydantic-Modell). + +In solchen Fällen können Sie statt des Rückgabetyps den **Pfadoperation-Dekorator**-Parameter `response_model` verwenden. + +Sie können `response_model` in jeder möglichen *Pfadoperation* verwenden: + +* `@app.get()` +* `@app.post()` +* `@app.put()` +* `@app.delete()` +* usw. + +=== "Python 3.10+" + + ```Python hl_lines="17 22 24-27" + {!> ../../../docs_src/response_model/tutorial001_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="17 22 24-27" + {!> ../../../docs_src/response_model/tutorial001_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="17 22 24-27" + {!> ../../../docs_src/response_model/tutorial001.py!} + ``` + +!!! note "Hinweis" + Beachten Sie, dass `response_model` ein Parameter der „Dekorator“-Methode ist (`get`, `post`, usw.). Nicht der *Pfadoperation-Funktion*, so wie die anderen Parameter. + +`response_model` nimmt denselben Typ entgegen, den Sie auch für ein Pydantic-Modellfeld deklarieren würden, also etwa ein Pydantic-Modell, aber es kann auch z. B. eine `list`e von Pydantic-Modellen sein, wie etwa `List[Item]`. + +FastAPI wird dieses `response_model` nehmen, um die Daten zu dokumentieren, validieren, usw. und auch, um **die Ausgabedaten** entsprechend der Typdeklaration **zu konvertieren und filtern**. + +!!! tip "Tipp" + Wenn Sie in Ihrem Editor strikte Typchecks haben, mypy, usw., können Sie den Funktions-Rückgabetyp als `Any` deklarieren. + + So sagen Sie dem Editor, dass Sie absichtlich *irgendetwas* zurückgeben. Aber FastAPI wird trotzdem die Dokumentation, Validierung, Filterung, usw. der Daten übernehmen, via `response_model`. + +### `response_model`-Priorität + +Wenn sowohl Rückgabetyp als auch `response_model` deklariert sind, hat `response_model` die Priorität und wird von FastAPI bevorzugt verwendet. + +So können Sie korrekte Typannotationen zu ihrer Funktion hinzufügen, die von ihrem Editor und Tools wie mypy verwendet werden. Und dennoch übernimmt FastAPI die Validierung und Dokumentation, usw., der Daten anhand von `response_model`. + +Sie können auch `response_model=None` verwenden, um das Erstellen eines Responsemodells für diese *Pfadoperation* zu unterbinden. Sie könnten das tun wollen, wenn sie Dinge annotieren, die nicht gültige Pydantic-Felder sind. Ein Beispiel dazu werden Sie in einer der Abschnitte unten sehen. + +## Dieselben Eingabedaten zurückgeben + +Im Folgenden deklarieren wir ein `UserIn`-Modell; es enthält ein Klartext-Passwort: + +=== "Python 3.10+" + + ```Python hl_lines="7 9" + {!> ../../../docs_src/response_model/tutorial002_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9 11" + {!> ../../../docs_src/response_model/tutorial002.py!} + ``` + +!!! info + Um `EmailStr` zu verwenden, installieren Sie zuerst `email_validator`. + + Z. B. `pip install email-validator` + oder `pip install pydantic[email]`. + +Wir verwenden dieses Modell, um sowohl unsere Eingabe- als auch Ausgabedaten zu deklarieren: + +=== "Python 3.10+" + + ```Python hl_lines="16" + {!> ../../../docs_src/response_model/tutorial002_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="18" + {!> ../../../docs_src/response_model/tutorial002.py!} + ``` + +Immer wenn jetzt ein Browser einen Benutzer mit Passwort erzeugt, gibt die API dasselbe Passwort in der Response zurück. + +Hier ist das möglicherweise kein Problem, da es derselbe Benutzer ist, der das Passwort sendet. + +Aber wenn wir dasselbe Modell für eine andere *Pfadoperation* verwenden, könnten wir das Passwort dieses Benutzers zu jedem Client schicken. + +!!! danger "Gefahr" + Speichern Sie niemals das Klartext-Passwort eines Benutzers, oder versenden Sie es in einer Response wie dieser, wenn Sie sich nicht der resultierenden Gefahren bewusst sind und nicht wissen, was Sie tun. + +## Ausgabemodell hinzufügen + +Wir können stattdessen ein Eingabemodell mit dem Klartext-Passwort, und ein Ausgabemodell ohne das Passwort erstellen: + +=== "Python 3.10+" + + ```Python hl_lines="9 11 16" + {!> ../../../docs_src/response_model/tutorial003_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9 11 16" + {!> ../../../docs_src/response_model/tutorial003.py!} + ``` + +Obwohl unsere *Pfadoperation-Funktion* hier denselben `user` von der Eingabe zurückgibt, der das Passwort enthält: + +=== "Python 3.10+" + + ```Python hl_lines="24" + {!> ../../../docs_src/response_model/tutorial003_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="24" + {!> ../../../docs_src/response_model/tutorial003.py!} + ``` + +... haben wir deklariert, dass `response_model` das Modell `UserOut` ist, welches das Passwort nicht enthält: + +=== "Python 3.10+" + + ```Python hl_lines="22" + {!> ../../../docs_src/response_model/tutorial003_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="22" + {!> ../../../docs_src/response_model/tutorial003.py!} + ``` + +Darum wird **FastAPI** sich darum kümmern, dass alle Daten, die nicht im Ausgabemodell deklariert sind, herausgefiltert werden (mittels Pydantic). + +### `response_model` oder Rückgabewert + +Da unsere zwei Modelle in diesem Fall unterschiedlich sind, würde, wenn wir den Rückgabewert der Funktion als `UserOut` deklarieren, der Editor sich beschweren, dass wir einen ungültigen Typ zurückgeben, weil das unterschiedliche Klassen sind. + +Darum müssen wir es in diesem Fall im `response_model`-Parameter deklarieren. + +... aber lesen Sie weiter, um zu sehen, wie man das anders lösen kann. + +## Rückgabewert und Datenfilterung + +Führen wir unser vorheriges Beispiel fort. Wir wollten **die Funktion mit einem Typ annotieren**, aber etwas zurückgeben, das **weniger Daten** enthält. + +Wir möchten auch, dass FastAPI die Daten weiterhin, dem Responsemodell entsprechend, **filtert**. + +Im vorherigen Beispiel mussten wir den `response_model`-Parameter verwenden, weil die Klassen unterschiedlich waren. Das bedeutet aber auch, wir bekommen keine Unterstützung vom Editor und anderen Tools, die den Funktions-Rückgabewert überprüfen. + +Aber in den meisten Fällen, wenn wir so etwas machen, wollen wir nur, dass das Modell einige der Daten **filtert/entfernt**, so wie in diesem Beispiel. + +Und in solchen Fällen können wir Klassen und Vererbung verwenden, um Vorteil aus den Typannotationen in der Funktion zu ziehen, was vom Editor und von Tools besser unterstützt wird, während wir gleichzeitig FastAPIs **Datenfilterung** behalten. + +=== "Python 3.10+" + + ```Python hl_lines="7-10 13-14 18" + {!> ../../../docs_src/response_model/tutorial003_01_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9-13 15-16 20" + {!> ../../../docs_src/response_model/tutorial003_01.py!} + ``` + +Damit erhalten wir Tool-Unterstützung, vom Editor und mypy, da dieser Code hinsichtlich der Typen korrekt ist, aber wir erhalten auch die Datenfilterung von FastAPI. + +Wie funktioniert das? Schauen wir uns das mal an. 🤓 + +### Typannotationen und Tooling + +Sehen wir uns zunächst an, wie Editor, mypy und andere Tools dies sehen würden. + +`BaseUser` verfügt über die Basis-Felder. Dann erbt `UserIn` von `BaseUser` und fügt das Feld `Passwort` hinzu, sodass dass es nun alle Felder beider Modelle hat. + +Wir annotieren den Funktionsrückgabetyp als `BaseUser`, geben aber tatsächlich eine `UserIn`-Instanz zurück. + +Für den Editor, mypy und andere Tools ist das kein Problem, da `UserIn` eine Unterklasse von `BaseUser` ist (Salopp: `UserIn` ist ein `BaseUser`). Es handelt sich um einen *gültigen* Typ, solange irgendetwas überreicht wird, das ein `BaseUser` ist. + +### FastAPI Datenfilterung + +FastAPI seinerseits wird den Rückgabetyp sehen und sicherstellen, dass das, was zurückgegeben wird, **nur** diejenigen Felder enthält, welche im Typ deklariert sind. + +FastAPI macht intern mehrere Dinge mit Pydantic, um sicherzustellen, dass obige Ähnlichkeitsregeln der Klassenvererbung nicht auf die Filterung der zurückgegebenen Daten angewendet werden, sonst könnten Sie am Ende mehr Daten zurückgeben als gewollt. + +Auf diese Weise erhalten Sie das beste beider Welten: Sowohl Typannotationen mit **Tool-Unterstützung** als auch **Datenfilterung**. + +## Anzeige in der Dokumentation + +Wenn Sie sich die automatische Dokumentation betrachten, können Sie sehen, dass Eingabe- und Ausgabemodell beide ihr eigenes JSON-Schema haben: + + + +Und beide Modelle werden auch in der interaktiven API-Dokumentation verwendet: + + + +## Andere Rückgabetyp-Annotationen + +Es kann Fälle geben, bei denen Sie etwas zurückgeben, das kein gültiges Pydantic-Feld ist, und Sie annotieren es in der Funktion nur, um Unterstützung von Tools zu erhalten (Editor, mypy, usw.). + +### Eine Response direkt zurückgeben + +Der häufigste Anwendungsfall ist, wenn Sie [eine Response direkt zurückgeben, wie es später im Handbuch für fortgeschrittene Benutzer erläutert wird](../advanced/response-directly.md){.internal-link target=_blank}. + +```Python hl_lines="8 10-11" +{!> ../../../docs_src/response_model/tutorial003_02.py!} +``` + +Dieser einfache Anwendungsfall wird automatisch von FastAPI gehandhabt, weil die Annotation des Rückgabetyps die Klasse (oder eine Unterklasse von) `Response` ist. + +Und Tools werden auch glücklich sein, weil sowohl `RedirectResponse` als auch `JSONResponse` Unterklassen von `Response` sind, die Typannotation ist daher korrekt. + +### Eine Unterklasse von Response annotieren + +Sie können auch eine Unterklasse von `Response` in der Typannotation verwenden. + +```Python hl_lines="8-9" +{!> ../../../docs_src/response_model/tutorial003_03.py!} +``` + +Das wird ebenfalls funktionieren, weil `RedirectResponse` eine Unterklasse von `Response` ist, und FastAPI sich um diesen einfachen Anwendungsfall automatisch kümmert. + +### Ungültige Rückgabetyp-Annotationen + +Aber wenn Sie ein beliebiges anderes Objekt zurückgeben, das kein gültiger Pydantic-Typ ist (z. B. ein Datenbank-Objekt), und Sie annotieren es so in der Funktion, wird FastAPI versuchen, ein Pydantic-Responsemodell von dieser Typannotation zu erstellen, und scheitern. + +Das gleiche wird passieren, wenn Sie eine Union mehrerer Typen haben, und einer oder mehrere sind nicht gültige Pydantic-Typen. Zum Beispiel funktioniert folgendes nicht 💥: + +=== "Python 3.10+" + + ```Python hl_lines="8" + {!> ../../../docs_src/response_model/tutorial003_04_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="10" + {!> ../../../docs_src/response_model/tutorial003_04.py!} + ``` + +... das scheitert, da die Typannotation kein Pydantic-Typ ist, und auch keine einzelne `Response`-Klasse, oder -Unterklasse, es ist eine Union (eines von beiden) von `Response` und `dict`. + +### Responsemodell deaktivieren + +Beim Beispiel oben fortsetzend, mögen Sie vielleicht die standardmäßige Datenvalidierung, -Dokumentation, -Filterung, usw., die von FastAPI durchgeführt wird, nicht haben. + +Aber Sie möchten dennoch den Rückgabetyp in der Funktion annotieren, um Unterstützung von Editoren und Typcheckern (z. B. mypy) zu erhalten. + +In diesem Fall können Sie die Generierung des Responsemodells abschalten, indem Sie `response_model=None` setzen: + +=== "Python 3.10+" + + ```Python hl_lines="7" + {!> ../../../docs_src/response_model/tutorial003_05_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9" + {!> ../../../docs_src/response_model/tutorial003_05.py!} + ``` + +Das bewirkt, dass FastAPI die Generierung des Responsemodells unterlässt, und damit können Sie jede gewünschte Rückgabetyp-Annotation haben, ohne dass es Ihre FastAPI-Anwendung beeinflusst. 🤓 + +## Parameter für die Enkodierung des Responsemodells + +Ihr Responsemodell könnte Defaultwerte haben, wie: + +=== "Python 3.10+" + + ```Python hl_lines="9 11-12" + {!> ../../../docs_src/response_model/tutorial004_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="11 13-14" + {!> ../../../docs_src/response_model/tutorial004_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="11 13-14" + {!> ../../../docs_src/response_model/tutorial004.py!} + ``` + +* `description: Union[str, None] = None` (oder `str | None = None` in Python 3.10) hat einen Defaultwert `None`. +* `tax: float = 10.5` hat einen Defaultwert `10.5`. +* `tags: List[str] = []` hat eine leere Liste als Defaultwert: `[]`. + +Aber Sie möchten diese vielleicht vom Resultat ausschließen, wenn Sie gar nicht gesetzt wurden. + +Wenn Sie zum Beispiel Modelle mit vielen optionalen Attributen in einer NoSQL-Datenbank haben, und Sie möchten nicht ellenlange JSON-Responses voller Defaultwerte senden. + +### Den `response_model_exclude_unset`-Parameter verwenden + +Sie können den *Pfadoperation-Dekorator*-Parameter `response_model_exclude_unset=True` setzen: + +=== "Python 3.10+" + + ```Python hl_lines="22" + {!> ../../../docs_src/response_model/tutorial004_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="24" + {!> ../../../docs_src/response_model/tutorial004_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="24" + {!> ../../../docs_src/response_model/tutorial004.py!} + ``` + +Die Defaultwerte werden dann nicht in der Response enthalten sein, sondern nur die tatsächlich gesetzten Werte. + +Wenn Sie also den Artikel mit der ID `foo` bei der *Pfadoperation* anfragen, wird (ohne die Defaultwerte) die Response sein: + +```JSON +{ + "name": "Foo", + "price": 50.2 +} +``` + +!!! info + In Pydantic v1 hieß diese Methode `.dict()`, in Pydantic v2 wurde sie deprecated (aber immer noch unterstützt) und in `.model_dump()` umbenannt. + + Die Beispiele hier verwenden `.dict()` für die Kompatibilität mit Pydantic v1, Sie sollten jedoch stattdessen `.model_dump()` verwenden, wenn Sie Pydantic v2 verwenden können. + +!!! info + FastAPI verwendet `.dict()` von Pydantic Modellen, mit dessen `exclude_unset`-Parameter, um das zu erreichen. + +!!! info + Sie können auch: + + * `response_model_exclude_defaults=True` + * `response_model_exclude_none=True` + + verwenden, wie in der Pydantic Dokumentation für `exclude_defaults` und `exclude_none` beschrieben. + +#### Daten mit Werten für Felder mit Defaultwerten + +Aber wenn ihre Daten Werte für Modellfelder mit Defaultwerten haben, wie etwa der Artikel mit der ID `bar`: + +```Python hl_lines="3 5" +{ + "name": "Bar", + "description": "The bartenders", + "price": 62, + "tax": 20.2 +} +``` + +dann werden diese Werte in der Response enthalten sein. + +#### Daten mit den gleichen Werten wie die Defaultwerte + +Wenn Daten die gleichen Werte haben wie ihre Defaultwerte, wie etwa der Artikel mit der ID `baz`: + +```Python hl_lines="3 5-6" +{ + "name": "Baz", + "description": None, + "price": 50.2, + "tax": 10.5, + "tags": [] +} +``` + +dann ist FastAPI klug genug (tatsächlich ist Pydantic klug genug) zu erkennen, dass, obwohl `description`, `tax`, und `tags` die gleichen Werte haben wie ihre Defaultwerte, sie explizit gesetzt wurden (statt dass sie von den Defaultwerten genommen wurden). + +Diese Felder werden also in der JSON-Response enthalten sein. + +!!! tip "Tipp" + Beachten Sie, dass Defaultwerte alles Mögliche sein können, nicht nur `None`. + + Sie können eine Liste (`[]`), ein `float` `10.5`, usw. sein. + +### `response_model_include` und `response_model_exclude` + +Sie können auch die Parameter `response_model_include` und `response_model_exclude` im **Pfadoperation-Dekorator** verwenden. + +Diese nehmen ein `set` von `str`s entgegen, welches Namen von Attributen sind, die eingeschlossen (ohne die Anderen) oder ausgeschlossen (nur die Anderen) werden sollen. + +Das kann als schnelle Abkürzung verwendet werden, wenn Sie nur ein Pydantic-Modell haben und ein paar Daten von der Ausgabe ausschließen wollen. + +!!! tip "Tipp" + Es wird dennoch empfohlen, dass Sie die Ideen von oben verwenden, also mehrere Klassen statt dieser Parameter. + + Der Grund ist, dass das das generierte JSON-Schema in der OpenAPI ihrer Anwendung (und deren Dokumentation) dennoch das komplette Modell abbildet, selbst wenn Sie `response_model_include` oder `response_model_exclude` verwenden, um einige Attribute auszuschließen. + + Das trifft auch auf `response_model_by_alias` zu, welches ähnlich funktioniert. + +=== "Python 3.10+" + + ```Python hl_lines="29 35" + {!> ../../../docs_src/response_model/tutorial005_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="31 37" + {!> ../../../docs_src/response_model/tutorial005.py!} + ``` + +!!! tip "Tipp" + Die Syntax `{"name", "description"}` erzeugt ein `set` mit diesen zwei Werten. + + Äquivalent zu `set(["name", "description"])`. + +#### `list`en statt `set`s verwenden + +Wenn Sie vergessen, ein `set` zu verwenden, und stattdessen eine `list`e oder ein `tuple` übergeben, wird FastAPI die dennoch in ein `set` konvertieren, und es wird korrekt funktionieren: + +=== "Python 3.10+" + + ```Python hl_lines="29 35" + {!> ../../../docs_src/response_model/tutorial006_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="31 37" + {!> ../../../docs_src/response_model/tutorial006.py!} + ``` + +## Zusammenfassung + +Verwenden Sie den Parameter `response_model` im *Pfadoperation-Dekorator*, um Responsemodelle zu definieren, und besonders, um private Daten herauszufiltern. + +Verwenden Sie `response_model_exclude_unset`, um nur explizit gesetzte Werte zurückzugeben. diff --git a/docs/de/docs/tutorial/schema-extra-example.md b/docs/de/docs/tutorial/schema-extra-example.md new file mode 100644 index 0000000000000..e8bfc987666c9 --- /dev/null +++ b/docs/de/docs/tutorial/schema-extra-example.md @@ -0,0 +1,326 @@ +# Beispiel-Request-Daten deklarieren + +Sie können Beispiele für die Daten deklarieren, die Ihre Anwendung empfangen kann. + +Hier sind mehrere Möglichkeiten, das zu tun. + +## Zusätzliche JSON-Schemadaten in Pydantic-Modellen + +Sie können `examples` („Beispiele“) für ein Pydantic-Modell deklarieren, welche dem generierten JSON-Schema hinzugefügt werden. + +=== "Python 3.10+ Pydantic v2" + + ```Python hl_lines="13-24" + {!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!} + ``` + +=== "Python 3.10+ Pydantic v1" + + ```Python hl_lines="13-23" + {!> ../../../docs_src/schema_extra_example/tutorial001_py310_pv1.py!} + ``` + +=== "Python 3.8+ Pydantic v2" + + ```Python hl_lines="15-26" + {!> ../../../docs_src/schema_extra_example/tutorial001.py!} + ``` + +=== "Python 3.8+ Pydantic v1" + + ```Python hl_lines="15-25" + {!> ../../../docs_src/schema_extra_example/tutorial001_pv1.py!} + ``` + +Diese zusätzlichen Informationen werden unverändert zum für dieses Modell ausgegebenen **JSON-Schema** hinzugefügt und in der API-Dokumentation verwendet. + +=== "Pydantic v2" + + In Pydantic Version 2 würden Sie das Attribut `model_config` verwenden, das ein `dict` akzeptiert, wie beschrieben in Pydantic-Dokumentation: Configuration. + + Sie können `json_schema_extra` setzen, mit einem `dict`, das alle zusätzlichen Daten enthält, die im generierten JSON-Schema angezeigt werden sollen, einschließlich `examples`. + +=== "Pydantic v1" + + In Pydantic Version 1 würden Sie eine interne Klasse `Config` und `schema_extra` verwenden, wie beschrieben in Pydantic-Dokumentation: Schema customization. + + Sie können `schema_extra` setzen, mit einem `dict`, das alle zusätzlichen Daten enthält, die im generierten JSON-Schema angezeigt werden sollen, einschließlich `examples`. + +!!! tip "Tipp" + Mit derselben Technik können Sie das JSON-Schema erweitern und Ihre eigenen benutzerdefinierten Zusatzinformationen hinzufügen. + + Sie könnten das beispielsweise verwenden, um Metadaten für eine Frontend-Benutzeroberfläche usw. hinzuzufügen. + +!!! info + OpenAPI 3.1.0 (verwendet seit FastAPI 0.99.0) hat Unterstützung für `examples` hinzugefügt, was Teil des **JSON Schema** Standards ist. + + Zuvor unterstützte es nur das Schlüsselwort `example` mit einem einzigen Beispiel. Dieses wird weiterhin von OpenAPI 3.1.0 unterstützt, ist jedoch deprecated und nicht Teil des JSON Schema Standards. Wir empfehlen Ihnen daher, von `example` nach `examples` zu migrieren. 🤓 + + Mehr erfahren Sie am Ende dieser Seite. + +## Zusätzliche Argumente für `Field` + +Wenn Sie `Field()` mit Pydantic-Modellen verwenden, können Sie ebenfalls zusätzliche `examples` deklarieren: + +=== "Python 3.10+" + + ```Python hl_lines="2 8-11" + {!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="4 10-13" + {!> ../../../docs_src/schema_extra_example/tutorial002.py!} + ``` + +## `examples` im JSON-Schema – OpenAPI + +Bei Verwendung von: + +* `Path()` +* `Query()` +* `Header()` +* `Cookie()` +* `Body()` +* `Form()` +* `File()` + +können Sie auch eine Gruppe von `examples` mit zusätzlichen Informationen deklarieren, die zu ihren **JSON-Schemas** innerhalb von **OpenAPI** hinzugefügt werden. + +### `Body` mit `examples` + +Hier übergeben wir `examples`, welches ein einzelnes Beispiel für die in `Body()` erwarteten Daten enthält: + +=== "Python 3.10+" + + ```Python hl_lines="22-29" + {!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="22-29" + {!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="23-30" + {!> ../../../docs_src/schema_extra_example/tutorial003_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="18-25" + {!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="20-27" + {!> ../../../docs_src/schema_extra_example/tutorial003.py!} + ``` + +### Beispiel in der Dokumentations-Benutzeroberfläche + +Mit jeder der oben genannten Methoden würde es in `/docs` so aussehen: + + + +### `Body` mit mehreren `examples` + +Sie können natürlich auch mehrere `examples` übergeben: + +=== "Python 3.10+" + + ```Python hl_lines="23-38" + {!> ../../../docs_src/schema_extra_example/tutorial004_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="23-38" + {!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="24-39" + {!> ../../../docs_src/schema_extra_example/tutorial004_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="19-34" + {!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="21-36" + {!> ../../../docs_src/schema_extra_example/tutorial004.py!} + ``` + +Wenn Sie das tun, werden die Beispiele Teil des internen **JSON-Schemas** für diese Body-Daten. + +Während dies geschrieben wird, unterstützt Swagger UI, das für die Anzeige der Dokumentations-Benutzeroberfläche zuständige Tool, jedoch nicht die Anzeige mehrerer Beispiele für die Daten in **JSON Schema**. Aber lesen Sie unten für einen Workaround weiter. + +### OpenAPI-spezifische `examples` + +Schon bevor **JSON Schema** `examples` unterstützte, unterstützte OpenAPI ein anderes Feld, das auch `examples` genannt wurde. + +Diese **OpenAPI-spezifischen** `examples` finden sich in einem anderen Abschnitt der OpenAPI-Spezifikation. Sie sind **Details für jede *Pfadoperation***, nicht für jedes JSON-Schema. + +Und Swagger UI unterstützt dieses spezielle Feld `examples` schon seit einiger Zeit. Sie können es also verwenden, um verschiedene **Beispiele in der Benutzeroberfläche der Dokumentation anzuzeigen**. + +Das Format dieses OpenAPI-spezifischen Felds `examples` ist ein `dict` mit **mehreren Beispielen** (anstelle einer `list`e), jedes mit zusätzlichen Informationen, die auch zu **OpenAPI** hinzugefügt werden. + +Dies erfolgt nicht innerhalb jedes in OpenAPI enthaltenen JSON-Schemas, sondern außerhalb, in der *Pfadoperation*. + +### Verwendung des Parameters `openapi_examples` + +Sie können die OpenAPI-spezifischen `examples` in FastAPI mit dem Parameter `openapi_examples` deklarieren, für: + +* `Path()` +* `Query()` +* `Header()` +* `Cookie()` +* `Body()` +* `Form()` +* `File()` + +Die Schlüssel des `dict` identifizieren jedes Beispiel, und jeder Wert (`"value"`) ist ein weiteres `dict`. + +Jedes spezifische Beispiel-`dict` in den `examples` kann Folgendes enthalten: + +* `summary`: Kurze Beschreibung für das Beispiel. +* `description`: Eine lange Beschreibung, die Markdown-Text enthalten kann. +* `value`: Dies ist das tatsächlich angezeigte Beispiel, z. B. ein `dict`. +* `externalValue`: Alternative zu `value`, eine URL, die auf das Beispiel verweist. Allerdings wird dies möglicherweise nicht von so vielen Tools unterstützt wie `value`. + +Sie können es so verwenden: + +=== "Python 3.10+" + + ```Python hl_lines="23-49" + {!> ../../../docs_src/schema_extra_example/tutorial005_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="23-49" + {!> ../../../docs_src/schema_extra_example/tutorial005_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="24-50" + {!> ../../../docs_src/schema_extra_example/tutorial005_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="19-45" + {!> ../../../docs_src/schema_extra_example/tutorial005_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="21-47" + {!> ../../../docs_src/schema_extra_example/tutorial005.py!} + ``` + +### OpenAPI-Beispiele in der Dokumentations-Benutzeroberfläche + +Wenn `openapi_examples` zu `Body()` hinzugefügt wird, würde `/docs` so aussehen: + + + +## Technische Details + +!!! tip "Tipp" + Wenn Sie bereits **FastAPI** Version **0.99.0 oder höher** verwenden, können Sie diese Details wahrscheinlich **überspringen**. + + Sie sind für ältere Versionen relevanter, bevor OpenAPI 3.1.0 verfügbar war. + + Sie können dies als eine kurze **Geschichtsstunde** zu OpenAPI und JSON Schema betrachten. 🤓 + +!!! warning "Achtung" + Dies sind sehr technische Details zu den Standards **JSON Schema** und **OpenAPI**. + + Wenn die oben genannten Ideen bereits für Sie funktionieren, reicht das möglicherweise aus und Sie benötigen diese Details wahrscheinlich nicht, überspringen Sie sie gerne. + +Vor OpenAPI 3.1.0 verwendete OpenAPI eine ältere und modifizierte Version von **JSON Schema**. + +JSON Schema hatte keine `examples`, daher fügte OpenAPI seiner eigenen modifizierten Version ein eigenes `example`-Feld hinzu. + +OpenAPI fügte auch die Felder `example` und `examples` zu anderen Teilen der Spezifikation hinzu: + +* `Parameter Object` (in der Spezifikation), das verwendet wurde von FastAPIs: + * `Path()` + * `Query()` + * `Header()` + * `Cookie()` +* `Request Body Object` im Feld `content` des `Media Type Object`s (in der Spezifikation), das verwendet wurde von FastAPIs: + * `Body()` + * `File()` + * `Form()` + +!!! info + Dieser alte, OpenAPI-spezifische `examples`-Parameter heißt seit FastAPI `0.103.0` jetzt `openapi_examples`. + +### JSON Schemas Feld `examples` + +Aber dann fügte JSON Schema ein `examples`-Feld zu einer neuen Version der Spezifikation hinzu. + +Und dann basierte das neue OpenAPI 3.1.0 auf der neuesten Version (JSON Schema 2020-12), die dieses neue Feld `examples` enthielt. + +Und jetzt hat dieses neue `examples`-Feld Vorrang vor dem alten (und benutzerdefinierten) `example`-Feld, im Singular, das jetzt deprecated ist. + +Dieses neue `examples`-Feld in JSON Schema ist **nur eine `list`e** von Beispielen, kein Dict mit zusätzlichen Metadaten wie an den anderen Stellen in OpenAPI (oben beschrieben). + +!!! info + Selbst, nachdem OpenAPI 3.1.0 veröffentlicht wurde, mit dieser neuen, einfacheren Integration mit JSON Schema, unterstützte Swagger UI, das Tool, das die automatische Dokumentation bereitstellt, eine Zeit lang OpenAPI 3.1.0 nicht (das tut es seit Version 5.0.0 🎉). + + Aus diesem Grund verwendeten Versionen von FastAPI vor 0.99.0 immer noch Versionen von OpenAPI vor 3.1.0. + +### Pydantic- und FastAPI-`examples` + +Wenn Sie `examples` innerhalb eines Pydantic-Modells hinzufügen, indem Sie `schema_extra` oder `Field(examples=["something"])` verwenden, wird dieses Beispiel dem **JSON-Schema** für dieses Pydantic-Modell hinzugefügt. + +Und dieses **JSON-Schema** des Pydantic-Modells ist in der **OpenAPI** Ihrer API enthalten und wird dann in der Benutzeroberfläche der Dokumentation verwendet. + +In Versionen von FastAPI vor 0.99.0 (0.99.0 und höher verwenden das neuere OpenAPI 3.1.0), wenn Sie `example` oder `examples` mit einem der anderen Werkzeuge (`Query()`, `Body()`, usw.) verwendet haben, wurden diese Beispiele nicht zum JSON-Schema hinzugefügt, das diese Daten beschreibt (nicht einmal zur OpenAPI-eigenen Version von JSON Schema), sondern direkt zur *Pfadoperation*-Deklaration in OpenAPI (außerhalb der Teile von OpenAPI, die JSON Schema verwenden). + +Aber jetzt, da FastAPI 0.99.0 und höher, OpenAPI 3.1.0 verwendet, das JSON Schema 2020-12 verwendet, und Swagger UI 5.0.0 und höher, ist alles konsistenter und die Beispiele sind in JSON Schema enthalten. + +### Swagger-Benutzeroberfläche und OpenAPI-spezifische `examples`. + +Da die Swagger-Benutzeroberfläche derzeit nicht mehrere JSON Schema Beispiele unterstützt (Stand: 26.08.2023), hatten Benutzer keine Möglichkeit, mehrere Beispiele in der Dokumentation anzuzeigen. + +Um dieses Problem zu lösen, hat FastAPI `0.103.0` **Unterstützung** für die Deklaration desselben alten **OpenAPI-spezifischen** `examples`-Felds mit dem neuen Parameter `openapi_examples` hinzugefügt. 🤓 + +### Zusammenfassung + +Ich habe immer gesagt, dass ich Geschichte nicht so sehr mag ... und jetzt schauen Sie mich an, wie ich „Technikgeschichte“-Unterricht gebe. 😅 + +Kurz gesagt: **Upgraden Sie auf FastAPI 0.99.0 oder höher**, und die Dinge sind viel **einfacher, konsistenter und intuitiver**, und Sie müssen nicht alle diese historischen Details kennen. 😎 diff --git a/docs/de/docs/tutorial/security/first-steps.md b/docs/de/docs/tutorial/security/first-steps.md new file mode 100644 index 0000000000000..1e75fa8d939fc --- /dev/null +++ b/docs/de/docs/tutorial/security/first-steps.md @@ -0,0 +1,233 @@ +# Sicherheit – Erste Schritte + +Stellen wir uns vor, dass Sie Ihre **Backend**-API auf einer Domain haben. + +Und Sie haben ein **Frontend** auf einer anderen Domain oder in einem anderen Pfad derselben Domain (oder in einer mobilen Anwendung). + +Und Sie möchten eine Möglichkeit haben, dass sich das Frontend mithilfe eines **Benutzernamens** und eines **Passworts** beim Backend authentisieren kann. + +Wir können **OAuth2** verwenden, um das mit **FastAPI** zu erstellen. + +Aber ersparen wir Ihnen die Zeit, die gesamte lange Spezifikation zu lesen, nur um die kleinen Informationen zu finden, die Sie benötigen. + +Lassen Sie uns die von **FastAPI** bereitgestellten Tools verwenden, um Sicherheit zu gewährleisten. + +## Wie es aussieht + +Lassen Sie uns zunächst einfach den Code verwenden und sehen, wie er funktioniert, und dann kommen wir zurück, um zu verstehen, was passiert. + +## `main.py` erstellen + +Kopieren Sie das Beispiel in eine Datei `main.py`: + +=== "Python 3.9+" + + ```Python + {!> ../../../docs_src/security/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python + {!> ../../../docs_src/security/tutorial001_an.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python + {!> ../../../docs_src/security/tutorial001.py!} + ``` + +## Ausführen + +!!! info + Um hochgeladene Dateien zu empfangen, installieren Sie zuerst `python-multipart`. + + Z. B. `pip install python-multipart`. + + Das, weil **OAuth2** „Formulardaten“ zum Senden von `username` und `password` verwendet. + +Führen Sie das Beispiel aus mit: + +
+ +```console +$ uvicorn main:app --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +## Überprüfen + +Gehen Sie zu der interaktiven Dokumentation unter: http://127.0.0.1:8000/docs. + +Sie werden etwa Folgendes sehen: + + + +!!! check "Authorize-Button!" + Sie haben bereits einen glänzenden, neuen „Authorize“-Button. + + Und Ihre *Pfadoperation* hat in der oberen rechten Ecke ein kleines Schloss, auf das Sie klicken können. + +Und wenn Sie darauf klicken, erhalten Sie ein kleines Anmeldeformular zur Eingabe eines `username` und `password` (und anderer optionaler Felder): + + + +!!! note "Hinweis" + Es spielt keine Rolle, was Sie in das Formular eingeben, es wird noch nicht funktionieren. Wir kommen dahin. + +Dies ist natürlich nicht das Frontend für die Endbenutzer, aber es ist ein großartiges automatisches Tool, um Ihre gesamte API interaktiv zu dokumentieren. + +Es kann vom Frontend-Team verwendet werden (das auch Sie selbst sein können). + +Es kann von Anwendungen und Systemen Dritter verwendet werden. + +Und es kann auch von Ihnen selbst verwendet werden, um dieselbe Anwendung zu debuggen, zu prüfen und zu testen. + +## Der `password`-Flow + +Lassen Sie uns nun etwas zurückgehen und verstehen, was das alles ist. + +Der `password`-„Flow“ ist eine der in OAuth2 definierten Wege („Flows“) zur Handhabung von Sicherheit und Authentifizierung. + +OAuth2 wurde so konzipiert, dass das Backend oder die API unabhängig vom Server sein kann, der den Benutzer authentifiziert. + +In diesem Fall handhabt jedoch dieselbe **FastAPI**-Anwendung sowohl die API als auch die Authentifizierung. + +Betrachten wir es also aus dieser vereinfachten Sicht: + +* Der Benutzer gibt den `username` und das `password` im Frontend ein und drückt `Enter`. +* Das Frontend (das im Browser des Benutzers läuft) sendet diesen `username` und das `password` an eine bestimmte URL in unserer API (deklariert mit `tokenUrl="token"`). +* Die API überprüft den `username` und das `password` und antwortet mit einem „Token“ (wir haben davon noch nichts implementiert). + * Ein „Token“ ist lediglich ein String mit einem Inhalt, den wir später verwenden können, um diesen Benutzer zu verifizieren. + * Normalerweise läuft ein Token nach einiger Zeit ab. + * Daher muss sich der Benutzer irgendwann später erneut anmelden. + * Und wenn der Token gestohlen wird, ist das Risiko geringer. Es handelt sich nicht um einen dauerhaften Schlüssel, der (in den meisten Fällen) für immer funktioniert. +* Das Frontend speichert diesen Token vorübergehend irgendwo. +* Der Benutzer klickt im Frontend, um zu einem anderen Abschnitt der Frontend-Web-Anwendung zu gelangen. +* Das Frontend muss weitere Daten von der API abrufen. + * Es benötigt jedoch eine Authentifizierung für diesen bestimmten Endpunkt. + * Um sich also bei unserer API zu authentifizieren, sendet es einen Header `Authorization` mit dem Wert `Bearer` plus dem Token. + * Wenn der Token `foobar` enthielte, wäre der Inhalt des `Authorization`-Headers: `Bearer foobar`. + +## **FastAPI**s `OAuth2PasswordBearer` + +**FastAPI** bietet mehrere Tools auf unterschiedlichen Abstraktionsebenen zur Implementierung dieser Sicherheitsfunktionen. + +In diesem Beispiel verwenden wir **OAuth2** mit dem **Password**-Flow und einem **Bearer**-Token. Wir machen das mit der Klasse `OAuth2PasswordBearer`. + +!!! info + Ein „Bearer“-Token ist nicht die einzige Option. + + Aber es ist die beste für unseren Anwendungsfall. + + Und es ist wahrscheinlich auch für die meisten anderen Anwendungsfälle die beste, es sei denn, Sie sind ein OAuth2-Experte und wissen genau, warum es eine andere Option gibt, die Ihren Anforderungen besser entspricht. + + In dem Fall gibt Ihnen **FastAPI** ebenfalls die Tools, die Sie zum Erstellen brauchen. + +Wenn wir eine Instanz der Klasse `OAuth2PasswordBearer` erstellen, übergeben wir den Parameter `tokenUrl`. Dieser Parameter enthält die URL, die der Client (das Frontend, das im Browser des Benutzers ausgeführt wird) verwendet, wenn er den `username` und das `password` sendet, um einen Token zu erhalten. + +=== "Python 3.9+" + + ```Python hl_lines="8" + {!> ../../../docs_src/security/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="7" + {!> ../../../docs_src/security/tutorial001_an.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="6" + {!> ../../../docs_src/security/tutorial001.py!} + ``` + +!!! tip "Tipp" + Hier bezieht sich `tokenUrl="token"` auf eine relative URL `token`, die wir noch nicht erstellt haben. Da es sich um eine relative URL handelt, entspricht sie `./token`. + + Da wir eine relative URL verwenden, würde sich das, wenn sich Ihre API unter `https://example.com/` befindet, auf `https://example.com/token` beziehen. Wenn sich Ihre API jedoch unter `https://example.com/api/v1/` befände, würde es sich auf `https://example.com/api/v1/token` beziehen. + + Die Verwendung einer relativen URL ist wichtig, um sicherzustellen, dass Ihre Anwendung auch in einem fortgeschrittenen Anwendungsfall, wie [hinter einem Proxy](../../advanced/behind-a-proxy.md){.internal-link target=_blank}, weiterhin funktioniert. + +Dieser Parameter erstellt nicht diesen Endpunkt / diese *Pfadoperation*, sondern deklariert, dass die URL `/token` diejenige sein wird, die der Client verwenden soll, um den Token abzurufen. Diese Information wird in OpenAPI und dann in den interaktiven API-Dokumentationssystemen verwendet. + +Wir werden demnächst auch die eigentliche Pfadoperation erstellen. + +!!! info + Wenn Sie ein sehr strenger „Pythonista“ sind, missfällt Ihnen möglicherweise die Schreibweise des Parameternamens `tokenUrl` anstelle von `token_url`. + + Das liegt daran, dass FastAPI denselben Namen wie in der OpenAPI-Spezifikation verwendet. Sodass Sie, wenn Sie mehr über eines dieser Sicherheitsschemas herausfinden möchten, den Namen einfach kopieren und einfügen können, um weitere Informationen darüber zu erhalten. + +Die Variable `oauth2_scheme` ist eine Instanz von `OAuth2PasswordBearer`, aber auch ein „Callable“. + +Es könnte wie folgt aufgerufen werden: + +```Python +oauth2_scheme(some, parameters) +``` + +Es kann also mit `Depends` verwendet werden. + +### Verwendung + +Jetzt können Sie dieses `oauth2_scheme` als Abhängigkeit `Depends` übergeben. + +=== "Python 3.9+" + + ```Python hl_lines="12" + {!> ../../../docs_src/security/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="11" + {!> ../../../docs_src/security/tutorial001_an.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="10" + {!> ../../../docs_src/security/tutorial001.py!} + ``` + +Diese Abhängigkeit stellt einen `str` bereit, der dem Parameter `token` der *Pfadoperation-Funktion* zugewiesen wird. + +**FastAPI** weiß, dass es diese Abhängigkeit verwenden kann, um ein „Sicherheitsschema“ im OpenAPI-Schema (und der automatischen API-Dokumentation) zu definieren. + +!!! info "Technische Details" + **FastAPI** weiß, dass es die Klasse `OAuth2PasswordBearer` (deklariert in einer Abhängigkeit) verwenden kann, um das Sicherheitsschema in OpenAPI zu definieren, da es von `fastapi.security.oauth2.OAuth2` erbt, das wiederum von `fastapi.security.base.SecurityBase` erbt. + + Alle Sicherheits-Werkzeuge, die in OpenAPI integriert sind (und die automatische API-Dokumentation), erben von `SecurityBase`, so weiß **FastAPI**, wie es sie in OpenAPI integrieren muss. + +## Was es macht + +FastAPI wird im Request nach diesem `Authorization`-Header suchen, prüfen, ob der Wert `Bearer` plus ein Token ist, und den Token als `str` zurückgeben. + +Wenn es keinen `Authorization`-Header sieht, oder der Wert keinen `Bearer`-Token hat, antwortet es direkt mit einem 401-Statuscode-Error (`UNAUTHORIZED`). + +Sie müssen nicht einmal prüfen, ob der Token existiert, um einen Fehler zurückzugeben. Seien Sie sicher, dass Ihre Funktion, wenn sie ausgeführt wird, ein `str` in diesem Token enthält. + +Sie können das bereits in der interaktiven Dokumentation ausprobieren: + + + +Wir überprüfen im Moment noch nicht die Gültigkeit des Tokens, aber das ist bereits ein Anfang. + +## Zusammenfassung + +Mit nur drei oder vier zusätzlichen Zeilen haben Sie also bereits eine primitive Form der Sicherheit. diff --git a/docs/de/docs/tutorial/security/get-current-user.md b/docs/de/docs/tutorial/security/get-current-user.md new file mode 100644 index 0000000000000..09b55a20e8d08 --- /dev/null +++ b/docs/de/docs/tutorial/security/get-current-user.md @@ -0,0 +1,288 @@ +# Aktuellen Benutzer abrufen + +Im vorherigen Kapitel hat das Sicherheitssystem (das auf dem Dependency Injection System basiert) der *Pfadoperation-Funktion* einen `token` vom Typ `str` überreicht: + +=== "Python 3.9+" + + ```Python hl_lines="12" + {!> ../../../docs_src/security/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="11" + {!> ../../../docs_src/security/tutorial001_an.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="10" + {!> ../../../docs_src/security/tutorial001.py!} + ``` + +Aber das ist immer noch nicht so nützlich. + +Lassen wir es uns den aktuellen Benutzer überreichen. + +## Ein Benutzermodell erstellen + +Erstellen wir zunächst ein Pydantic-Benutzermodell. + +So wie wir Pydantic zum Deklarieren von Bodys verwenden, können wir es auch überall sonst verwenden: + +=== "Python 3.10+" + + ```Python hl_lines="5 12-16" + {!> ../../../docs_src/security/tutorial002_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="5 12-16" + {!> ../../../docs_src/security/tutorial002_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="5 13-17" + {!> ../../../docs_src/security/tutorial002_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="3 10-14" + {!> ../../../docs_src/security/tutorial002_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="5 12-16" + {!> ../../../docs_src/security/tutorial002.py!} + ``` + +## Eine `get_current_user`-Abhängigkeit erstellen + +Erstellen wir eine Abhängigkeit `get_current_user`. + +Erinnern Sie sich, dass Abhängigkeiten Unterabhängigkeiten haben können? + +`get_current_user` wird seinerseits von `oauth2_scheme` abhängen, das wir zuvor erstellt haben. + +So wie wir es zuvor in der *Pfadoperation* direkt gemacht haben, erhält unsere neue Abhängigkeit `get_current_user` von der Unterabhängigkeit `oauth2_scheme` einen `token` vom Typ `str`: + +=== "Python 3.10+" + + ```Python hl_lines="25" + {!> ../../../docs_src/security/tutorial002_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="25" + {!> ../../../docs_src/security/tutorial002_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="26" + {!> ../../../docs_src/security/tutorial002_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="23" + {!> ../../../docs_src/security/tutorial002_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="25" + {!> ../../../docs_src/security/tutorial002.py!} + ``` + +## Den Benutzer holen + +`get_current_user` wird eine von uns erstellte (gefakte) Hilfsfunktion verwenden, welche einen Token vom Typ `str` entgegennimmt und unser Pydantic-`User`-Modell zurückgibt: + +=== "Python 3.10+" + + ```Python hl_lines="19-22 26-27" + {!> ../../../docs_src/security/tutorial002_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="19-22 26-27" + {!> ../../../docs_src/security/tutorial002_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="20-23 27-28" + {!> ../../../docs_src/security/tutorial002_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="17-20 24-25" + {!> ../../../docs_src/security/tutorial002_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="19-22 26-27" + {!> ../../../docs_src/security/tutorial002.py!} + ``` + +## Den aktuellen Benutzer einfügen + +Und jetzt können wir wiederum `Depends` mit unserem `get_current_user` in der *Pfadoperation* verwenden: + +=== "Python 3.10+" + + ```Python hl_lines="31" + {!> ../../../docs_src/security/tutorial002_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="31" + {!> ../../../docs_src/security/tutorial002_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="32" + {!> ../../../docs_src/security/tutorial002_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="29" + {!> ../../../docs_src/security/tutorial002_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="31" + {!> ../../../docs_src/security/tutorial002.py!} + ``` + +Beachten Sie, dass wir als Typ von `current_user` das Pydantic-Modell `User` deklarieren. + +Das wird uns innerhalb der Funktion bei Codevervollständigung und Typprüfungen helfen. + +!!! tip "Tipp" + Sie erinnern sich vielleicht, dass Requestbodys ebenfalls mit Pydantic-Modellen deklariert werden. + + Weil Sie `Depends` verwenden, wird **FastAPI** hier aber nicht verwirrt. + +!!! check + Die Art und Weise, wie dieses System von Abhängigkeiten konzipiert ist, ermöglicht es uns, verschiedene Abhängigkeiten (verschiedene „Dependables“) zu haben, die alle ein `User`-Modell zurückgeben. + + Wir sind nicht darauf beschränkt, nur eine Abhängigkeit zu haben, die diesen Typ von Daten zurückgeben kann. + +## Andere Modelle + +Sie können jetzt den aktuellen Benutzer direkt in den *Pfadoperation-Funktionen* abrufen und die Sicherheitsmechanismen auf **Dependency Injection** Ebene handhaben, mittels `Depends`. + +Und Sie können alle Modelle und Daten für die Sicherheitsanforderungen verwenden (in diesem Fall ein Pydantic-Modell `User`). + +Sie sind jedoch nicht auf die Verwendung von bestimmten Datenmodellen, Klassen, oder Typen beschränkt. + +Möchten Sie eine `id` und eine `email` und keinen `username` in Ihrem Modell haben? Kein Problem. Sie können dieselben Tools verwenden. + +Möchten Sie nur ein `str` haben? Oder nur ein `dict`? Oder direkt eine Instanz eines Modells einer Datenbank-Klasse? Es funktioniert alles auf die gleiche Weise. + +Sie haben eigentlich keine Benutzer, die sich bei Ihrer Anwendung anmelden, sondern Roboter, Bots oder andere Systeme, die nur über einen Zugriffstoken verfügen? Auch hier funktioniert alles gleich. + +Verwenden Sie einfach jede Art von Modell, jede Art von Klasse, jede Art von Datenbank, die Sie für Ihre Anwendung benötigen. **FastAPI** deckt das alles mit seinem Dependency Injection System ab. + +## Codegröße + +Dieses Beispiel mag ausführlich erscheinen. Bedenken Sie, dass wir Sicherheit, Datenmodelle, Hilfsfunktionen und *Pfadoperationen* in derselben Datei vermischen. + +Aber hier ist der entscheidende Punkt. + +Der Code für Sicherheit und Dependency Injection wird einmal geschrieben. + +Sie können es so komplex gestalten, wie Sie möchten. Und dennoch haben Sie es nur einmal geschrieben, an einer einzigen Stelle. Mit all der Flexibilität. + +Aber Sie können Tausende von Endpunkten (*Pfadoperationen*) haben, die dasselbe Sicherheitssystem verwenden. + +Und alle (oder beliebige Teile davon) können Vorteil ziehen aus der Wiederverwendung dieser und anderer von Ihnen erstellter Abhängigkeiten. + +Und alle diese Tausenden von *Pfadoperationen* können nur drei Zeilen lang sein: + +=== "Python 3.10+" + + ```Python hl_lines="30-32" + {!> ../../../docs_src/security/tutorial002_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="30-32" + {!> ../../../docs_src/security/tutorial002_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="31-33" + {!> ../../../docs_src/security/tutorial002_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="28-30" + {!> ../../../docs_src/security/tutorial002_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="30-32" + {!> ../../../docs_src/security/tutorial002.py!} + ``` + +## Zusammenfassung + +Sie können jetzt den aktuellen Benutzer direkt in Ihrer *Pfadoperation-Funktion* abrufen. + +Wir haben bereits die Hälfte geschafft. + +Wir müssen jetzt nur noch eine *Pfadoperation* hinzufügen, mittels der der Benutzer/Client tatsächlich seinen `username` und `password` senden kann. + +Das kommt als nächstes. diff --git a/docs/de/docs/tutorial/security/index.md b/docs/de/docs/tutorial/security/index.md new file mode 100644 index 0000000000000..7a11e704dcfa0 --- /dev/null +++ b/docs/de/docs/tutorial/security/index.md @@ -0,0 +1,101 @@ +# Sicherheit + +Es gibt viele Wege, Sicherheit, Authentifizierung und Autorisierung zu handhaben. + +Und normalerweise ist es ein komplexes und „schwieriges“ Thema. + +In vielen Frameworks und Systemen erfordert allein die Handhabung von Sicherheit und Authentifizierung viel Aufwand und Code (in vielen Fällen kann er 50 % oder mehr des gesamten geschriebenen Codes ausmachen). + +**FastAPI** bietet mehrere Tools, die Ihnen helfen, schnell und auf standardisierte Weise mit **Sicherheit** umzugehen, ohne alle Sicherheits-Spezifikationen studieren und erlernen zu müssen. + +Aber schauen wir uns zunächst ein paar kleine Konzepte an. + +## In Eile? + +Wenn Ihnen diese Begriffe egal sind und Sie einfach *jetzt* Sicherheit mit Authentifizierung basierend auf Benutzername und Passwort hinzufügen müssen, fahren Sie mit den nächsten Kapiteln fort. + +## OAuth2 + +OAuth2 ist eine Spezifikation, die verschiedene Möglichkeiten zur Handhabung von Authentifizierung und Autorisierung definiert. + +Es handelt sich um eine recht umfangreiche Spezifikation, und sie deckt mehrere komplexe Anwendungsfälle ab. + +Sie umfasst Möglichkeiten zur Authentifizierung mithilfe eines „Dritten“ („third party“). + +Das ist es, was alle diese „Login mit Facebook, Google, Twitter, GitHub“-Systeme unter der Haube verwenden. + +### OAuth 1 + +Es gab ein OAuth 1, das sich stark von OAuth2 unterscheidet und komplexer ist, da es direkte Spezifikationen enthält, wie die Kommunikation verschlüsselt wird. + +Heutzutage ist es nicht sehr populär und wird kaum verwendet. + +OAuth2 spezifiziert nicht, wie die Kommunikation verschlüsselt werden soll, sondern erwartet, dass Ihre Anwendung mit HTTPS bereitgestellt wird. + +!!! tip "Tipp" + Im Abschnitt über **Deployment** erfahren Sie, wie Sie HTTPS mithilfe von Traefik und Let's Encrypt kostenlos einrichten. + + +## OpenID Connect + +OpenID Connect ist eine weitere Spezifikation, die auf **OAuth2** basiert. + +Sie erweitert lediglich OAuth2, indem sie einige Dinge spezifiziert, die in OAuth2 relativ mehrdeutig sind, um zu versuchen, es interoperabler zu machen. + +Beispielsweise verwendet der Google Login OpenID Connect (welches seinerseits OAuth2 verwendet). + +Aber der Facebook Login unterstützt OpenID Connect nicht. Es hat seine eigene Variante von OAuth2. + +### OpenID (nicht „OpenID Connect“) + +Es gab auch eine „OpenID“-Spezifikation. Sie versuchte das Gleiche zu lösen wie **OpenID Connect**, basierte aber nicht auf OAuth2. + +Es handelte sich also um ein komplett zusätzliches System. + +Heutzutage ist es nicht sehr populär und wird kaum verwendet. + +## OpenAPI + +OpenAPI (früher bekannt als Swagger) ist die offene Spezifikation zum Erstellen von APIs (jetzt Teil der Linux Foundation). + +**FastAPI** basiert auf **OpenAPI**. + +Das ist es, was erlaubt, mehrere automatische interaktive Dokumentations-Oberflächen, Codegenerierung, usw. zu haben. + +OpenAPI bietet die Möglichkeit, mehrere Sicherheits„systeme“ zu definieren. + +Durch deren Verwendung können Sie alle diese Standards-basierten Tools nutzen, einschließlich dieser interaktiven Dokumentationssysteme. + +OpenAPI definiert die folgenden Sicherheitsschemas: + +* `apiKey`: ein anwendungsspezifischer Schlüssel, der stammen kann von: + * Einem Query-Parameter. + * Einem Header. + * Einem Cookie. +* `http`: Standard-HTTP-Authentifizierungssysteme, einschließlich: + * `bearer`: ein Header `Authorization` mit dem Wert `Bearer` plus einem Token. Dies wird von OAuth2 geerbt. + * HTTP Basic Authentication. + * HTTP Digest, usw. +* `oauth2`: Alle OAuth2-Methoden zum Umgang mit Sicherheit (genannt „Flows“). + * Mehrere dieser Flows eignen sich zum Aufbau eines OAuth 2.0-Authentifizierungsanbieters (wie Google, Facebook, Twitter, GitHub usw.): + * `implicit` + * `clientCredentials` + * `authorizationCode` + * Es gibt jedoch einen bestimmten „Flow“, der perfekt für die direkte Abwicklung der Authentifizierung in derselben Anwendung verwendet werden kann: + * `password`: Einige der nächsten Kapitel werden Beispiele dafür behandeln. +* `openIdConnect`: bietet eine Möglichkeit, zu definieren, wie OAuth2-Authentifizierungsdaten automatisch ermittelt werden können. + * Diese automatische Erkennung ist es, die in der OpenID Connect Spezifikation definiert ist. + + +!!! tip "Tipp" + Auch die Integration anderer Authentifizierungs-/Autorisierungsanbieter wie Google, Facebook, Twitter, GitHub, usw. ist möglich und relativ einfach. + + Das komplexeste Problem besteht darin, einen Authentifizierungs-/Autorisierungsanbieter wie solche aufzubauen, aber **FastAPI** reicht Ihnen die Tools, das einfach zu erledigen, während Ihnen die schwere Arbeit abgenommen wird. + +## **FastAPI** Tools + +FastAPI stellt für jedes dieser Sicherheitsschemas im Modul `fastapi.security` verschiedene Tools bereit, die die Verwendung dieser Sicherheitsmechanismen vereinfachen. + +In den nächsten Kapiteln erfahren Sie, wie Sie mit diesen von **FastAPI** bereitgestellten Tools Sicherheit zu Ihrer API hinzufügen. + +Und Sie werden auch sehen, wie dies automatisch in das interaktive Dokumentationssystem integriert wird. diff --git a/docs/de/docs/tutorial/security/oauth2-jwt.md b/docs/de/docs/tutorial/security/oauth2-jwt.md new file mode 100644 index 0000000000000..9f43cccc9a0e1 --- /dev/null +++ b/docs/de/docs/tutorial/security/oauth2-jwt.md @@ -0,0 +1,393 @@ +# OAuth2 mit Password (und Hashing), Bearer mit JWT-Tokens + +Da wir nun über den gesamten Sicherheitsablauf verfügen, machen wir die Anwendung tatsächlich sicher, indem wir JWT-Tokens und sicheres Passwort-Hashing verwenden. + +Diesen Code können Sie tatsächlich in Ihrer Anwendung verwenden, die Passwort-Hashes in Ihrer Datenbank speichern, usw. + +Wir bauen auf dem vorherigen Kapitel auf. + +## Über JWT + +JWT bedeutet „JSON Web Tokens“. + +Es ist ein Standard, um ein JSON-Objekt in einem langen, kompakten String ohne Leerzeichen zu kodieren. Das sieht so aus: + +``` +eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c +``` + +Da er nicht verschlüsselt ist, kann jeder die Informationen aus dem Inhalt wiederherstellen. + +Aber er ist signiert. Wenn Sie also einen von Ihnen gesendeten Token zurückerhalten, können Sie überprüfen, ob Sie ihn tatsächlich gesendet haben. + +Auf diese Weise können Sie einen Token mit einer Gültigkeitsdauer von beispielsweise einer Woche erstellen. Und wenn der Benutzer am nächsten Tag mit dem Token zurückkommt, wissen Sie, dass der Benutzer immer noch bei Ihrem System angemeldet ist. + +Nach einer Woche läuft der Token ab und der Benutzer wird nicht autorisiert und muss sich erneut anmelden, um einen neuen Token zu erhalten. Und wenn der Benutzer (oder ein Dritter) versuchen würde, den Token zu ändern, um das Ablaufdatum zu ändern, würden Sie das entdecken, weil die Signaturen nicht übereinstimmen würden. + +Wenn Sie mit JWT-Tokens spielen und sehen möchten, wie sie funktionieren, schauen Sie sich https://jwt.io an. + +## `python-jose` installieren. + +Wir müssen `python-jose` installieren, um die JWT-Tokens in Python zu generieren und zu verifizieren: + +
+ +```console +$ pip install "python-jose[cryptography]" + +---> 100% +``` + +
+ +python-jose erfordert zusätzlich ein kryptografisches Backend. + +Hier verwenden wir das empfohlene: pyca/cryptography. + +!!! tip "Tipp" + Dieses Tutorial verwendete zuvor PyJWT. + + Es wurde jedoch aktualisiert, stattdessen python-jose zu verwenden, da dieses alle Funktionen von PyJWT sowie einige Extras bietet, die Sie später möglicherweise benötigen, wenn Sie Integrationen mit anderen Tools erstellen. + +## Passwort-Hashing + +„Hashing“ bedeutet: Konvertieren eines Inhalts (in diesem Fall eines Passworts) in eine Folge von Bytes (ein schlichter String), die wie Kauderwelsch aussieht. + +Immer wenn Sie genau den gleichen Inhalt (genau das gleiche Passwort) übergeben, erhalten Sie genau den gleichen Kauderwelsch. + +Sie können jedoch nicht vom Kauderwelsch zurück zum Passwort konvertieren. + +### Warum Passwort-Hashing verwenden? + +Wenn Ihre Datenbank gestohlen wird, hat der Dieb nicht die Klartext-Passwörter Ihrer Benutzer, sondern nur die Hashes. + +Der Dieb kann also nicht versuchen, die gleichen Passwörter in einem anderen System zu verwenden (da viele Benutzer überall das gleiche Passwort verwenden, wäre dies gefährlich). + +## `passlib` installieren + +PassLib ist ein großartiges Python-Package, um Passwort-Hashes zu handhaben. + +Es unterstützt viele sichere Hashing-Algorithmen und Werkzeuge, um mit diesen zu arbeiten. + +Der empfohlene Algorithmus ist „Bcrypt“. + +Installieren Sie also PassLib mit Bcrypt: + +
+ +```console +$ pip install "passlib[bcrypt]" + +---> 100% +``` + +
+ +!!! tip "Tipp" + Mit `passlib` können Sie sogar konfigurieren, Passwörter zu lesen, die von **Django**, einem **Flask**-Sicherheit-Plugin, oder vielen anderen erstellt wurden. + + So könnten Sie beispielsweise die gleichen Daten aus einer Django-Anwendung in einer Datenbank mit einer FastAPI-Anwendung teilen. Oder schrittweise eine Django-Anwendung migrieren, während Sie dieselbe Datenbank verwenden. + + Und Ihre Benutzer könnten sich gleichzeitig über Ihre Django-Anwendung oder Ihre **FastAPI**-Anwendung anmelden. + +## Die Passwörter hashen und überprüfen + +Importieren Sie die benötigten Tools aus `passlib`. + +Erstellen Sie einen PassLib-„Kontext“. Der wird für das Hashen und Verifizieren von Passwörtern verwendet. + +!!! tip "Tipp" + Der PassLib-Kontext kann auch andere Hashing-Algorithmen verwenden, einschließlich deprecateter Alter, um etwa nur eine Verifizierung usw. zu ermöglichen. + + Sie könnten ihn beispielsweise verwenden, um von einem anderen System (wie Django) generierte Passwörter zu lesen und zu verifizieren, aber alle neuen Passwörter mit einem anderen Algorithmus wie Bcrypt zu hashen. + + Und mit allen gleichzeitig kompatibel sein. + +Erstellen Sie eine Hilfsfunktion, um ein vom Benutzer stammendes Passwort zu hashen. + +Und eine weitere, um zu überprüfen, ob ein empfangenes Passwort mit dem gespeicherten Hash übereinstimmt. + +Und noch eine, um einen Benutzer zu authentifizieren und zurückzugeben. + +=== "Python 3.10+" + + ```Python hl_lines="7 48 55-56 59-60 69-75" + {!> ../../../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.8+" + + ```Python hl_lines="7 49 56-57 60-61 70-76" + {!> ../../../docs_src/security/tutorial004_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="6 47 54-55 58-59 68-74" + {!> ../../../docs_src/security/tutorial004_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="7 48 55-56 59-60 69-75" + {!> ../../../docs_src/security/tutorial004.py!} + ``` + +!!! note "Hinweis" + Wenn Sie sich die neue (gefakte) Datenbank `fake_users_db` anschauen, sehen Sie, wie das gehashte Passwort jetzt aussieht: `"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`. + +## JWT-Token verarbeiten + +Importieren Sie die installierten Module. + +Erstellen Sie einen zufälligen geheimen Schlüssel, der zum Signieren der JWT-Tokens verwendet wird. + +Um einen sicheren zufälligen geheimen Schlüssel zu generieren, verwenden Sie den folgenden Befehl: + +
+ +```console +$ openssl rand -hex 32 + +09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7 +``` + +
+ +Und kopieren Sie die Ausgabe in die Variable `SECRET_KEY` (verwenden Sie nicht die im Beispiel). + +Erstellen Sie eine Variable `ALGORITHM` für den Algorithmus, der zum Signieren des JWT-Tokens verwendet wird, und setzen Sie sie auf `"HS256"`. + +Erstellen Sie eine Variable für das Ablaufdatum des Tokens. + +Definieren Sie ein Pydantic-Modell, das im Token-Endpunkt für die Response verwendet wird. + +Erstellen Sie eine Hilfsfunktion, um einen neuen Zugriffstoken zu generieren. + +=== "Python 3.10+" + + ```Python hl_lines="6 12-14 28-30 78-86" + {!> ../../../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.8+" + + ```Python hl_lines="6 13-15 29-31 79-87" + {!> ../../../docs_src/security/tutorial004_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="5 11-13 27-29 77-85" + {!> ../../../docs_src/security/tutorial004_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="6 12-14 28-30 78-86" + {!> ../../../docs_src/security/tutorial004.py!} + ``` + +## Die Abhängigkeiten aktualisieren + +Aktualisieren Sie `get_current_user`, um den gleichen Token wie zuvor zu erhalten, dieses Mal jedoch unter Verwendung von JWT-Tokens. + +Dekodieren Sie den empfangenen Token, validieren Sie ihn und geben Sie den aktuellen Benutzer zurück. + +Wenn der Token ungültig ist, geben Sie sofort einen HTTP-Fehler zurück. + +=== "Python 3.10+" + + ```Python hl_lines="89-106" + {!> ../../../docs_src/security/tutorial004_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="89-106" + {!> ../../../docs_src/security/tutorial004_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="90-107" + {!> ../../../docs_src/security/tutorial004_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="88-105" + {!> ../../../docs_src/security/tutorial004_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="89-106" + {!> ../../../docs_src/security/tutorial004.py!} + ``` + +## Die *Pfadoperation* `/token` aktualisieren + +Erstellen Sie ein `timedelta` mit der Ablaufzeit des Tokens. + +Erstellen Sie einen echten JWT-Zugriffstoken und geben Sie ihn zurück. + +=== "Python 3.10+" + + ```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.8+" + + ```Python hl_lines="118-133" + {!> ../../../docs_src/security/tutorial004_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="114-129" + {!> ../../../docs_src/security/tutorial004_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="115-130" + {!> ../../../docs_src/security/tutorial004.py!} + ``` + +### Technische Details zum JWT-„Subjekt“ `sub` + +Die JWT-Spezifikation besagt, dass es einen Schlüssel `sub` mit dem Subjekt des Tokens gibt. + +Die Verwendung ist optional, aber dort würden Sie die Identifikation des Benutzers speichern, daher verwenden wir das hier. + +JWT kann auch für andere Dinge verwendet werden, abgesehen davon, einen Benutzer zu identifizieren und ihm zu erlauben, Operationen direkt auf Ihrer API auszuführen. + +Sie könnten beispielsweise ein „Auto“ oder einen „Blog-Beitrag“ identifizieren. + +Anschließend könnten Sie Berechtigungen für diese Entität hinzufügen, etwa „Fahren“ (für das Auto) oder „Bearbeiten“ (für den Blog). + +Und dann könnten Sie diesen JWT-Token einem Benutzer (oder Bot) geben und dieser könnte ihn verwenden, um diese Aktionen auszuführen (das Auto fahren oder den Blog-Beitrag bearbeiten), ohne dass er überhaupt ein Konto haben müsste, einfach mit dem JWT-Token, den Ihre API dafür generiert hat. + +Mit diesen Ideen kann JWT für weitaus anspruchsvollere Szenarien verwendet werden. + +In diesen Fällen könnten mehrere dieser Entitäten die gleiche ID haben, sagen wir `foo` (ein Benutzer `foo`, ein Auto `foo` und ein Blog-Beitrag `foo`). + +Deshalb, um ID-Kollisionen zu vermeiden, könnten Sie beim Erstellen des JWT-Tokens für den Benutzer, dem Wert des `sub`-Schlüssels ein Präfix, z. B. `username:` voranstellen. In diesem Beispiel hätte der Wert von `sub` also auch `username:johndoe` sein können. + +Der wesentliche Punkt ist, dass der `sub`-Schlüssel in der gesamten Anwendung eine eindeutige Kennung haben sollte, und er sollte ein String sein. + +## Es testen + +Führen Sie den Server aus und gehen Sie zur Dokumentation: http://127.0.0.1:8000/docs. + +Die Benutzeroberfläche sieht wie folgt aus: + + + +Melden Sie sich bei der Anwendung auf die gleiche Weise wie zuvor an. + +Verwenden Sie die Anmeldeinformationen: + +Benutzername: `johndoe` +Passwort: `secret`. + +!!! check + Beachten Sie, dass im Code nirgendwo das Klartext-Passwort "`secret`" steht, wir haben nur die gehashte Version. + + + +Rufen Sie den Endpunkt `/users/me/` auf, Sie erhalten die Response: + +```JSON +{ + "username": "johndoe", + "email": "johndoe@example.com", + "full_name": "John Doe", + "disabled": false +} +``` + + + +Wenn Sie die Developer Tools öffnen, können Sie sehen, dass die gesendeten Daten nur den Token enthalten. Das Passwort wird nur bei der ersten Anfrage gesendet, um den Benutzer zu authentisieren und diesen Zugriffstoken zu erhalten, aber nicht mehr danach: + + + +!!! note "Hinweis" + Beachten Sie den Header `Authorization` mit einem Wert, der mit `Bearer` beginnt. + +## Fortgeschrittene Verwendung mit `scopes` + +OAuth2 hat ein Konzept von „Scopes“. + +Sie können diese verwenden, um einem JWT-Token einen bestimmten Satz von Berechtigungen zu übergeben. + +Anschließend können Sie diesen Token einem Benutzer direkt oder einem Dritten geben, damit diese mit einer Reihe von Einschränkungen mit Ihrer API interagieren können. + +Wie Sie sie verwenden und wie sie in **FastAPI** integriert sind, erfahren Sie später im **Handbuch für fortgeschrittene Benutzer**. + +## Zusammenfassung + +Mit dem, was Sie bis hier gesehen haben, können Sie eine sichere **FastAPI**-Anwendung mithilfe von Standards wie OAuth2 und JWT einrichten. + +In fast jedem Framework wird die Handhabung der Sicherheit recht schnell zu einem ziemlich komplexen Thema. + +Viele Packages, die es stark vereinfachen, müssen viele Kompromisse beim Datenmodell, der Datenbank und den verfügbaren Funktionen eingehen. Und einige dieser Pakete, die die Dinge zu sehr vereinfachen, weisen tatsächlich Sicherheitslücken auf. + +--- + +**FastAPI** geht bei keiner Datenbank, keinem Datenmodell oder Tool Kompromisse ein. + +Es gibt Ihnen die volle Flexibilität, diejenigen auszuwählen, die am besten zu Ihrem Projekt passen. + +Und Sie können viele gut gepflegte und weit verbreitete Packages wie `passlib` und `python-jose` direkt verwenden, da **FastAPI** keine komplexen Mechanismen zur Integration externer Pakete erfordert. + +Aber es bietet Ihnen die Werkzeuge, um den Prozess so weit wie möglich zu vereinfachen, ohne Kompromisse bei Flexibilität, Robustheit oder Sicherheit einzugehen. + +Und Sie können sichere Standardprotokolle wie OAuth2 auf relativ einfache Weise verwenden und implementieren. + +Im **Handbuch für fortgeschrittene Benutzer** erfahren Sie mehr darüber, wie Sie OAuth2-„Scopes“ für ein feingranuliertes Berechtigungssystem verwenden, das denselben Standards folgt. OAuth2 mit Scopes ist der Mechanismus, der von vielen großen Authentifizierungsanbietern wie Facebook, Google, GitHub, Microsoft, Twitter, usw. verwendet wird, um Drittanbieteranwendungen zu autorisieren, im Namen ihrer Benutzer mit ihren APIs zu interagieren. diff --git a/docs/de/docs/tutorial/security/simple-oauth2.md b/docs/de/docs/tutorial/security/simple-oauth2.md new file mode 100644 index 0000000000000..ed280d48669f3 --- /dev/null +++ b/docs/de/docs/tutorial/security/simple-oauth2.md @@ -0,0 +1,435 @@ +# Einfaches OAuth2 mit Password und Bearer + +Lassen Sie uns nun auf dem vorherigen Kapitel aufbauen und die fehlenden Teile hinzufügen, um einen vollständigen Sicherheits-Flow zu erhalten. + +## `username` und `password` entgegennehmen + +Wir werden **FastAPIs** Sicherheits-Werkzeuge verwenden, um den `username` und das `password` entgegenzunehmen. + +OAuth2 spezifiziert, dass der Client/Benutzer bei Verwendung des „Password Flow“ (den wir verwenden) die Felder `username` und `password` als Formulardaten senden muss. + +Und die Spezifikation sagt, dass die Felder so benannt werden müssen. `user-name` oder `email` würde also nicht funktionieren. + +Aber keine Sorge, Sie können sie Ihren Endbenutzern im Frontend so anzeigen, wie Sie möchten. + +Und Ihre Datenbankmodelle können beliebige andere Namen verwenden. + +Aber für die Login-*Pfadoperation* müssen wir diese Namen verwenden, um mit der Spezifikation kompatibel zu sein (und beispielsweise das integrierte API-Dokumentationssystem verwenden zu können). + +Die Spezifikation besagt auch, dass `username` und `password` als Formulardaten gesendet werden müssen (hier also kein JSON). + +### `scope` + +Ferner sagt die Spezifikation, dass der Client ein weiteres Formularfeld "`scope`" („Geltungsbereich“) senden kann. + +Der Name des Formularfelds lautet `scope` (im Singular), tatsächlich handelt es sich jedoch um einen langen String mit durch Leerzeichen getrennten „Scopes“. + +Jeder „Scope“ ist nur ein String (ohne Leerzeichen). + +Diese werden normalerweise verwendet, um bestimmte Sicherheitsberechtigungen zu deklarieren, zum Beispiel: + +* `users:read` oder `users:write` sind gängige Beispiele. +* `instagram_basic` wird von Facebook / Instagram verwendet. +* `https://www.googleapis.com/auth/drive` wird von Google verwendet. + +!!! info + In OAuth2 ist ein „Scope“ nur ein String, der eine bestimmte erforderliche Berechtigung deklariert. + + Es spielt keine Rolle, ob er andere Zeichen wie `:` enthält oder ob es eine URL ist. + + Diese Details sind implementierungsspezifisch. + + Für OAuth2 sind es einfach nur Strings. + +## Code, um `username` und `password` entgegenzunehmen. + +Lassen Sie uns nun die von **FastAPI** bereitgestellten Werkzeuge verwenden, um das zu erledigen. + +### `OAuth2PasswordRequestForm` + +Importieren Sie zunächst `OAuth2PasswordRequestForm` und verwenden Sie es als Abhängigkeit mit `Depends` in der *Pfadoperation* für `/token`: + +=== "Python 3.10+" + + ```Python hl_lines="4 78" + {!> ../../../docs_src/security/tutorial003_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="4 78" + {!> ../../../docs_src/security/tutorial003_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="4 79" + {!> ../../../docs_src/security/tutorial003_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="2 74" + {!> ../../../docs_src/security/tutorial003_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="4 76" + {!> ../../../docs_src/security/tutorial003.py!} + ``` + +`OAuth2PasswordRequestForm` ist eine Klassenabhängigkeit, die einen Formularbody deklariert mit: + +* Dem `username`. +* Dem `password`. +* Einem optionalen `scope`-Feld als langem String, bestehend aus durch Leerzeichen getrennten Strings. +* Einem optionalen `grant_type` („Art der Anmeldung“). + +!!! tip "Tipp" + Die OAuth2-Spezifikation *erfordert* tatsächlich ein Feld `grant_type` mit dem festen Wert `password`, aber `OAuth2PasswordRequestForm` erzwingt dies nicht. + + Wenn Sie es erzwingen müssen, verwenden Sie `OAuth2PasswordRequestFormStrict` anstelle von `OAuth2PasswordRequestForm`. + +* Eine optionale `client_id` (benötigen wir für unser Beispiel nicht). +* Ein optionales `client_secret` (benötigen wir für unser Beispiel nicht). + +!!! info + `OAuth2PasswordRequestForm` ist keine spezielle Klasse für **FastAPI**, so wie `OAuth2PasswordBearer`. + + `OAuth2PasswordBearer` lässt **FastAPI** wissen, dass es sich um ein Sicherheitsschema handelt. Daher wird es auf diese Weise zu OpenAPI hinzugefügt. + + Aber `OAuth2PasswordRequestForm` ist nur eine Klassenabhängigkeit, die Sie selbst hätten schreiben können, oder Sie hätten `Form`ular-Parameter direkt deklarieren können. + + Da es sich jedoch um einen häufigen Anwendungsfall handelt, wird er zur Vereinfachung direkt von **FastAPI** bereitgestellt. + +### Die Formulardaten verwenden + +!!! tip "Tipp" + Die Instanz der Klassenabhängigkeit `OAuth2PasswordRequestForm` verfügt, statt eines Attributs `scope` mit dem durch Leerzeichen getrennten langen String, über das Attribut `scopes` mit einer tatsächlichen Liste von Strings, einem für jeden gesendeten Scope. + + In diesem Beispiel verwenden wir keine `scopes`, aber die Funktionalität ist vorhanden, wenn Sie sie benötigen. + +Rufen Sie nun die Benutzerdaten aus der (gefakten) Datenbank ab, für diesen `username` aus dem Formularfeld. + +Wenn es keinen solchen Benutzer gibt, geben wir die Fehlermeldung „Incorrect username or password“ zurück. + +Für den Fehler verwenden wir die Exception `HTTPException`: + +=== "Python 3.10+" + + ```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.8+" + + ```Python hl_lines="3 80-82" + {!> ../../../docs_src/security/tutorial003_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="1 75-77" + {!> ../../../docs_src/security/tutorial003_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="3 77-79" + {!> ../../../docs_src/security/tutorial003.py!} + ``` + +### Das Passwort überprüfen + +Zu diesem Zeitpunkt liegen uns die Benutzerdaten aus unserer Datenbank vor, das Passwort haben wir jedoch noch nicht überprüft. + +Lassen Sie uns diese Daten zunächst in das Pydantic-Modell `UserInDB` einfügen. + +Sie sollten niemals Klartext-Passwörter speichern, daher verwenden wir ein (gefaktes) Passwort-Hashing-System. + +Wenn die Passwörter nicht übereinstimmen, geben wir denselben Fehler zurück. + +#### Passwort-Hashing + +„Hashing“ bedeutet: Konvertieren eines Inhalts (in diesem Fall eines Passworts) in eine Folge von Bytes (ein schlichter String), die wie Kauderwelsch aussieht. + +Immer wenn Sie genau den gleichen Inhalt (genau das gleiche Passwort) übergeben, erhalten Sie genau den gleichen Kauderwelsch. + +Sie können jedoch nicht vom Kauderwelsch zurück zum Passwort konvertieren. + +##### Warum Passwort-Hashing verwenden? + +Wenn Ihre Datenbank gestohlen wird, hat der Dieb nicht die Klartext-Passwörter Ihrer Benutzer, sondern nur die Hashes. + +Der Dieb kann also nicht versuchen, die gleichen Passwörter in einem anderen System zu verwenden (da viele Benutzer überall das gleiche Passwort verwenden, wäre dies gefährlich). + +=== "Python 3.10+" + + ```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.8+" + + ```Python hl_lines="83-86" + {!> ../../../docs_src/security/tutorial003_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="78-81" + {!> ../../../docs_src/security/tutorial003_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="80-83" + {!> ../../../docs_src/security/tutorial003.py!} + ``` + +#### Über `**user_dict` + +`UserInDB(**user_dict)` bedeutet: + +*Übergib die Schlüssel und Werte des `user_dict` direkt als Schlüssel-Wert-Argumente, äquivalent zu:* + +```Python +UserInDB( + username = user_dict["username"], + email = user_dict["email"], + full_name = user_dict["full_name"], + disabled = user_dict["disabled"], + hashed_password = user_dict["hashed_password"], +) +``` + +!!! info + Eine ausführlichere Erklärung von `**user_dict` finden Sie in [der Dokumentation für **Extra Modelle**](../extra-models.md#uber-user_indict){.internal-link target=_blank}. + +## Den Token zurückgeben + +Die Response des `token`-Endpunkts muss ein JSON-Objekt sein. + +Es sollte einen `token_type` haben. Da wir in unserem Fall „Bearer“-Token verwenden, sollte der Token-Typ "`bearer`" sein. + +Und es sollte einen `access_token` haben, mit einem String, der unseren Zugriffstoken enthält. + +In diesem einfachen Beispiel gehen wir einfach völlig unsicher vor und geben denselben `username` wie der Token zurück. + +!!! tip "Tipp" + Im nächsten Kapitel sehen Sie eine wirklich sichere Implementierung mit Passwort-Hashing und JWT-Tokens. + + Aber konzentrieren wir uns zunächst auf die spezifischen Details, die wir benötigen. + +=== "Python 3.10+" + + ```Python hl_lines="87" + {!> ../../../docs_src/security/tutorial003_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="87" + {!> ../../../docs_src/security/tutorial003_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="88" + {!> ../../../docs_src/security/tutorial003_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="83" + {!> ../../../docs_src/security/tutorial003_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="85" + {!> ../../../docs_src/security/tutorial003.py!} + ``` + +!!! tip "Tipp" + Gemäß der Spezifikation sollten Sie ein JSON mit einem `access_token` und einem `token_type` zurückgeben, genau wie in diesem Beispiel. + + Das müssen Sie selbst in Ihrem Code tun und sicherstellen, dass Sie diese JSON-Schlüssel verwenden. + + Es ist fast das Einzige, woran Sie denken müssen, es selbst richtigzumachen und die Spezifikationen einzuhalten. + + Den Rest erledigt **FastAPI** für Sie. + +## Die Abhängigkeiten aktualisieren + +Jetzt werden wir unsere Abhängigkeiten aktualisieren. + +Wir möchten den `current_user` *nur* erhalten, wenn dieser Benutzer aktiv ist. + +Daher erstellen wir eine zusätzliche Abhängigkeit `get_current_active_user`, die wiederum `get_current_user` als Abhängigkeit verwendet. + +Beide Abhängigkeiten geben nur dann einen HTTP-Error zurück, wenn der Benutzer nicht existiert oder inaktiv ist. + +In unserem Endpunkt erhalten wir also nur dann einen Benutzer, wenn der Benutzer existiert, korrekt authentifiziert wurde und aktiv ist: + +=== "Python 3.10+" + + ```Python hl_lines="58-66 69-74 94" + {!> ../../../docs_src/security/tutorial003_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="58-66 69-74 94" + {!> ../../../docs_src/security/tutorial003_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="59-67 70-75 95" + {!> ../../../docs_src/security/tutorial003_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="56-64 67-70 88" + {!> ../../../docs_src/security/tutorial003_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="58-66 69-72 90" + {!> ../../../docs_src/security/tutorial003.py!} + ``` + +!!! info + Der zusätzliche Header `WWW-Authenticate` mit dem Wert `Bearer`, den wir hier zurückgeben, ist ebenfalls Teil der Spezifikation. + + Jeder HTTP-(Fehler-)Statuscode 401 „UNAUTHORIZED“ soll auch einen `WWW-Authenticate`-Header zurückgeben. + + Im Fall von Bearer-Tokens (in unserem Fall) sollte der Wert dieses Headers `Bearer` lauten. + + Sie können diesen zusätzlichen Header tatsächlich weglassen und es würde trotzdem funktionieren. + + Aber er wird hier bereitgestellt, um den Spezifikationen zu entsprechen. + + Außerdem gibt es möglicherweise Tools, die ihn erwarten und verwenden (jetzt oder in der Zukunft) und das könnte für Sie oder Ihre Benutzer jetzt oder in der Zukunft nützlich sein. + + Das ist der Vorteil von Standards ... + +## Es in Aktion sehen + +Öffnen Sie die interaktive Dokumentation: http://127.0.0.1:8000/docs. + +### Authentifizieren + +Klicken Sie auf den Button „Authorize“. + +Verwenden Sie die Anmeldedaten: + +Benutzer: `johndoe` + +Passwort: `secret`. + + + +Nach der Authentifizierung im System sehen Sie Folgendes: + + + +### Die eigenen Benutzerdaten ansehen + +Verwenden Sie nun die Operation `GET` mit dem Pfad `/users/me`. + +Sie erhalten Ihre Benutzerdaten: + +```JSON +{ + "username": "johndoe", + "email": "johndoe@example.com", + "full_name": "John Doe", + "disabled": false, + "hashed_password": "fakehashedsecret" +} +``` + + + +Wenn Sie auf das Schlosssymbol klicken und sich abmelden und dann den gleichen Vorgang nochmal versuchen, erhalten Sie einen HTTP 401 Error: + +```JSON +{ + "detail": "Not authenticated" +} +``` + +### Inaktiver Benutzer + +Versuchen Sie es nun mit einem inaktiven Benutzer und authentisieren Sie sich mit: + +Benutzer: `alice`. + +Passwort: `secret2`. + +Und versuchen Sie, die Operation `GET` mit dem Pfad `/users/me` zu verwenden. + +Sie erhalten die Fehlermeldung „Inactive user“: + +```JSON +{ + "detail": "Inactive user" +} +``` + +## Zusammenfassung + +Sie verfügen jetzt über die Tools, um ein vollständiges Sicherheitssystem basierend auf `username` und `password` für Ihre API zu implementieren. + +Mit diesen Tools können Sie das Sicherheitssystem mit jeder Datenbank und jedem Benutzer oder Datenmodell kompatibel machen. + +Das einzige fehlende Detail ist, dass es noch nicht wirklich „sicher“ ist. + +Im nächsten Kapitel erfahren Sie, wie Sie eine sichere Passwort-Hashing-Bibliothek und JWT-Token verwenden. diff --git a/docs/de/docs/tutorial/static-files.md b/docs/de/docs/tutorial/static-files.md new file mode 100644 index 0000000000000..1e289e120ed59 --- /dev/null +++ b/docs/de/docs/tutorial/static-files.md @@ -0,0 +1,39 @@ +# Statische Dateien + +Mit `StaticFiles` können Sie statische Dateien aus einem Verzeichnis automatisch bereitstellen. + +## `StaticFiles` verwenden + +* Importieren Sie `StaticFiles`. +* „Mounten“ Sie eine `StaticFiles()`-Instanz in einem bestimmten Pfad. + +```Python hl_lines="2 6" +{!../../../docs_src/static_files/tutorial001.py!} +``` + +!!! note "Technische Details" + Sie könnten auch `from starlette.staticfiles import StaticFiles` verwenden. + + **FastAPI** stellt dasselbe `starlette.staticfiles` auch via `fastapi.staticfiles` bereit, als Annehmlichkeit für Sie, den Entwickler. Es kommt aber tatsächlich direkt von Starlette. + +### Was ist „Mounten“? + +„Mounten“ bedeutet das Hinzufügen einer vollständigen „unabhängigen“ Anwendung an einem bestimmten Pfad, die sich dann um die Handhabung aller Unterpfade kümmert. + +Dies unterscheidet sich von der Verwendung eines `APIRouter`, da eine gemountete Anwendung völlig unabhängig ist. Die OpenAPI und Dokumentation Ihrer Hauptanwendung enthalten nichts von der gemounteten Anwendung, usw. + +Weitere Informationen hierzu finden Sie im [Handbuch für fortgeschrittene Benutzer](../advanced/index.md){.internal-link target=_blank}. + +## Einzelheiten + +Das erste `"/static"` bezieht sich auf den Unterpfad, auf dem diese „Unteranwendung“ „gemountet“ wird. Daher wird jeder Pfad, der mit `"/static"` beginnt, von ihr verarbeitet. + +Das `directory="static"` bezieht sich auf den Namen des Verzeichnisses, das Ihre statischen Dateien enthält. + +Das `name="static"` gibt dieser Unteranwendung einen Namen, der intern von **FastAPI** verwendet werden kann. + +Alle diese Parameter können anders als "`static`" lauten, passen Sie sie an die Bedürfnisse und spezifischen Details Ihrer eigenen Anwendung an. + +## Weitere Informationen + +Weitere Details und Optionen finden Sie in der Dokumentation von Starlette zu statischen Dateien. diff --git a/docs/de/docs/tutorial/testing.md b/docs/de/docs/tutorial/testing.md new file mode 100644 index 0000000000000..541cc1bf0482e --- /dev/null +++ b/docs/de/docs/tutorial/testing.md @@ -0,0 +1,212 @@ +# Testen + +Dank Starlette ist das Testen von **FastAPI**-Anwendungen einfach und macht Spaß. + +Es basiert auf HTTPX, welches wiederum auf der Grundlage von requests konzipiert wurde, es ist also sehr vertraut und intuitiv. + +Damit können Sie pytest direkt mit **FastAPI** verwenden. + +## Verwendung von `TestClient` + +!!! info + Um `TestClient` zu verwenden, installieren Sie zunächst `httpx`. + + Z. B. `pip install httpx`. + +Importieren Sie `TestClient`. + +Erstellen Sie einen `TestClient`, indem Sie ihm Ihre **FastAPI**-Anwendung übergeben. + +Erstellen Sie Funktionen mit einem Namen, der mit `test_` beginnt (das sind `pytest`-Konventionen). + +Verwenden Sie das `TestClient`-Objekt auf die gleiche Weise wie `httpx`. + +Schreiben Sie einfache `assert`-Anweisungen mit den Standard-Python-Ausdrücken, die Sie überprüfen müssen (wiederum, Standard-`pytest`). + +```Python hl_lines="2 12 15-18" +{!../../../docs_src/app_testing/tutorial001.py!} +``` + +!!! tip "Tipp" + Beachten Sie, dass die Testfunktionen normal `def` und nicht `async def` sind. + + Und die Anrufe an den Client sind ebenfalls normale Anrufe, die nicht `await` verwenden. + + Dadurch können Sie `pytest` ohne Komplikationen direkt nutzen. + +!!! note "Technische Details" + Sie könnten auch `from starlette.testclient import TestClient` verwenden. + + **FastAPI** stellt denselben `starlette.testclient` auch via `fastapi.testclient` bereit, als Annehmlichkeit für Sie, den Entwickler. Es kommt aber tatsächlich direkt von Starlette. + +!!! tip "Tipp" + Wenn Sie in Ihren Tests neben dem Senden von Anfragen an Ihre FastAPI-Anwendung auch `async`-Funktionen aufrufen möchten (z. B. asynchrone Datenbankfunktionen), werfen Sie einen Blick auf die [Async-Tests](../advanced/async-tests.md){.internal-link target=_blank} im Handbuch für fortgeschrittene Benutzer. + +## Tests separieren + +In einer echten Anwendung würden Sie Ihre Tests wahrscheinlich in einer anderen Datei haben. + +Und Ihre **FastAPI**-Anwendung könnte auch aus mehreren Dateien/Modulen, usw. bestehen. + +### **FastAPI** Anwendungsdatei + +Nehmen wir an, Sie haben eine Dateistruktur wie in [Größere Anwendungen](bigger-applications.md){.internal-link target=_blank} beschrieben: + +``` +. +├── app +│   ├── __init__.py +│   └── main.py +``` + +In der Datei `main.py` haben Sie Ihre **FastAPI**-Anwendung: + + +```Python +{!../../../docs_src/app_testing/main.py!} +``` + +### Testdatei + +Dann könnten Sie eine Datei `test_main.py` mit Ihren Tests haben. Sie könnte sich im selben Python-Package befinden (dasselbe Verzeichnis mit einer `__init__.py`-Datei): + +``` hl_lines="5" +. +├── app +│   ├── __init__.py +│   ├── main.py +│   └── test_main.py +``` + +Da sich diese Datei im selben Package befindet, können Sie relative Importe verwenden, um das Objekt `app` aus dem `main`-Modul (`main.py`) zu importieren: + +```Python hl_lines="3" +{!../../../docs_src/app_testing/test_main.py!} +``` + +... und haben den Code für die Tests wie zuvor. + +## Testen: erweitertes Beispiel + +Nun erweitern wir dieses Beispiel und fügen weitere Details hinzu, um zu sehen, wie verschiedene Teile getestet werden. + +### Erweiterte **FastAPI**-Anwendungsdatei + +Fahren wir mit der gleichen Dateistruktur wie zuvor fort: + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +│   └── test_main.py +``` + +Nehmen wir an, dass die Datei `main.py` mit Ihrer **FastAPI**-Anwendung jetzt einige andere **Pfadoperationen** hat. + +Sie verfügt über eine `GET`-Operation, die einen Fehler zurückgeben könnte. + +Sie verfügt über eine `POST`-Operation, die mehrere Fehler zurückgeben könnte. + +Beide *Pfadoperationen* erfordern einen `X-Token`-Header. + +=== "Python 3.10+" + + ```Python + {!> ../../../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.8+" + + ```Python + {!> ../../../docs_src/app_testing/app_b_an/main.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python + {!> ../../../docs_src/app_testing/app_b_py310/main.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python + {!> ../../../docs_src/app_testing/app_b/main.py!} + ``` + +### Erweiterte Testdatei + +Anschließend könnten Sie `test_main.py` mit den erweiterten Tests aktualisieren: + +```Python +{!> ../../../docs_src/app_testing/app_b/test_main.py!} +``` + +Wenn Sie möchten, dass der Client Informationen im Request übergibt und Sie nicht wissen, wie das geht, können Sie suchen (googeln), wie es mit `httpx` gemacht wird, oder sogar, wie es mit `requests` gemacht wird, da das Design von HTTPX auf dem Design von Requests basiert. + +Dann machen Sie in Ihren Tests einfach das gleiche. + +Z. B.: + +* Um einen *Pfad*- oder *Query*-Parameter zu übergeben, fügen Sie ihn der URL selbst hinzu. +* Um einen JSON-Body zu übergeben, übergeben Sie ein Python-Objekt (z. B. ein `dict`) an den Parameter `json`. +* Wenn Sie *Formulardaten* anstelle von JSON senden müssen, verwenden Sie stattdessen den `data`-Parameter. +* Um *Header* zu übergeben, verwenden Sie ein `dict` im `headers`-Parameter. +* Für *Cookies* ein `dict` im `cookies`-Parameter. + +Weitere Informationen zum Übergeben von Daten an das Backend (mithilfe von `httpx` oder dem `TestClient`) finden Sie in der HTTPX-Dokumentation. + +!!! info + Beachten Sie, dass der `TestClient` Daten empfängt, die nach JSON konvertiert werden können, keine Pydantic-Modelle. + + Wenn Sie ein Pydantic-Modell in Ihrem Test haben und dessen Daten während des Testens an die Anwendung senden möchten, können Sie den `jsonable_encoder` verwenden, der in [JSON-kompatibler Encoder](encoder.md){.internal-link target=_blank} beschrieben wird. + +## Tests ausführen + +Danach müssen Sie nur noch `pytest` installieren: + +
+ +```console +$ pip install pytest + +---> 100% +``` + +
+ +Es erkennt die Dateien und Tests automatisch, führt sie aus und berichtet Ihnen die Ergebnisse. + +Führen Sie die Tests aus, mit: + +
+ +```console +$ pytest + +================ test session starts ================ +platform linux -- Python 3.6.9, pytest-5.3.5, py-1.8.1, pluggy-0.13.1 +rootdir: /home/user/code/superawesome-cli/app +plugins: forked-1.1.3, xdist-1.31.0, cov-2.8.1 +collected 6 items + +---> 100% + +test_main.py ...... [100%] + +================= 1 passed in 0.03s ================= +``` + +
diff --git a/docs/em/docs/advanced/dataclasses.md b/docs/em/docs/advanced/dataclasses.md index a4c2871062ccb..e8c4b99a23e8d 100644 --- a/docs/em/docs/advanced/dataclasses.md +++ b/docs/em/docs/advanced/dataclasses.md @@ -8,7 +8,7 @@ FastAPI 🏗 🔛 🔝 **Pydantic**, & 👤 ✔️ 🌏 👆 ❔ ⚙️ Pyda {!../../../docs_src/dataclasses/tutorial001.py!} ``` -👉 🐕‍🦺 👏 **Pydantic**, ⚫️ ✔️ 🔗 🐕‍🦺 `dataclasses`. +👉 🐕‍🦺 👏 **Pydantic**, ⚫️ ✔️ 🔗 🐕‍🦺 `dataclasses`. , ⏮️ 📟 🔛 👈 🚫 ⚙️ Pydantic 🎯, FastAPI ⚙️ Pydantic 🗜 📚 🐩 🎻 Pydantic 👍 🍛 🎻. @@ -91,7 +91,7 @@ FastAPI 🏗 🔛 🔝 **Pydantic**, & 👤 ✔️ 🌏 👆 ❔ ⚙️ Pyda 👆 💪 🌀 `dataclasses` ⏮️ 🎏 Pydantic 🏷, 😖 ⚪️➡️ 👫, 🔌 👫 👆 👍 🏷, ♒️. -💡 🌅, ✅ Pydantic 🩺 🔃 🎻. +💡 🌅, ✅ Pydantic 🩺 🔃 🎻. ## ⏬ diff --git a/docs/em/docs/advanced/extending-openapi.md b/docs/em/docs/advanced/extending-openapi.md deleted file mode 100644 index 496a8d9de34f4..0000000000000 --- a/docs/em/docs/advanced/extending-openapi.md +++ /dev/null @@ -1,314 +0,0 @@ -# ↔ 🗄 - -!!! warning - 👉 👍 🏧 ⚒. 👆 🎲 💪 🚶 ⚫️. - - 🚥 👆 📄 🔰 - 👩‍💻 🦮, 👆 💪 🎲 🚶 👉 📄. - - 🚥 👆 ⏪ 💭 👈 👆 💪 🔀 🏗 🗄 🔗, 😣 👂. - -📤 💼 🌐❔ 👆 💪 💪 🔀 🏗 🗄 🔗. - -👉 📄 👆 🔜 👀 ❔. - -## 😐 🛠️ - -😐 (🔢) 🛠️, ⏩. - -`FastAPI` 🈸 (👐) ✔️ `.openapi()` 👩‍🔬 👈 📈 📨 🗄 🔗. - -🍕 🈸 🎚 🏗, *➡ 🛠️* `/openapi.json` (⚖️ ⚫️❔ 👆 ⚒ 👆 `openapi_url`) ®. - -⚫️ 📨 🎻 📨 ⏮️ 🏁 🈸 `.openapi()` 👩‍🔬. - -🔢, ⚫️❔ 👩‍🔬 `.openapi()` 🔨 ✅ 🏠 `.openapi_schema` 👀 🚥 ⚫️ ✔️ 🎚 & 📨 👫. - -🚥 ⚫️ 🚫, ⚫️ 🏗 👫 ⚙️ 🚙 🔢 `fastapi.openapi.utils.get_openapi`. - -& 👈 🔢 `get_openapi()` 📨 🔢: - -* `title`: 🗄 📛, 🎦 🩺. -* `version`: ⏬ 👆 🛠️, ✅ `2.5.0`. -* `openapi_version`: ⏬ 🗄 🔧 ⚙️. 🔢, ⏪: `3.0.2`. -* `description`: 📛 👆 🛠️. -* `routes`: 📇 🛣, 👫 🔠 ® *➡ 🛠️*. 👫 ✊ ⚪️➡️ `app.routes`. - -## 🔑 🔢 - -⚙️ ℹ 🔛, 👆 💪 ⚙️ 🎏 🚙 🔢 🏗 🗄 🔗 & 🔐 🔠 🍕 👈 👆 💪. - -🖼, ➡️ 🚮 📄 🗄 ↔ 🔌 🛃 🔱. - -### 😐 **FastAPI** - -🥇, ✍ 🌐 👆 **FastAPI** 🈸 🛎: - -```Python hl_lines="1 4 7-9" -{!../../../docs_src/extending_openapi/tutorial001.py!} -``` - -### 🏗 🗄 🔗 - -⤴️, ⚙️ 🎏 🚙 🔢 🏗 🗄 🔗, 🔘 `custom_openapi()` 🔢: - -```Python hl_lines="2 15-20" -{!../../../docs_src/extending_openapi/tutorial001.py!} -``` - -### 🔀 🗄 🔗 - -🔜 👆 💪 🚮 📄 ↔, ❎ 🛃 `x-logo` `info` "🎚" 🗄 🔗: - -```Python hl_lines="21-23" -{!../../../docs_src/extending_openapi/tutorial001.py!} -``` - -### 💾 🗄 🔗 - -👆 💪 ⚙️ 🏠 `.openapi_schema` "💾", 🏪 👆 🏗 🔗. - -👈 🌌, 👆 🈸 🏆 🚫 ✔️ 🏗 🔗 🔠 🕰 👩‍💻 📂 👆 🛠️ 🩺. - -⚫️ 🔜 🏗 🕴 🕐, & ⤴️ 🎏 💾 🔗 🔜 ⚙️ ⏭ 📨. - -```Python hl_lines="13-14 24-25" -{!../../../docs_src/extending_openapi/tutorial001.py!} -``` - -### 🔐 👩‍🔬 - -🔜 👆 💪 ❎ `.openapi()` 👩‍🔬 ⏮️ 👆 🆕 🔢. - -```Python hl_lines="28" -{!../../../docs_src/extending_openapi/tutorial001.py!} -``` - -### ✅ ⚫️ - -🕐 👆 🚶 http://127.0.0.1:8000/redoc 👆 🔜 👀 👈 👆 ⚙️ 👆 🛃 🔱 (👉 🖼, **FastAPI**'Ⓜ 🔱): - - - -## 👤-🕸 🕸 & 🎚 🩺 - -🛠️ 🩺 ⚙️ **🦁 🎚** & **📄**, & 🔠 👈 💪 🕸 & 🎚 📁. - -🔢, 👈 📁 🍦 ⚪️➡️ 💲. - -✋️ ⚫️ 💪 🛃 ⚫️, 👆 💪 ⚒ 🎯 💲, ⚖️ 🍦 📁 👆. - -👈 ⚠, 🖼, 🚥 👆 💪 👆 📱 🚧 👷 ⏪ 📱, 🍵 📂 🕸 🔐, ⚖️ 🇧🇿 🕸. - -📥 👆 🔜 👀 ❔ 🍦 👈 📁 👆, 🎏 FastAPI 📱, & 🔗 🩺 ⚙️ 👫. - -### 🏗 📁 📊 - -➡️ 💬 👆 🏗 📁 📊 👀 💖 👉: - -``` -. -├── app -│ ├── __init__.py -│ ├── main.py -``` - -🔜 ✍ 📁 🏪 📚 🎻 📁. - -👆 🆕 📁 📊 💪 👀 💖 👉: - -``` -. -├── app -│   ├── __init__.py -│   ├── main.py -└── static/ -``` - -### ⏬ 📁 - -⏬ 🎻 📁 💪 🩺 & 🚮 👫 🔛 👈 `static/` 📁. - -👆 💪 🎲 ▶️️-🖊 🔠 🔗 & 🖊 🎛 🎏 `Save link as...`. - -**🦁 🎚** ⚙️ 📁: - -* `swagger-ui-bundle.js` -* `swagger-ui.css` - -& **📄** ⚙️ 📁: - -* `redoc.standalone.js` - -⏮️ 👈, 👆 📁 📊 💪 👀 💖: - -``` -. -├── app -│   ├── __init__.py -│   ├── main.py -└── static - ├── redoc.standalone.js - ├── swagger-ui-bundle.js - └── swagger-ui.css -``` - -### 🍦 🎻 📁 - -* 🗄 `StaticFiles`. -* "🗻" `StaticFiles()` 👐 🎯 ➡. - -```Python hl_lines="7 11" -{!../../../docs_src/extending_openapi/tutorial002.py!} -``` - -### 💯 🎻 📁 - -▶️ 👆 🈸 & 🚶 http://127.0.0.1:8000/static/redoc.standalone.js. - -👆 🔜 👀 📶 📏 🕸 📁 **📄**. - -⚫️ 💪 ▶️ ⏮️ 🕳 💖: - -```JavaScript -/*! - * ReDoc - OpenAPI/Swagger-generated API Reference Documentation - * ------------------------------------------------------------- - * Version: "2.0.0-rc.18" - * Repo: https://github.com/Redocly/redoc - */ -!function(e,t){"object"==typeof exports&&"object"==typeof m - -... -``` - -👈 ✔ 👈 👆 💆‍♂ 💪 🍦 🎻 📁 ⚪️➡️ 👆 📱, & 👈 👆 🥉 🎻 📁 🩺 ☑ 🥉. - -🔜 👥 💪 🔗 📱 ⚙️ 📚 🎻 📁 🩺. - -### ❎ 🏧 🩺 - -🥇 🔁 ❎ 🏧 🩺, 📚 ⚙️ 💲 🔢. - -❎ 👫, ⚒ 👫 📛 `None` 🕐❔ 🏗 👆 `FastAPI` 📱: - -```Python hl_lines="9" -{!../../../docs_src/extending_openapi/tutorial002.py!} -``` - -### 🔌 🛃 🩺 - -🔜 👆 💪 ✍ *➡ 🛠️* 🛃 🩺. - -👆 💪 🏤-⚙️ FastAPI 🔗 🔢 ✍ 🕸 📃 🩺, & 🚶‍♀️ 👫 💪 ❌: - -* `openapi_url`: 📛 🌐❔ 🕸 📃 🩺 💪 🤚 🗄 🔗 👆 🛠️. 👆 💪 ⚙️ 📥 🔢 `app.openapi_url`. -* `title`: 📛 👆 🛠️. -* `oauth2_redirect_url`: 👆 💪 ⚙️ `app.swagger_ui_oauth2_redirect_url` 📥 ⚙️ 🔢. -* `swagger_js_url`: 📛 🌐❔ 🕸 👆 🦁 🎚 🩺 💪 🤚 **🕸** 📁. 👉 1️⃣ 👈 👆 👍 📱 🔜 🍦. -* `swagger_css_url`: 📛 🌐❔ 🕸 👆 🦁 🎚 🩺 💪 🤚 **🎚** 📁. 👉 1️⃣ 👈 👆 👍 📱 🔜 🍦. - -& ➡ 📄... - -```Python hl_lines="2-6 14-22 25-27 30-36" -{!../../../docs_src/extending_openapi/tutorial002.py!} -``` - -!!! tip - *➡ 🛠️* `swagger_ui_redirect` 👩‍🎓 🕐❔ 👆 ⚙️ Oauth2️⃣. - - 🚥 👆 🛠️ 👆 🛠️ ⏮️ Oauth2️⃣ 🐕‍🦺, 👆 🔜 💪 🔓 & 👟 🔙 🛠️ 🩺 ⏮️ 📎 🎓. & 🔗 ⏮️ ⚫️ ⚙️ 🎰 Oauth2️⃣ 🤝. - - 🦁 🎚 🔜 🍵 ⚫️ ⛅ 🎑 👆, ✋️ ⚫️ 💪 👉 "❎" 👩‍🎓. - -### ✍ *➡ 🛠️* 💯 ⚫️ - -🔜, 💪 💯 👈 🌐 👷, ✍ *➡ 🛠️*: - -```Python hl_lines="39-41" -{!../../../docs_src/extending_openapi/tutorial002.py!} -``` - -### 💯 ⚫️ - -🔜, 👆 🔜 💪 🔌 👆 📻, 🚶 👆 🩺 http://127.0.0.1:8000/docs, & 🔃 📃. - -& 🍵 🕸, 👆 🔜 💪 👀 🩺 👆 🛠️ & 🔗 ⏮️ ⚫️. - -## 🛠️ 🦁 🎚 - -👆 💪 🔗 ➕ 🦁 🎚 🔢. - -🔗 👫, 🚶‍♀️ `swagger_ui_parameters` ❌ 🕐❔ 🏗 `FastAPI()` 📱 🎚 ⚖️ `get_swagger_ui_html()` 🔢. - -`swagger_ui_parameters` 📨 📖 ⏮️ 📳 🚶‍♀️ 🦁 🎚 🔗. - -FastAPI 🗜 📳 **🎻** ⚒ 👫 🔗 ⏮️ 🕸, 👈 ⚫️❔ 🦁 🎚 💪. - -### ❎ ❕ 🎦 - -🖼, 👆 💪 ❎ ❕ 🎦 🦁 🎚. - -🍵 🔀 ⚒, ❕ 🎦 🛠️ 🔢: - - - -✋️ 👆 💪 ❎ ⚫️ ⚒ `syntaxHighlight` `False`: - -```Python hl_lines="3" -{!../../../docs_src/extending_openapi/tutorial003.py!} -``` - -...& ⤴️ 🦁 🎚 🏆 🚫 🎦 ❕ 🎦 🚫🔜: - - - -### 🔀 🎢 - -🎏 🌌 👆 💪 ⚒ ❕ 🎦 🎢 ⏮️ 🔑 `"syntaxHighlight.theme"` (👀 👈 ⚫️ ✔️ ❣ 🖕): - -```Python hl_lines="3" -{!../../../docs_src/extending_openapi/tutorial004.py!} -``` - -👈 📳 🔜 🔀 ❕ 🎦 🎨 🎢: - - - -### 🔀 🔢 🦁 🎚 🔢 - -FastAPI 🔌 🔢 📳 🔢 ☑ 🌅 ⚙️ 💼. - -⚫️ 🔌 👫 🔢 📳: - -```Python -{!../../../fastapi/openapi/docs.py[ln:7-13]!} -``` - -👆 💪 🔐 🙆 👫 ⚒ 🎏 💲 ❌ `swagger_ui_parameters`. - -🖼, ❎ `deepLinking` 👆 💪 🚶‍♀️ 👉 ⚒ `swagger_ui_parameters`: - -```Python hl_lines="3" -{!../../../docs_src/extending_openapi/tutorial005.py!} -``` - -### 🎏 🦁 🎚 🔢 - -👀 🌐 🎏 💪 📳 👆 💪 ⚙️, ✍ 🛂 🩺 🦁 🎚 🔢. - -### 🕸-🕴 ⚒ - -🦁 🎚 ✔ 🎏 📳 **🕸-🕴** 🎚 (🖼, 🕸 🔢). - -FastAPI 🔌 👫 🕸-🕴 `presets` ⚒: - -```JavaScript -presets: [ - SwaggerUIBundle.presets.apis, - SwaggerUIBundle.SwaggerUIStandalonePreset -] -``` - -👫 **🕸** 🎚, 🚫 🎻, 👆 💪 🚫 🚶‍♀️ 👫 ⚪️➡️ 🐍 📟 🔗. - -🚥 👆 💪 ⚙️ 🕸-🕴 📳 💖 📚, 👆 💪 ⚙️ 1️⃣ 👩‍🔬 🔛. 🔐 🌐 🦁 🎚 *➡ 🛠️* & ❎ ✍ 🙆 🕸 👆 💪. diff --git a/docs/em/docs/advanced/openapi-callbacks.md b/docs/em/docs/advanced/openapi-callbacks.md index 630b75ed29f0b..3355d6071b277 100644 --- a/docs/em/docs/advanced/openapi-callbacks.md +++ b/docs/em/docs/advanced/openapi-callbacks.md @@ -36,7 +36,7 @@ ``` !!! tip - `callback_url` 🔢 🔢 ⚙️ Pydantic 📛 🆎. + `callback_url` 🔢 🔢 ⚙️ Pydantic 📛 🆎. 🕴 🆕 👜 `callbacks=messages_callback_router.routes` ❌ *➡ 🛠️ 👨‍🎨*. 👥 🔜 👀 ⚫️❔ 👈 ⏭. diff --git a/docs/em/docs/advanced/security/oauth2-scopes.md b/docs/em/docs/advanced/security/oauth2-scopes.md index a4684352ccd4d..d82fe152bef31 100644 --- a/docs/em/docs/advanced/security/oauth2-scopes.md +++ b/docs/em/docs/advanced/security/oauth2-scopes.md @@ -56,7 +56,7 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀. 🥇, ➡️ 🔜 👀 🍕 👈 🔀 ⚪️➡️ 🖼 👑 **🔰 - 👩‍💻 🦮** [Oauth2️⃣ ⏮️ 🔐 (& 🔁), 📨 ⏮️ 🥙 🤝](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. 🔜 ⚙️ Oauth2️⃣ ↔: -```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 153" +```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" {!../../../docs_src/security/tutorial005.py!} ``` @@ -93,7 +93,7 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀. ✋️ 👆 🈸, 💂‍♂, 👆 🔜 ⚒ 💭 👆 🕴 🚮 ↔ 👈 👩‍💻 🤙 💪 ✔️, ⚖️ 🕐 👆 ✔️ 🔁. -```Python hl_lines="153" +```Python hl_lines="155" {!../../../docs_src/security/tutorial005.py!} ``` @@ -118,7 +118,7 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀. 👥 🔨 ⚫️ 📥 🎦 ❔ **FastAPI** 🍵 ↔ 📣 🎏 🎚. -```Python hl_lines="4 139 166" +```Python hl_lines="4 139 168" {!../../../docs_src/security/tutorial005.py!} ``` diff --git a/docs/em/docs/advanced/settings.md b/docs/em/docs/advanced/settings.md index bc50bf755ae43..c172120235414 100644 --- a/docs/em/docs/advanced/settings.md +++ b/docs/em/docs/advanced/settings.md @@ -125,7 +125,7 @@ Hello World from Python ## Pydantic `Settings` -👐, Pydantic 🚚 👑 🚙 🍵 👫 ⚒ 👟 ⚪️➡️ 🌐 🔢 ⏮️ Pydantic: ⚒ 🧾. +👐, Pydantic 🚚 👑 🚙 🍵 👫 ⚒ 👟 ⚪️➡️ 🌐 🔢 ⏮️ Pydantic: ⚒ 🧾. ### ✍ `Settings` 🎚 @@ -221,7 +221,7 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uvicorn main:app ``` !!! tip - 👥 🔜 🔬 `@lru_cache()` 🍖. + 👥 🔜 🔬 `@lru_cache` 🍖. 🔜 👆 💪 🤔 `get_settings()` 😐 🔢. @@ -254,7 +254,7 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uvicorn main:app ✋️ 🇨🇻 📁 🚫 🤙 ✔️ ✔️ 👈 ☑ 📁. -Pydantic ✔️ 🐕‍🦺 👂 ⚪️➡️ 👉 🆎 📁 ⚙️ 🔢 🗃. 👆 💪 ✍ 🌖 Pydantic ⚒: 🇨🇻 (.🇨🇻) 🐕‍🦺. +Pydantic ✔️ 🐕‍🦺 👂 ⚪️➡️ 👉 🆎 📁 ⚙️ 🔢 🗃. 👆 💪 ✍ 🌖 Pydantic ⚒: 🇨🇻 (.🇨🇻) 🐕‍🦺. !!! tip 👉 👷, 👆 💪 `pip install python-dotenv`. @@ -279,7 +279,7 @@ APP_NAME="ChimichangApp" 📥 👥 ✍ 🎓 `Config` 🔘 👆 Pydantic `Settings` 🎓, & ⚒ `env_file` 📁 ⏮️ 🇨🇻 📁 👥 💚 ⚙️. !!! tip - `Config` 🎓 ⚙️ Pydantic 📳. 👆 💪 ✍ 🌖 Pydantic 🏷 📁 + `Config` 🎓 ⚙️ Pydantic 📳. 👆 💪 ✍ 🌖 Pydantic 🏷 📁 ### 🏗 `Settings` 🕴 🕐 ⏮️ `lru_cache` @@ -302,7 +302,7 @@ def get_settings(): 👥 🔜 ✍ 👈 🎚 🔠 📨, & 👥 🔜 👂 `.env` 📁 🔠 📨. 👶 👶 -✋️ 👥 ⚙️ `@lru_cache()` 👨‍🎨 🔛 🔝, `Settings` 🎚 🔜 ✍ 🕴 🕐, 🥇 🕰 ⚫️ 🤙. 👶 👶 +✋️ 👥 ⚙️ `@lru_cache` 👨‍🎨 🔛 🔝, `Settings` 🎚 🔜 ✍ 🕴 🕐, 🥇 🕰 ⚫️ 🤙. 👶 👶 ```Python hl_lines="1 10" {!../../../docs_src/settings/app03/main.py!} @@ -312,14 +312,14 @@ def get_settings(): #### `lru_cache` 📡 ℹ -`@lru_cache()` 🔀 🔢 ⚫️ 🎀 📨 🎏 💲 👈 📨 🥇 🕰, ↩️ 💻 ⚫️ 🔄, 🛠️ 📟 🔢 🔠 🕰. +`@lru_cache` 🔀 🔢 ⚫️ 🎀 📨 🎏 💲 👈 📨 🥇 🕰, ↩️ 💻 ⚫️ 🔄, 🛠️ 📟 🔢 🔠 🕰. , 🔢 🔛 ⚫️ 🔜 🛠️ 🕐 🔠 🌀 ❌. & ⤴️ 💲 📨 🔠 👈 🌀 ❌ 🔜 ⚙️ 🔄 & 🔄 🕐❔ 🔢 🤙 ⏮️ ⚫️❔ 🎏 🌀 ❌. 🖼, 🚥 👆 ✔️ 🔢: ```Python -@lru_cache() +@lru_cache def say_hi(name: str, salutation: str = "Ms."): return f"Hello {salutation} {name}" ``` @@ -371,7 +371,7 @@ participant execute as Execute function 👈 🌌, ⚫️ 🎭 🌖 🚥 ⚫️ 🌐 🔢. ✋️ ⚫️ ⚙️ 🔗 🔢, ⤴️ 👥 💪 🔐 ⚫️ 💪 🔬. -`@lru_cache()` 🍕 `functools` ❔ 🍕 🐍 🐩 🗃, 👆 💪 ✍ 🌅 🔃 ⚫️ 🐍 🩺 `@lru_cache()`. +`@lru_cache` 🍕 `functools` ❔ 🍕 🐍 🐩 🗃, 👆 💪 ✍ 🌅 🔃 ⚫️ 🐍 🩺 `@lru_cache`. ## 🌃 @@ -379,4 +379,4 @@ participant execute as Execute function * ⚙️ 🔗 👆 💪 📉 🔬. * 👆 💪 ⚙️ `.env` 📁 ⏮️ ⚫️. -* ⚙️ `@lru_cache()` ➡️ 👆 ❎ 👂 🇨🇻 📁 🔄 & 🔄 🔠 📨, ⏪ 🤝 👆 🔐 ⚫️ ⏮️ 🔬. +* ⚙️ `@lru_cache` ➡️ 👆 ❎ 👂 🇨🇻 📁 🔄 & 🔄 🔠 📨, ⏪ 🤝 👆 🔐 ⚫️ ⏮️ 🔬. diff --git a/docs/em/docs/advanced/templates.md b/docs/em/docs/advanced/templates.md index 1fb57725af175..0a73a4f47e811 100644 --- a/docs/em/docs/advanced/templates.md +++ b/docs/em/docs/advanced/templates.md @@ -27,7 +27,7 @@ $ pip install jinja2 * 📣 `Request` 🔢 *➡ 🛠️* 👈 🔜 📨 📄. * ⚙️ `templates` 👆 ✍ ✍ & 📨 `TemplateResponse`, 🚶‍♀️ `request` 1️⃣ 🔑-💲 👫 Jinja2️⃣ "🔑". -```Python hl_lines="4 11 15-16" +```Python hl_lines="4 11 15-18" {!../../../docs_src/templates/tutorial001.py!} ``` diff --git a/docs/em/docs/alternatives.md b/docs/em/docs/alternatives.md index 6169aa52d7128..5890b3b1364da 100644 --- a/docs/em/docs/alternatives.md +++ b/docs/em/docs/alternatives.md @@ -342,7 +342,7 @@ Webarg 🧰 👈 ⚒ 🚚 👈 🔛 🔝 📚 🛠️, 🔌 🏺. ## ⚙️ **FastAPI** -### Pydantic +### Pydantic Pydantic 🗃 🔬 💽 🔬, 🛠️ & 🧾 (⚙️ 🎻 🔗) ⚓️ 🔛 🐍 🆎 🔑. diff --git a/docs/em/docs/async.md b/docs/em/docs/async.md index 13b362b5de681..ddcae15739c13 100644 --- a/docs/em/docs/async.md +++ b/docs/em/docs/async.md @@ -409,11 +409,11 @@ async def read_burgers(): ### 🔗 -🎏 ✔ [🔗](/tutorial/dependencies/index.md){.internal-link target=_blank}. 🚥 🔗 🐩 `def` 🔢 ↩️ `async def`, ⚫️ 🏃 🔢 🧵. +🎏 ✔ [🔗](./tutorial/dependencies/index.md){.internal-link target=_blank}. 🚥 🔗 🐩 `def` 🔢 ↩️ `async def`, ⚫️ 🏃 🔢 🧵. ### 🎧-🔗 -👆 💪 ✔️ 💗 🔗 & [🎧-🔗](/tutorial/dependencies/sub-dependencies.md){.internal-link target=_blank} 🚫 🔠 🎏 (🔢 🔢 🔑), 👫 💪 ✍ ⏮️ `async def` & ⏮️ 😐 `def`. ⚫️ 🔜 👷, & 🕐 ✍ ⏮️ 😐 `def` 🔜 🤙 🔛 🔢 🧵 (⚪️➡️ 🧵) ↩️ ➖ "⌛". +👆 💪 ✔️ 💗 🔗 & [🎧-🔗](./tutorial/dependencies/sub-dependencies.md){.internal-link target=_blank} 🚫 🔠 🎏 (🔢 🔢 🔑), 👫 💪 ✍ ⏮️ `async def` & ⏮️ 😐 `def`. ⚫️ 🔜 👷, & 🕐 ✍ ⏮️ 😐 `def` 🔜 🤙 🔛 🔢 🧵 (⚪️➡️ 🧵) ↩️ ➖ "⌛". ### 🎏 🚙 🔢 diff --git a/docs/em/docs/deployment/concepts.md b/docs/em/docs/deployment/concepts.md index 8ce7754114434..162b68615a877 100644 --- a/docs/em/docs/deployment/concepts.md +++ b/docs/em/docs/deployment/concepts.md @@ -43,7 +43,7 @@ * ⏮️ 🔢 🦲 💖 Certbot 📄 🔕 * ✳ * ⏮️ 🔢 🦲 💖 Certbot 📄 🔕 -* Kubernete ⏮️ 🚧 🕹 💖 👌 +* Kubernetes ⏮️ 🚧 🕹 💖 👌 * ⏮️ 🔢 🦲 💖 🛂-👨‍💼 📄 🔕 * 🍵 🔘 ☁ 🐕‍🦺 🍕 👫 🐕‍🦺 (✍ 🔛 👶) @@ -115,7 +115,7 @@ 🖼 🧰 👈 💪 👉 👨‍🏭: * ☁ -* Kubernete +* Kubernetes * ☁ ✍ * ☁ 🐝 📳 * ✳ @@ -165,7 +165,7 @@ 🖼, 👉 💪 🍵: * ☁ -* Kubernete +* Kubernetes * ☁ ✍ * ☁ 🐝 📳 * ✳ @@ -233,15 +233,15 @@ * 🐁 🔜 **🛠️ 👨‍💼** 👂 🔛 **📢** & **⛴**, 🧬 🔜 ✔️ **💗 Uvicorn 👨‍🏭 🛠️** * **Uvicorn** 🛠️ **Uvicorn 👨‍🏭** * 1️⃣ Uvicorn **🛠️ 👨‍💼** 🔜 👂 🔛 **📢** & **⛴**, & ⚫️ 🔜 ▶️ **💗 Uvicorn 👨‍🏭 🛠️** -* **Kubernete** & 🎏 📎 **📦 ⚙️** +* **Kubernetes** & 🎏 📎 **📦 ⚙️** * 🕳 **☁** 🧽 🔜 👂 🔛 **📢** & **⛴**. 🧬 🔜 ✔️ **💗 📦**, 🔠 ⏮️ **1️⃣ Uvicorn 🛠️** 🏃‍♂ * **☁ 🐕‍🦺** 👈 🍵 👉 👆 * ☁ 🐕‍🦺 🔜 🎲 **🍵 🧬 👆**. ⚫️ 🔜 🎲 ➡️ 👆 🔬 **🛠️ 🏃**, ⚖️ **📦 🖼** ⚙️, 🙆 💼, ⚫️ 🔜 🌅 🎲 **👁 Uvicorn 🛠️**, & ☁ 🐕‍🦺 🔜 🈚 🔁 ⚫️. !!! tip - 🚫 😟 🚥 👫 🏬 🔃 **📦**, ☁, ⚖️ Kubernete 🚫 ⚒ 📚 🔑. + 🚫 😟 🚥 👫 🏬 🔃 **📦**, ☁, ⚖️ Kubernetes 🚫 ⚒ 📚 🔑. - 👤 🔜 💬 👆 🌅 🔃 📦 🖼, ☁, Kubernete, ♒️. 🔮 📃: [FastAPI 📦 - ☁](./docker.md){.internal-link target=_blank}. + 👤 🔜 💬 👆 🌅 🔃 📦 🖼, ☁, Kubernetes, ♒️. 🔮 📃: [FastAPI 📦 - ☁](./docker.md){.internal-link target=_blank}. ## ⏮️ 🔁 ⏭ ▶️ @@ -268,7 +268,7 @@ 📥 💪 💭: -* "🕑 📦" Kubernete 👈 🏃 ⏭ 👆 📱 📦 +* "🕑 📦" Kubernetes 👈 🏃 ⏭ 👆 📱 📦 * 🎉 ✍ 👈 🏃 ⏮️ 🔁 & ⤴️ ▶️ 👆 🈸 * 👆 🔜 💪 🌌 ▶️/⏏ *👈* 🎉 ✍, 🔍 ❌, ♒️. diff --git a/docs/em/docs/deployment/deta.md b/docs/em/docs/deployment/deta.md deleted file mode 100644 index 89b6c4bdbed57..0000000000000 --- a/docs/em/docs/deployment/deta.md +++ /dev/null @@ -1,258 +0,0 @@ -# 🛠️ FastAPI 🔛 🪔 - -👉 📄 👆 🔜 💡 ❔ 💪 🛠️ **FastAPI** 🈸 🔛 🪔 ⚙️ 🆓 📄. 👶 - -⚫️ 🔜 ✊ 👆 🔃 **1️⃣0️⃣ ⏲**. - -!!! info - 🪔 **FastAPI** 💰. 👶 - -## 🔰 **FastAPI** 📱 - -* ✍ 📁 👆 📱, 🖼, `./fastapideta/` & ⛔ 🔘 ⚫️. - -### FastAPI 📟 - -* ✍ `main.py` 📁 ⏮️: - -```Python -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): - return {"item_id": item_id} -``` - -### 📄 - -🔜, 🎏 📁 ✍ 📁 `requirements.txt` ⏮️: - -```text -fastapi -``` - -!!! tip - 👆 🚫 💪 ❎ Uvicorn 🛠️ 🔛 🪔, 👐 👆 🔜 🎲 💚 ❎ ⚫️ 🌐 💯 👆 📱. - -### 📁 📊 - -👆 🔜 🔜 ✔️ 1️⃣ 📁 `./fastapideta/` ⏮️ 2️⃣ 📁: - -``` -. -└── main.py -└── requirements.txt -``` - -## ✍ 🆓 🪔 🏧 - -🔜 ✍ 🆓 🏧 🔛 🪔, 👆 💪 📧 & 🔐. - -👆 🚫 💪 💳. - -## ❎ ✳ - -🕐 👆 ✔️ 👆 🏧, ❎ 🪔 : - -=== "💾, 🇸🇻" - -
- - ```console - $ curl -fsSL https://get.deta.dev/cli.sh | sh - ``` - -
- -=== "🚪 📋" - -
- - ```console - $ iwr https://get.deta.dev/cli.ps1 -useb | iex - ``` - -
- -⏮️ ❎ ⚫️, 📂 🆕 📶 👈 ❎ ✳ 🔍. - -🆕 📶, ✔ 👈 ⚫️ ☑ ❎ ⏮️: - -
- -```console -$ deta --help - -Deta command line interface for managing deta micros. -Complete documentation available at https://docs.deta.sh - -Usage: - deta [flags] - deta [command] - -Available Commands: - auth Change auth settings for a deta micro - -... -``` - -
- -!!! tip - 🚥 👆 ✔️ ⚠ ❎ ✳, ✅ 🛂 🪔 🩺. - -## 💳 ⏮️ ✳ - -🔜 💳 🪔 ⚪️➡️ ✳ ⏮️: - -
- -```console -$ deta login - -Please, log in from the web page. Waiting.. -Logged in successfully. -``` - -
- -👉 🔜 📂 🕸 🖥 & 🔓 🔁. - -## 🛠️ ⏮️ 🪔 - -⏭, 🛠️ 👆 🈸 ⏮️ 🪔 ✳: - -
- -```console -$ deta new - -Successfully created a new micro - -// Notice the "endpoint" 🔍 - -{ - "name": "fastapideta", - "runtime": "python3.7", - "endpoint": "https://qltnci.deta.dev", - "visor": "enabled", - "http_auth": "enabled" -} - -Adding dependencies... - - ----> 100% - - -Successfully installed fastapi-0.61.1 pydantic-1.7.2 starlette-0.13.6 -``` - -
- -👆 🔜 👀 🎻 📧 🎏: - -```JSON hl_lines="4" -{ - "name": "fastapideta", - "runtime": "python3.7", - "endpoint": "https://qltnci.deta.dev", - "visor": "enabled", - "http_auth": "enabled" -} -``` - -!!! tip - 👆 🛠️ 🔜 ✔️ 🎏 `"endpoint"` 📛. - -## ✅ ⚫️ - -🔜 📂 👆 🖥 👆 `endpoint` 📛. 🖼 🔛 ⚫️ `https://qltnci.deta.dev`, ✋️ 👆 🔜 🎏. - -👆 🔜 👀 🎻 📨 ⚪️➡️ 👆 FastAPI 📱: - -```JSON -{ - "Hello": "World" -} -``` - -& 🔜 🚶 `/docs` 👆 🛠️, 🖼 🔛 ⚫️ 🔜 `https://qltnci.deta.dev/docs`. - -⚫️ 🔜 🎦 👆 🩺 💖: - - - -## 🛠️ 📢 🔐 - -🔢, 🪔 🔜 🍵 🤝 ⚙️ 🍪 👆 🏧. - -✋️ 🕐 👆 🔜, 👆 💪 ⚒ ⚫️ 📢 ⏮️: - -
- -```console -$ deta auth disable - -Successfully disabled http auth -``` - -
- -🔜 👆 💪 💰 👈 📛 ⏮️ 🙆 & 👫 🔜 💪 🔐 👆 🛠️. 👶 - -## 🇺🇸🔍 - -㊗ ❗ 👆 🛠️ 👆 FastAPI 📱 🪔 ❗ 👶 👶 - -, 👀 👈 🪔 ☑ 🍵 🇺🇸🔍 👆, 👆 🚫 ✔️ ✊ 💅 👈 & 💪 💭 👈 👆 👩‍💻 🔜 ✔️ 🔐 🗜 🔗. 👶 👶 - -## ✅ 🕶 - -⚪️➡️ 👆 🩺 🎚 (👫 🔜 📛 💖 `https://qltnci.deta.dev/docs`) 📨 📨 👆 *➡ 🛠️* `/items/{item_id}`. - -🖼 ⏮️ 🆔 `5`. - -🔜 🚶 https://web.deta.sh. - -👆 🔜 👀 📤 📄 ◀️ 🤙 "◾" ⏮️ 🔠 👆 📱. - -👆 🔜 👀 📑 ⏮️ "ℹ", & 📑 "🕶", 🚶 📑 "🕶". - -📤 👆 💪 ✔ ⏮️ 📨 📨 👆 📱. - -👆 💪 ✍ 👫 & 🏤-🤾 👫. - - - -## 💡 🌅 - -☝, 👆 🔜 🎲 💚 🏪 💽 👆 📱 🌌 👈 😣 🔘 🕰. 👈 👆 💪 ⚙️ 🪔 🧢, ⚫️ ✔️ 👍 **🆓 🎚**. - -👆 💪 ✍ 🌅 🪔 🩺. - -## 🛠️ 🔧 - -👟 🔙 🔧 👥 🔬 [🛠️ 🔧](./concepts.md){.internal-link target=_blank}, 📥 ❔ 🔠 👫 🔜 🍵 ⏮️ 🪔: - -* **🇺🇸🔍**: 🍵 🪔, 👫 🔜 🤝 👆 📁 & 🍵 🇺🇸🔍 🔁. -* **🏃‍♂ 🔛 🕴**: 🍵 🪔, 🍕 👫 🐕‍🦺. -* **⏏**: 🍵 🪔, 🍕 👫 🐕‍🦺. -* **🧬**: 🍵 🪔, 🍕 👫 🐕‍🦺. -* **💾**: 📉 🔁 🪔, 👆 💪 📧 👫 📈 ⚫️. -* **⏮️ 🔁 ⏭ ▶️**: 🚫 🔗 🐕‍🦺, 👆 💪 ⚒ ⚫️ 👷 ⏮️ 👫 💾 ⚙️ ⚖️ 🌖 ✍. - -!!! note - 🪔 🔧 ⚒ ⚫️ ⏩ (& 🆓) 🛠️ 🙅 🈸 🔜. - - ⚫️ 💪 📉 📚 ⚙️ 💼, ✋️ 🎏 🕰, ⚫️ 🚫 🐕‍🦺 🎏, 💖 ⚙️ 🔢 💽 (↖️ ⚪️➡️ 🪔 👍 ☁ 💽 ⚙️), 🛃 🕹 🎰, ♒️. - - 👆 💪 ✍ 🌅 ℹ 🪔 🩺 👀 🚥 ⚫️ ▶️️ ⚒ 👆. diff --git a/docs/em/docs/deployment/docker.md b/docs/em/docs/deployment/docker.md index 51ece5599e29b..f28735ed7194a 100644 --- a/docs/em/docs/deployment/docker.md +++ b/docs/em/docs/deployment/docker.md @@ -74,7 +74,7 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] , 👆 🔜 🏃 **💗 📦** ⏮️ 🎏 👜, 💖 💽, 🐍 🈸, 🕸 💽 ⏮️ 😥 🕸 🈸, & 🔗 👫 👯‍♂️ 📨 👫 🔗 🕸. -🌐 📦 🧾 ⚙️ (💖 ☁ ⚖️ Kubernete) ✔️ 👫 🕸 ⚒ 🛠️ 🔘 👫. +🌐 📦 🧾 ⚙️ (💖 ☁ ⚖️ Kubernetes) ✔️ 👫 🕸 ⚒ 🛠️ 🔘 👫. ## 📦 & 🛠️ @@ -96,7 +96,7 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 👉 ⚫️❔ 👆 🔜 💚 **🏆 💼**, 🖼: -* ⚙️ **Kubernete** ⚖️ 🎏 🧰 +* ⚙️ **Kubernetes** ⚖️ 🎏 🧰 * 🕐❔ 🏃‍♂ 🔛 **🍓 👲** * ⚙️ ☁ 🐕‍🦺 👈 🔜 🏃 📦 🖼 👆, ♒️. @@ -395,7 +395,7 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] ⚫️ 💪 ➕1️⃣ 📦, 🖼 ⏮️ Traefik, 🚚 **🇺🇸🔍** & **🏧** 🛠️ **📄**. !!! tip - Traefik ✔️ 🛠️ ⏮️ ☁, Kubernete, & 🎏, ⚫️ 📶 ⏩ ⚒ 🆙 & 🔗 🇺🇸🔍 👆 📦 ⏮️ ⚫️. + Traefik ✔️ 🛠️ ⏮️ ☁, Kubernetes, & 🎏, ⚫️ 📶 ⏩ ⚒ 🆙 & 🔗 🇺🇸🔍 👆 📦 ⏮️ ⚫️. 👐, 🇺🇸🔍 💪 🍵 ☁ 🐕‍🦺 1️⃣ 👫 🐕‍🦺 (⏪ 🏃 🈸 📦). @@ -403,7 +403,7 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] 📤 🛎 ➕1️⃣ 🧰 🈚 **▶️ & 🏃‍♂** 👆 📦. -⚫️ 💪 **☁** 🔗, **☁ ✍**, **Kubernete**, **☁ 🐕‍🦺**, ♒️. +⚫️ 💪 **☁** 🔗, **☁ ✍**, **Kubernetes**, **☁ 🐕‍🦺**, ♒️. 🌅 (⚖️ 🌐) 💼, 📤 🙅 🎛 🛠️ 🏃 📦 🔛 🕴 & 🛠️ ⏏ 🔛 ❌. 🖼, ☁, ⚫️ 📋 ⏸ 🎛 `--restart`. @@ -413,7 +413,7 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] 🚥 👆 ✔️ 🌑 🎰 ⏮️ **☁**, ☁ 🐝 📳, 🖖, ⚖️ ➕1️⃣ 🎏 🏗 ⚙️ 🛠️ 📎 📦 🔛 💗 🎰, ⤴️ 👆 🔜 🎲 💚 **🍵 🧬** **🌑 🎚** ↩️ ⚙️ **🛠️ 👨‍💼** (💖 🐁 ⏮️ 👨‍🏭) 🔠 📦. -1️⃣ 📚 📎 📦 🧾 ⚙️ 💖 Kubernete 🛎 ✔️ 🛠️ 🌌 🚚 **🧬 📦** ⏪ 🔗 **📐 ⚖** 📨 📨. 🌐 **🌑 🎚**. +1️⃣ 📚 📎 📦 🧾 ⚙️ 💖 Kubernetes 🛎 ✔️ 🛠️ 🌌 🚚 **🧬 📦** ⏪ 🔗 **📐 ⚖** 📨 📨. 🌐 **🌑 🎚**. 📚 💼, 👆 🔜 🎲 💚 🏗 **☁ 🖼 ⚪️➡️ 🖌** [🔬 🔛](#dockerfile), ❎ 👆 🔗, & 🏃‍♂ **👁 Uvicorn 🛠️** ↩️ 🏃‍♂ 🕳 💖 🐁 ⏮️ Uvicorn 👨‍🏭. @@ -430,7 +430,7 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] ### 1️⃣ 📐 ⚙ - 💗 👨‍🏭 📦 -🕐❔ 👷 ⏮️ **Kubernete** ⚖️ 🎏 📎 📦 🧾 ⚙️, ⚙️ 👫 🔗 🕸 🛠️ 🔜 ✔ 👁 **📐 ⚙** 👈 👂 🔛 👑 **⛴** 📶 📻 (📨) 🎲 **💗 📦** 🏃 👆 📱. +🕐❔ 👷 ⏮️ **Kubernetes** ⚖️ 🎏 📎 📦 🧾 ⚙️, ⚙️ 👫 🔗 🕸 🛠️ 🔜 ✔ 👁 **📐 ⚙** 👈 👂 🔛 👑 **⛴** 📶 📻 (📨) 🎲 **💗 📦** 🏃 👆 📱. 🔠 👫 📦 🏃‍♂ 👆 📱 🔜 🛎 ✔️ **1️⃣ 🛠️** (✅ Uvicorn 🛠️ 🏃 👆 FastAPI 🈸). 👫 🔜 🌐 **🌓 📦**, 🏃‍♂ 🎏 👜, ✋️ 🔠 ⏮️ 🚮 👍 🛠️, 💾, ♒️. 👈 🌌 👆 🔜 ✊ 📈 **🛠️** **🎏 🐚** 💽, ⚖️ **🎏 🎰**. @@ -489,7 +489,7 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] 🚥 👆 🏃 **👁 🛠️ 📍 📦** 👆 🔜 ✔️ 🌅 ⚖️ 🌘 👍-🔬, ⚖, & 📉 💸 💾 🍴 🔠 👈 📦 (🌅 🌘 1️⃣ 🚥 👫 🔁). -& ⤴️ 👆 💪 ⚒ 👈 🎏 💾 📉 & 📄 👆 📳 👆 📦 🧾 ⚙️ (🖼 **Kubernete**). 👈 🌌 ⚫️ 🔜 💪 **🔁 📦** **💪 🎰** ✊ 🔘 🏧 💸 💾 💪 👫, & 💸 💪 🎰 🌑. +& ⤴️ 👆 💪 ⚒ 👈 🎏 💾 📉 & 📄 👆 📳 👆 📦 🧾 ⚙️ (🖼 **Kubernetes**). 👈 🌌 ⚫️ 🔜 💪 **🔁 📦** **💪 🎰** ✊ 🔘 🏧 💸 💾 💪 👫, & 💸 💪 🎰 🌑. 🚥 👆 🈸 **🙅**, 👉 🔜 🎲 **🚫 ⚠**, & 👆 💪 🚫 💪 ✔ 🏋️ 💾 📉. ✋️ 🚥 👆 **⚙️ 📚 💾** (🖼 ⏮️ **🎰 🏫** 🏷), 👆 🔜 ✅ ❔ 🌅 💾 👆 😩 & 🔆 **🔢 📦** 👈 🏃 **🔠 🎰** (& 🎲 🚮 🌖 🎰 👆 🌑). @@ -497,14 +497,14 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] ## ⏮️ 🔁 ⏭ ▶️ & 📦 -🚥 👆 ⚙️ 📦 (✅ ☁, Kubernete), ⤴️ 📤 2️⃣ 👑 🎯 👆 💪 ⚙️. +🚥 👆 ⚙️ 📦 (✅ ☁, Kubernetes), ⤴️ 📤 2️⃣ 👑 🎯 👆 💪 ⚙️. ### 💗 📦 -🚥 👆 ✔️ **💗 📦**, 🎲 🔠 1️⃣ 🏃 **👁 🛠️** (🖼, **Kubernete** 🌑), ⤴️ 👆 🔜 🎲 💚 ✔️ **🎏 📦** 🔨 👷 **⏮️ 📶** 👁 📦, 🏃 👁 🛠️, **⏭** 🏃 🔁 👨‍🏭 📦. +🚥 👆 ✔️ **💗 📦**, 🎲 🔠 1️⃣ 🏃 **👁 🛠️** (🖼, **Kubernetes** 🌑), ⤴️ 👆 🔜 🎲 💚 ✔️ **🎏 📦** 🔨 👷 **⏮️ 📶** 👁 📦, 🏃 👁 🛠️, **⏭** 🏃 🔁 👨‍🏭 📦. !!! info - 🚥 👆 ⚙️ Kubernete, 👉 🔜 🎲 🕑 📦. + 🚥 👆 ⚙️ Kubernetes, 👉 🔜 🎲 🕑 📦. 🚥 👆 ⚙️ 💼 📤 🙅‍♂ ⚠ 🏃‍♂ 👈 ⏮️ 📶 **💗 🕰 🔗** (🖼 🚥 👆 🚫 🏃 💽 🛠️, ✋️ ✅ 🚥 💽 🔜), ⤴️ 👆 💪 🚮 👫 🔠 📦 ▶️️ ⏭ ▶️ 👑 🛠️. @@ -574,7 +574,7 @@ COPY ./app /app/app ### 🕐❔ ⚙️ -👆 🔜 🎲 **🚫** ⚙️ 👉 🛂 🧢 🖼 (⚖️ 🙆 🎏 🎏 1️⃣) 🚥 👆 ⚙️ **Kubernete** (⚖️ 🎏) & 👆 ⏪ ⚒ **🧬** 🌑 🎚, ⏮️ 💗 **📦**. 📚 💼, 👆 👍 📆 **🏗 🖼 ⚪️➡️ 🖌** 🔬 🔛: [🏗 ☁ 🖼 FastAPI](#build-a-docker-image-for-fastapi). +👆 🔜 🎲 **🚫** ⚙️ 👉 🛂 🧢 🖼 (⚖️ 🙆 🎏 🎏 1️⃣) 🚥 👆 ⚙️ **Kubernetes** (⚖️ 🎏) & 👆 ⏪ ⚒ **🧬** 🌑 🎚, ⏮️ 💗 **📦**. 📚 💼, 👆 👍 📆 **🏗 🖼 ⚪️➡️ 🖌** 🔬 🔛: [🏗 ☁ 🖼 FastAPI](#build-a-docker-image-for-fastapi). 👉 🖼 🔜 ⚠ ✴️ 🎁 💼 🔬 🔛 [📦 ⏮️ 💗 🛠️ & 🎁 💼](#containers-with-multiple-processes-and-special-cases). 🖼, 🚥 👆 🈸 **🙅 🥃** 👈 ⚒ 🔢 🔢 🛠️ ⚓️ 🔛 💽 👷 👍, 👆 🚫 💚 😥 ⏮️ ❎ 🛠️ 🧬 🌑 🎚, & 👆 🚫 🏃 🌅 🌘 1️⃣ 📦 ⏮️ 👆 📱. ⚖️ 🚥 👆 🛠️ ⏮️ **☁ ✍**, 🏃 🔛 👁 💽, ♒️. @@ -585,7 +585,7 @@ COPY ./app /app/app 🖼: * ⏮️ **☁ ✍** 👁 💽 -* ⏮️ **Kubernete** 🌑 +* ⏮️ **Kubernetes** 🌑 * ⏮️ ☁ 🐝 📳 🌑 * ⏮️ ➕1️⃣ 🧰 💖 🖖 * ⏮️ ☁ 🐕‍🦺 👈 ✊ 👆 📦 🖼 & 🛠️ ⚫️ @@ -682,7 +682,7 @@ CMD ["uvicorn", "app.main:app", "--proxy-headers", "--host", "0.0.0.0", "--port" ## 🌃 -⚙️ 📦 ⚙️ (✅ ⏮️ **☁** & **Kubernete**) ⚫️ ▶️️ 📶 🎯 🍵 🌐 **🛠️ 🔧**: +⚙️ 📦 ⚙️ (✅ ⏮️ **☁** & **Kubernetes**) ⚫️ ▶️️ 📶 🎯 🍵 🌐 **🛠️ 🔧**: * 🇺🇸🔍 * 🏃‍♂ 🔛 🕴 diff --git a/docs/em/docs/deployment/server-workers.md b/docs/em/docs/deployment/server-workers.md index ca068d74479fe..b7e58c4f4714c 100644 --- a/docs/em/docs/deployment/server-workers.md +++ b/docs/em/docs/deployment/server-workers.md @@ -18,9 +18,9 @@ 📥 👤 🔜 🎦 👆 ❔ ⚙️ **🐁** ⏮️ **Uvicorn 👨‍🏭 🛠️**. !!! info - 🚥 👆 ⚙️ 📦, 🖼 ⏮️ ☁ ⚖️ Kubernete, 👤 🔜 💬 👆 🌅 🔃 👈 ⏭ 📃: [FastAPI 📦 - ☁](./docker.md){.internal-link target=_blank}. + 🚥 👆 ⚙️ 📦, 🖼 ⏮️ ☁ ⚖️ Kubernetes, 👤 🔜 💬 👆 🌅 🔃 👈 ⏭ 📃: [FastAPI 📦 - ☁](./docker.md){.internal-link target=_blank}. - 🎯, 🕐❔ 🏃 🔛 **Kubernete** 👆 🔜 🎲 **🚫** 💚 ⚙️ 🐁 & ↩️ 🏃 **👁 Uvicorn 🛠️ 📍 📦**, ✋️ 👤 🔜 💬 👆 🔃 ⚫️ ⏪ 👈 📃. + 🎯, 🕐❔ 🏃 🔛 **Kubernetes** 👆 🔜 🎲 **🚫** 💚 ⚙️ 🐁 & ↩️ 🏃 **👁 Uvicorn 🛠️ 📍 📦**, ✋️ 👤 🔜 💬 👆 🔃 ⚫️ ⏪ 👈 📃. ## 🐁 ⏮️ Uvicorn 👨‍🏭 @@ -167,7 +167,7 @@ $ uvicorn main:app --host 0.0.0.0 --port 8080 --workers 4 👤 🔜 🎦 👆 **🛂 ☁ 🖼** 👈 🔌 **🐁 ⏮️ Uvicorn 👨‍🏭** & 🔢 📳 👈 💪 ⚠ 🙅 💼. -📤 👤 🔜 🎦 👆 ❔ **🏗 👆 👍 🖼 ⚪️➡️ 🖌** 🏃 👁 Uvicorn 🛠️ (🍵 🐁). ⚫️ 🙅 🛠️ & 🎲 ⚫️❔ 👆 🔜 💚 🕐❔ ⚙️ 📎 📦 🧾 ⚙️ 💖 **Kubernete**. +📤 👤 🔜 🎦 👆 ❔ **🏗 👆 👍 🖼 ⚪️➡️ 🖌** 🏃 👁 Uvicorn 🛠️ (🍵 🐁). ⚫️ 🙅 🛠️ & 🎲 ⚫️❔ 👆 🔜 💚 🕐❔ ⚙️ 📎 📦 🧾 ⚙️ 💖 **Kubernetes**. ## 🌃 @@ -175,4 +175,4 @@ $ uvicorn main:app --host 0.0.0.0 --port 8080 --workers 4 👆 💪 ⚙️ 👉 🧰 & 💭 🚥 👆 ⚒ 🆙 **👆 👍 🛠️ ⚙️** ⏪ ✊ 💅 🎏 🛠️ 🔧 👆. -✅ 👅 ⏭ 📃 💡 🔃 **FastAPI** ⏮️ 📦 (✅ ☁ & Kubernete). 👆 🔜 👀 👈 👈 🧰 ✔️ 🙅 🌌 ❎ 🎏 **🛠️ 🔧** 👍. 👶 +✅ 👅 ⏭ 📃 💡 🔃 **FastAPI** ⏮️ 📦 (✅ ☁ & Kubernetes). 👆 🔜 👀 👈 👈 🧰 ✔️ 🙅 🌌 ❎ 🎏 **🛠️ 🔧** 👍. 👶 diff --git a/docs/em/docs/external-links.md b/docs/em/docs/external-links.md index 4440b1f122b74..5ba668bfacf08 100644 --- a/docs/em/docs/external-links.md +++ b/docs/em/docs/external-links.md @@ -11,77 +11,21 @@ ## 📄 -### 🇪🇸 +{% for section_name, section_content in external_links.items() %} -{% if external_links %} -{% for article in external_links.articles.english %} +## {{ section_name }} -* {{ article.title }} {{ article.author }}. -{% endfor %} -{% endif %} - -### 🇯🇵 - -{% if external_links %} -{% for article in external_links.articles.japanese %} - -* {{ article.title }} {{ article.author }}. -{% endfor %} -{% endif %} - -### 🇻🇳 - -{% if external_links %} -{% for article in external_links.articles.vietnamese %} - -* {{ article.title }} {{ article.author }}. -{% endfor %} -{% endif %} - -### 🇷🇺 - -{% if external_links %} -{% for article in external_links.articles.russian %} +{% for lang_name, lang_content in section_content.items() %} -* {{ article.title }} {{ article.author }}. -{% endfor %} -{% endif %} +### {{ lang_name }} -### 🇩🇪 +{% for item in lang_content %} -{% if external_links %} -{% for article in external_links.articles.german %} +* {{ item.title }} by {{ item.author }}. -* {{ article.title }} {{ article.author }}. {% endfor %} -{% endif %} - -### 🇹🇼 - -{% if external_links %} -{% for article in external_links.articles.taiwanese %} - -* {{ article.title }} {{ article.author }}. {% endfor %} -{% endif %} - -## 📻 - -{% if external_links %} -{% for article in external_links.podcasts.english %} - -* {{ article.title }} {{ article.author }}. -{% endfor %} -{% endif %} - -## 💬 - -{% if external_links %} -{% for article in external_links.talks.english %} - -* {{ article.title }} {{ article.author }}. {% endfor %} -{% endif %} ## 🏗 diff --git a/docs/em/docs/fastapi-people.md b/docs/em/docs/fastapi-people.md index dc94d80da7500..ec1d4c47ced53 100644 --- a/docs/em/docs/fastapi-people.md +++ b/docs/em/docs/fastapi-people.md @@ -40,7 +40,7 @@ FastAPI ✔️ 🎆 👪 👈 🙋 👫👫 ⚪️➡️ 🌐 🖥. {% if people %}
-{% for user in people.last_month_active %} +{% for user in people.last_month_experts[:10] %}
@{{ user.login }}
❔ 📨: {{ user.count }}
{% endfor %} @@ -58,7 +58,7 @@ FastAPI ✔️ 🎆 👪 👈 🙋 👫👫 ⚪️➡️ 🌐 🖥. {% if people %}
-{% for user in people.experts %} +{% for user in people.experts[:50] %}
@{{ user.login }}
❔ 📨: {{ user.count }}
{% endfor %} @@ -76,7 +76,7 @@ FastAPI ✔️ 🎆 👪 👈 🙋 👫👫 ⚪️➡️ 🌐 🖥. {% if people %}
-{% for user in people.top_contributors %} +{% for user in people.top_contributors[:50] %}
@{{ user.login }}
🚲 📨: {{ user.count }}
{% endfor %} @@ -100,7 +100,7 @@ FastAPI ✔️ 🎆 👪 👈 🙋 👫👫 ⚪️➡️ 🌐 🖥. {% if people %}
-{% for user in people.top_reviewers %} +{% for user in people.top_translations_reviewers[:50] %}
@{{ user.login }}
📄: {{ user.count }}
{% endfor %} diff --git a/docs/em/docs/features.md b/docs/em/docs/features.md index 19193da075549..3693f4c54d97a 100644 --- a/docs/em/docs/features.md +++ b/docs/em/docs/features.md @@ -174,7 +174,7 @@ FastAPI 🔌 📶 ⏩ ⚙️, ✋️ 📶 🏋️ 💾/🧶/🧠**: * ↩️ Pydantic 📊 📊 👐 🎓 👆 🔬; 🚘-🛠️, 🧽, ✍ & 👆 🤔 🔜 🌐 👷 ☑ ⏮️ 👆 ✔ 💽. -* **⏩**: - * 📇 Pydantic ⏩ 🌘 🌐 🎏 💯 🗃. * ✔ **🏗 📊**: * ⚙️ 🔗 Pydantic 🏷, 🐍 `typing`'Ⓜ `List` & `Dict`, ♒️. * & 💳 ✔ 🏗 💽 🔗 🎯 & 💪 🔬, ✅ & 📄 🎻 🔗. diff --git a/docs/em/docs/help-fastapi.md b/docs/em/docs/help-fastapi.md index d7b66185d4e74..b998ade42b493 100644 --- a/docs/em/docs/help-fastapi.md +++ b/docs/em/docs/help-fastapi.md @@ -231,8 +231,6 @@ ⚙️ 💬 🕴 🎏 🏢 💬. -📤 ⏮️ 🥊 💬, ✋️ ⚫️ 🚫 ✔️ 📻 & 🏧 ⚒, 💬 🌖 ⚠, 😧 🔜 👍 ⚙️. - ### 🚫 ⚙️ 💬 ❔ ✔️ 🤯 👈 💬 ✔ 🌅 "🆓 💬", ⚫️ ⏩ 💭 ❔ 👈 💁‍♂️ 🏢 & 🌅 ⚠ ❔,, 👆 💪 🚫 📨 ❔. diff --git a/docs/em/docs/history-design-future.md b/docs/em/docs/history-design-future.md index 7e39972de878c..7a45fe14b9d57 100644 --- a/docs/em/docs/history-design-future.md +++ b/docs/em/docs/history-design-future.md @@ -54,7 +54,7 @@ ## 📄 -⏮️ 🔬 📚 🎛, 👤 💭 👈 👤 🔜 ⚙️ **Pydantic** 🚮 📈. +⏮️ 🔬 📚 🎛, 👤 💭 👈 👤 🔜 ⚙️ **Pydantic** 🚮 📈. ⤴️ 👤 📉 ⚫️, ⚒ ⚫️ 🍕 🛠️ ⏮️ 🎻 🔗, 🐕‍🦺 🎏 🌌 🔬 ⚛ 📄, & 📉 👨‍🎨 🐕‍🦺 (🆎 ✅, ✍) ⚓️ 🔛 💯 📚 👨‍🎨. diff --git a/docs/em/docs/advanced/conditional-openapi.md b/docs/em/docs/how-to/conditional-openapi.md similarity index 100% rename from docs/em/docs/advanced/conditional-openapi.md rename to docs/em/docs/how-to/conditional-openapi.md diff --git a/docs/em/docs/advanced/custom-request-and-route.md b/docs/em/docs/how-to/custom-request-and-route.md similarity index 100% rename from docs/em/docs/advanced/custom-request-and-route.md rename to docs/em/docs/how-to/custom-request-and-route.md diff --git a/docs/em/docs/how-to/extending-openapi.md b/docs/em/docs/how-to/extending-openapi.md new file mode 100644 index 0000000000000..6b3bc00757940 --- /dev/null +++ b/docs/em/docs/how-to/extending-openapi.md @@ -0,0 +1,90 @@ +# ↔ 🗄 + +!!! warning + 👉 👍 🏧 ⚒. 👆 🎲 💪 🚶 ⚫️. + + 🚥 👆 📄 🔰 - 👩‍💻 🦮, 👆 💪 🎲 🚶 👉 📄. + + 🚥 👆 ⏪ 💭 👈 👆 💪 🔀 🏗 🗄 🔗, 😣 👂. + +📤 💼 🌐❔ 👆 💪 💪 🔀 🏗 🗄 🔗. + +👉 📄 👆 🔜 👀 ❔. + +## 😐 🛠️ + +😐 (🔢) 🛠️, ⏩. + +`FastAPI` 🈸 (👐) ✔️ `.openapi()` 👩‍🔬 👈 📈 📨 🗄 🔗. + +🍕 🈸 🎚 🏗, *➡ 🛠️* `/openapi.json` (⚖️ ⚫️❔ 👆 ⚒ 👆 `openapi_url`) ®. + +⚫️ 📨 🎻 📨 ⏮️ 🏁 🈸 `.openapi()` 👩‍🔬. + +🔢, ⚫️❔ 👩‍🔬 `.openapi()` 🔨 ✅ 🏠 `.openapi_schema` 👀 🚥 ⚫️ ✔️ 🎚 & 📨 👫. + +🚥 ⚫️ 🚫, ⚫️ 🏗 👫 ⚙️ 🚙 🔢 `fastapi.openapi.utils.get_openapi`. + +& 👈 🔢 `get_openapi()` 📨 🔢: + +* `title`: 🗄 📛, 🎦 🩺. +* `version`: ⏬ 👆 🛠️, ✅ `2.5.0`. +* `openapi_version`: ⏬ 🗄 🔧 ⚙️. 🔢, ⏪: `3.0.2`. +* `description`: 📛 👆 🛠️. +* `routes`: 📇 🛣, 👫 🔠 ® *➡ 🛠️*. 👫 ✊ ⚪️➡️ `app.routes`. + +## 🔑 🔢 + +⚙️ ℹ 🔛, 👆 💪 ⚙️ 🎏 🚙 🔢 🏗 🗄 🔗 & 🔐 🔠 🍕 👈 👆 💪. + +🖼, ➡️ 🚮 📄 🗄 ↔ 🔌 🛃 🔱. + +### 😐 **FastAPI** + +🥇, ✍ 🌐 👆 **FastAPI** 🈸 🛎: + +```Python hl_lines="1 4 7-9" +{!../../../docs_src/extending_openapi/tutorial001.py!} +``` + +### 🏗 🗄 🔗 + +⤴️, ⚙️ 🎏 🚙 🔢 🏗 🗄 🔗, 🔘 `custom_openapi()` 🔢: + +```Python hl_lines="2 15-20" +{!../../../docs_src/extending_openapi/tutorial001.py!} +``` + +### 🔀 🗄 🔗 + +🔜 👆 💪 🚮 📄 ↔, ❎ 🛃 `x-logo` `info` "🎚" 🗄 🔗: + +```Python hl_lines="21-23" +{!../../../docs_src/extending_openapi/tutorial001.py!} +``` + +### 💾 🗄 🔗 + +👆 💪 ⚙️ 🏠 `.openapi_schema` "💾", 🏪 👆 🏗 🔗. + +👈 🌌, 👆 🈸 🏆 🚫 ✔️ 🏗 🔗 🔠 🕰 👩‍💻 📂 👆 🛠️ 🩺. + +⚫️ 🔜 🏗 🕴 🕐, & ⤴️ 🎏 💾 🔗 🔜 ⚙️ ⏭ 📨. + +```Python hl_lines="13-14 24-25" +{!../../../docs_src/extending_openapi/tutorial001.py!} +``` + +### 🔐 👩‍🔬 + +🔜 👆 💪 ❎ `.openapi()` 👩‍🔬 ⏮️ 👆 🆕 🔢. + +```Python hl_lines="28" +{!../../../docs_src/extending_openapi/tutorial001.py!} +``` + +### ✅ ⚫️ + +🕐 👆 🚶 http://127.0.0.1:8000/redoc 👆 🔜 👀 👈 👆 ⚙️ 👆 🛃 🔱 (👉 🖼, **FastAPI**'Ⓜ 🔱): + + diff --git a/docs/em/docs/advanced/graphql.md b/docs/em/docs/how-to/graphql.md similarity index 100% rename from docs/em/docs/advanced/graphql.md rename to docs/em/docs/how-to/graphql.md diff --git a/docs/em/docs/advanced/sql-databases-peewee.md b/docs/em/docs/how-to/sql-databases-peewee.md similarity index 100% rename from docs/em/docs/advanced/sql-databases-peewee.md rename to docs/em/docs/how-to/sql-databases-peewee.md diff --git a/docs/em/docs/index.md b/docs/em/docs/index.md index ea8a9d41c8c47..a0ccfafb81b6b 100644 --- a/docs/em/docs/index.md +++ b/docs/em/docs/index.md @@ -27,7 +27,7 @@ --- -FastAPI 🏛, ⏩ (↕-🎭), 🕸 🛠️ 🏗 🛠️ ⏮️ 🐍 3️⃣.7️⃣ ➕ ⚓️ 🔛 🐩 🐍 🆎 🔑. +FastAPI 🏛, ⏩ (↕-🎭), 🕸 🛠️ 🏗 🛠️ ⏮️ 🐍 3️⃣.8️⃣ ➕ ⚓️ 🔛 🐩 🐍 🆎 🔑. 🔑 ⚒: @@ -120,7 +120,7 @@ FastAPI 🏛, ⏩ (↕-🎭), 🕸 🛠️ 🏗 🛠️ ⏮️ 🐍 3️⃣.7️ FastAPI 🧍 🔛 ⌚ 🐘: * 💃 🕸 🍕. -* Pydantic 📊 🍕. +* Pydantic 📊 🍕. ## 👷‍♂ @@ -452,7 +452,7 @@ item: Item * httpx - ✔ 🚥 👆 💚 ⚙️ `TestClient`. * jinja2 - ✔ 🚥 👆 💚 ⚙️ 🔢 📄 📳. -* python-multipart - ✔ 🚥 👆 💚 🐕‍🦺 📨 "✍", ⏮️ `request.form()`. +* python-multipart - ✔ 🚥 👆 💚 🐕‍🦺 📨 "✍", ⏮️ `request.form()`. * itsdangerous - ✔ `SessionMiddleware` 🐕‍🦺. * pyyaml - ✔ 💃 `SchemaGenerator` 🐕‍🦺 (👆 🎲 🚫 💪 ⚫️ ⏮️ FastAPI). * ujson - ✔ 🚥 👆 💚 ⚙️ `UJSONResponse`. diff --git a/docs/em/docs/project-generation.md b/docs/em/docs/project-generation.md index 5fd667ad19bf2..ae959e1d5c39d 100644 --- a/docs/em/docs/project-generation.md +++ b/docs/em/docs/project-generation.md @@ -79,6 +79,6 @@ * **🌈** 🕜 🏷 🛠️. * **☁ 🧠 🔎** 📨 📁 🏗. * **🏭 🔜** 🐍 🕸 💽 ⚙️ Uvicorn & 🐁. -* **☁ 👩‍💻** Kubernete (🦲) 🆑/💿 🛠️ 🏗. +* **☁ 👩‍💻** Kubernetes (🦲) 🆑/💿 🛠️ 🏗. * **🤸‍♂** 💪 ⚒ 1️⃣ 🌈 🏗 🇪🇸 ⏮️ 🏗 🖥. * **💪 🏧** 🎏 🏷 🛠️ (Pytorch, 🇸🇲), 🚫 🌈. diff --git a/docs/em/docs/python-types.md b/docs/em/docs/python-types.md index e079d9039dd37..b8f61a113fe02 100644 --- a/docs/em/docs/python-types.md +++ b/docs/em/docs/python-types.md @@ -424,7 +424,7 @@ say_hi(name=None) # This works, None is valid 🎉 ## Pydantic 🏷 -Pydantic 🐍 🗃 🎭 📊 🔬. +Pydantic 🐍 🗃 🎭 📊 🔬. 👆 📣 "💠" 💽 🎓 ⏮️ 🔢. @@ -455,14 +455,14 @@ say_hi(name=None) # This works, None is valid 🎉 ``` !!! info - 💡 🌖 🔃 Pydantic, ✅ 🚮 🩺. + 💡 🌖 🔃 Pydantic, ✅ 🚮 🩺. **FastAPI** 🌐 ⚓️ 🔛 Pydantic. 👆 🔜 👀 📚 🌅 🌐 👉 💡 [🔰 - 👩‍💻 🦮](tutorial/index.md){.internal-link target=_blank}. !!! tip - Pydantic ✔️ 🎁 🎭 🕐❔ 👆 ⚙️ `Optional` ⚖️ `Union[Something, None]` 🍵 🔢 💲, 👆 💪 ✍ 🌅 🔃 ⚫️ Pydantic 🩺 🔃 ✔ 📦 🏑. + Pydantic ✔️ 🎁 🎭 🕐❔ 👆 ⚙️ `Optional` ⚖️ `Union[Something, None]` 🍵 🔢 💲, 👆 💪 ✍ 🌅 🔃 ⚫️ Pydantic 🩺 🔃 ✔ 📦 🏑. ## 🆎 🔑 **FastAPI** diff --git a/docs/em/docs/tutorial/bigger-applications.md b/docs/em/docs/tutorial/bigger-applications.md index 7b4694387dd9b..c30bba106afa4 100644 --- a/docs/em/docs/tutorial/bigger-applications.md +++ b/docs/em/docs/tutorial/bigger-applications.md @@ -79,7 +79,7 @@ 👆 🗄 ⚫️ & ✍ "👐" 🎏 🌌 👆 🔜 ⏮️ 🎓 `FastAPI`: -```Python hl_lines="1 3" +```Python hl_lines="1 3" title="app/routers/users.py" {!../../../docs_src/bigger_applications/app/routers/users.py!} ``` @@ -89,7 +89,7 @@ ⚙️ ⚫️ 🎏 🌌 👆 🔜 ⚙️ `FastAPI` 🎓: -```Python hl_lines="6 11 16" +```Python hl_lines="6 11 16" title="app/routers/users.py" {!../../../docs_src/bigger_applications/app/routers/users.py!} ``` @@ -112,7 +112,7 @@ 👥 🔜 🔜 ⚙️ 🙅 🔗 ✍ 🛃 `X-Token` 🎚: -```Python hl_lines="1 4-6" +```Python hl_lines="1 4-6" title="app/dependencies.py" {!../../../docs_src/bigger_applications/app/dependencies.py!} ``` @@ -143,7 +143,7 @@ , ↩️ ❎ 🌐 👈 🔠 *➡ 🛠️*, 👥 💪 🚮 ⚫️ `APIRouter`. -```Python hl_lines="5-10 16 21" +```Python hl_lines="5-10 16 21" title="app/routers/items.py" {!../../../docs_src/bigger_applications/app/routers/items.py!} ``` @@ -195,7 +195,7 @@ async def read_item(item_id: str): 👥 ⚙️ ⚖ 🗄 ⏮️ `..` 🔗: -```Python hl_lines="3" +```Python hl_lines="3" title="app/routers/items.py" {!../../../docs_src/bigger_applications/app/routers/items.py!} ``` @@ -265,7 +265,7 @@ that 🔜 ⛓: ✋️ 👥 💪 🚮 _🌅_ `tags` 👈 🔜 ✔ 🎯 *➡ 🛠️*, & ➕ `responses` 🎯 👈 *➡ 🛠️*: -```Python hl_lines="30-31" +```Python hl_lines="30-31" title="app/routers/items.py" {!../../../docs_src/bigger_applications/app/routers/items.py!} ``` @@ -290,7 +290,7 @@ that 🔜 ⛓: & 👥 💪 📣 [🌐 🔗](dependencies/global-dependencies.md){.internal-link target=_blank} 👈 🔜 🌀 ⏮️ 🔗 🔠 `APIRouter`: -```Python hl_lines="1 3 7" +```Python hl_lines="1 3 7" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` @@ -298,7 +298,7 @@ that 🔜 ⛓: 🔜 👥 🗄 🎏 🔁 👈 ✔️ `APIRouter`Ⓜ: -```Python hl_lines="5" +```Python hl_lines="5" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` @@ -360,7 +360,7 @@ from .routers.users import router , 💪 ⚙️ 👯‍♂️ 👫 🎏 📁, 👥 🗄 🔁 🔗: -```Python hl_lines="4" +```Python hl_lines="5" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` @@ -368,7 +368,7 @@ from .routers.users import router 🔜, ➡️ 🔌 `router`Ⓜ ⚪️➡️ 🔁 `users` & `items`: -```Python hl_lines="10-11" +```Python hl_lines="10-11" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` @@ -401,7 +401,7 @@ from .routers.users import router 👉 🖼 ⚫️ 🔜 💎 🙅. ✋️ ➡️ 💬 👈 ↩️ ⚫️ 💰 ⏮️ 🎏 🏗 🏢, 👥 🚫🔜 🔀 ⚫️ & 🚮 `prefix`, `dependencies`, `tags`, ♒️. 🔗 `APIRouter`: -```Python hl_lines="3" +```Python hl_lines="3" title="app/internal/admin.py" {!../../../docs_src/bigger_applications/app/internal/admin.py!} ``` @@ -409,7 +409,7 @@ from .routers.users import router 👥 💪 📣 🌐 👈 🍵 ✔️ 🔀 ⏮️ `APIRouter` 🚶‍♀️ 👈 🔢 `app.include_router()`: -```Python hl_lines="14-17" +```Python hl_lines="14-17" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` @@ -432,7 +432,7 @@ from .routers.users import router 📥 👥 ⚫️... 🎦 👈 👥 💪 🤷: -```Python hl_lines="21-23" +```Python hl_lines="21-23" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` diff --git a/docs/em/docs/tutorial/body-nested-models.md b/docs/em/docs/tutorial/body-nested-models.md index f4bd50f5cbd96..c941fa08afe6b 100644 --- a/docs/em/docs/tutorial/body-nested-models.md +++ b/docs/em/docs/tutorial/body-nested-models.md @@ -192,7 +192,7 @@ my_list: List[str] ↖️ ⚪️➡️ 😐 ⭐ 🆎 💖 `str`, `int`, `float`, ♒️. 👆 💪 ⚙️ 🌅 🏗 ⭐ 🆎 👈 😖 ⚪️➡️ `str`. -👀 🌐 🎛 👆 ✔️, 🛒 🩺 Pydantic 😍 🆎. 👆 🔜 👀 🖼 ⏭ 📃. +👀 🌐 🎛 👆 ✔️, 🛒 🩺 Pydantic 😍 🆎. 👆 🔜 👀 🖼 ⏭ 📃. 🖼, `Image` 🏷 👥 ✔️ `url` 🏑, 👥 💪 📣 ⚫️ ↩️ `str`, Pydantic `HttpUrl`: diff --git a/docs/em/docs/tutorial/body.md b/docs/em/docs/tutorial/body.md index ca2f113bf4c48..db850162a21d4 100644 --- a/docs/em/docs/tutorial/body.md +++ b/docs/em/docs/tutorial/body.md @@ -6,7 +6,7 @@ 👆 🛠️ 🌖 🕧 ✔️ 📨 **📨** 💪. ✋️ 👩‍💻 🚫 🎯 💪 📨 **📨** 💪 🌐 🕰. -📣 **📨** 💪, 👆 ⚙️ Pydantic 🏷 ⏮️ 🌐 👫 🏋️ & 💰. +📣 **📨** 💪, 👆 ⚙️ Pydantic 🏷 ⏮️ 🌐 👫 🏋️ & 💰. !!! info 📨 💽, 👆 🔜 ⚙️ 1️⃣: `POST` (🌅 ⚠), `PUT`, `DELETE` ⚖️ `PATCH`. diff --git a/docs/em/docs/tutorial/extra-data-types.md b/docs/em/docs/tutorial/extra-data-types.md index dfdf6141b8ee1..54a186f126863 100644 --- a/docs/em/docs/tutorial/extra-data-types.md +++ b/docs/em/docs/tutorial/extra-data-types.md @@ -36,7 +36,7 @@ * `datetime.timedelta`: * 🐍 `datetime.timedelta`. * 📨 & 📨 🔜 🎨 `float` 🌐 🥈. - * Pydantic ✔ 🎦 ⚫️ "💾 8️⃣6️⃣0️⃣1️⃣ 🕰 ➕ 🔢", 👀 🩺 🌅 ℹ. + * Pydantic ✔ 🎦 ⚫️ "💾 8️⃣6️⃣0️⃣1️⃣ 🕰 ➕ 🔢", 👀 🩺 🌅 ℹ. * `frozenset`: * 📨 & 📨, 😥 🎏 `set`: * 📨, 📇 🔜 ✍, ❎ ❎ & 🏭 ⚫️ `set`. @@ -49,7 +49,7 @@ * `Decimal`: * 🐩 🐍 `Decimal`. * 📨 & 📨, 🍵 🎏 `float`. -* 👆 💪 ✅ 🌐 ☑ Pydantic 📊 🆎 📥: Pydantic 📊 🆎. +* 👆 💪 ✅ 🌐 ☑ Pydantic 📊 🆎 📥: Pydantic 📊 🆎. ## 🖼 diff --git a/docs/em/docs/tutorial/extra-models.md b/docs/em/docs/tutorial/extra-models.md index 06c36285d3392..7cb54a963b8b4 100644 --- a/docs/em/docs/tutorial/extra-models.md +++ b/docs/em/docs/tutorial/extra-models.md @@ -179,7 +179,7 @@ UserInDB( 👈, ⚙️ 🐩 🐍 🆎 🔑 `typing.Union`: !!! note - 🕐❔ ⚖ `Union`, 🔌 🏆 🎯 🆎 🥇, ⏩ 🌘 🎯 🆎. 🖼 🔛, 🌖 🎯 `PlaneItem` 👟 ⏭ `CarItem` `Union[PlaneItem, CarItem]`. + 🕐❔ ⚖ `Union`, 🔌 🏆 🎯 🆎 🥇, ⏩ 🌘 🎯 🆎. 🖼 🔛, 🌖 🎯 `PlaneItem` 👟 ⏭ `CarItem` `Union[PlaneItem, CarItem]`. === "🐍 3️⃣.6️⃣ & 🔛" diff --git a/docs/em/docs/tutorial/handling-errors.md b/docs/em/docs/tutorial/handling-errors.md index ef7bbfa6516fb..36d58e2af3da6 100644 --- a/docs/em/docs/tutorial/handling-errors.md +++ b/docs/em/docs/tutorial/handling-errors.md @@ -163,7 +163,7 @@ path -> item_id !!! warning 👫 📡 ℹ 👈 👆 💪 🚶 🚥 ⚫️ 🚫 ⚠ 👆 🔜. -`RequestValidationError` 🎧-🎓 Pydantic `ValidationError`. +`RequestValidationError` 🎧-🎓 Pydantic `ValidationError`. **FastAPI** ⚙️ ⚫️ 👈, 🚥 👆 ⚙️ Pydantic 🏷 `response_model`, & 👆 💽 ✔️ ❌, 👆 🔜 👀 ❌ 👆 🕹. diff --git a/docs/em/docs/tutorial/path-params.md b/docs/em/docs/tutorial/path-params.md index ea939b458a8e6..ac64d2ebb6db5 100644 --- a/docs/em/docs/tutorial/path-params.md +++ b/docs/em/docs/tutorial/path-params.md @@ -93,7 +93,7 @@ ## Pydantic -🌐 💽 🔬 🎭 🔽 🚘 Pydantic, 👆 🤚 🌐 💰 ⚪️➡️ ⚫️. & 👆 💭 👆 👍 ✋. +🌐 💽 🔬 🎭 🔽 🚘 Pydantic, 👆 🤚 🌐 💰 ⚪️➡️ ⚫️. & 👆 💭 👆 👍 ✋. 👆 💪 ⚙️ 🎏 🆎 📄 ⏮️ `str`, `float`, `bool` & 📚 🎏 🏗 📊 🆎. diff --git a/docs/em/docs/tutorial/query-params-str-validations.md b/docs/em/docs/tutorial/query-params-str-validations.md index d6b67bd518f73..1268c0d6ef014 100644 --- a/docs/em/docs/tutorial/query-params-str-validations.md +++ b/docs/em/docs/tutorial/query-params-str-validations.md @@ -227,7 +227,7 @@ q: Union[str, None] = Query(default=None, min_length=3) ``` !!! tip - Pydantic, ❔ ⚫️❔ 🏋️ 🌐 💽 🔬 & 🛠️ FastAPI, ✔️ 🎁 🎭 🕐❔ 👆 ⚙️ `Optional` ⚖️ `Union[Something, None]` 🍵 🔢 💲, 👆 💪 ✍ 🌅 🔃 ⚫️ Pydantic 🩺 🔃 ✔ 📦 🏑. + Pydantic, ❔ ⚫️❔ 🏋️ 🌐 💽 🔬 & 🛠️ FastAPI, ✔️ 🎁 🎭 🕐❔ 👆 ⚙️ `Optional` ⚖️ `Union[Something, None]` 🍵 🔢 💲, 👆 💪 ✍ 🌅 🔃 ⚫️ Pydantic 🩺 🔃 ✔ 📦 🏑. ### ⚙️ Pydantic `Required` ↩️ ❕ (`...`) @@ -371,7 +371,7 @@ http://localhost:8000/items/ === "🐍 3️⃣.1️⃣0️⃣ & 🔛" - ```Python hl_lines="12" + ```Python hl_lines="11" {!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!} ``` @@ -421,7 +421,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems === "🐍 3️⃣.1️⃣0️⃣ & 🔛" - ```Python hl_lines="17" + ```Python hl_lines="16" {!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!} ``` diff --git a/docs/em/docs/tutorial/request-files.md b/docs/em/docs/tutorial/request-files.md index 26631823f204e..be2218f89843a 100644 --- a/docs/em/docs/tutorial/request-files.md +++ b/docs/em/docs/tutorial/request-files.md @@ -3,7 +3,7 @@ 👆 💪 🔬 📁 📂 👩‍💻 ⚙️ `File`. !!! info - 📨 📂 📁, 🥇 ❎ `python-multipart`. + 📨 📂 📁, 🥇 ❎ `python-multipart`. 🤶 Ⓜ. `pip install python-multipart`. diff --git a/docs/em/docs/tutorial/request-forms-and-files.md b/docs/em/docs/tutorial/request-forms-and-files.md index 99aeca000353a..0415dbf01d5f6 100644 --- a/docs/em/docs/tutorial/request-forms-and-files.md +++ b/docs/em/docs/tutorial/request-forms-and-files.md @@ -3,7 +3,7 @@ 👆 💪 🔬 📁 & 📨 🏑 🎏 🕰 ⚙️ `File` & `Form`. !!! info - 📨 📂 📁 & /⚖️ 📨 📊, 🥇 ❎ `python-multipart`. + 📨 📂 📁 & /⚖️ 📨 📊, 🥇 ❎ `python-multipart`. 🤶 Ⓜ. `pip install python-multipart`. diff --git a/docs/em/docs/tutorial/request-forms.md b/docs/em/docs/tutorial/request-forms.md index fa74adae5de11..f12d6e65059d7 100644 --- a/docs/em/docs/tutorial/request-forms.md +++ b/docs/em/docs/tutorial/request-forms.md @@ -3,7 +3,7 @@ 🕐❔ 👆 💪 📨 📨 🏑 ↩️ 🎻, 👆 💪 ⚙️ `Form`. !!! info - ⚙️ 📨, 🥇 ❎ `python-multipart`. + ⚙️ 📨, 🥇 ❎ `python-multipart`. 🤶 Ⓜ. `pip install python-multipart`. diff --git a/docs/em/docs/tutorial/response-model.md b/docs/em/docs/tutorial/response-model.md index 6ea4413f89b32..7103e9176a6d4 100644 --- a/docs/em/docs/tutorial/response-model.md +++ b/docs/em/docs/tutorial/response-model.md @@ -378,7 +378,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 ``` !!! info - FastAPI ⚙️ Pydantic 🏷 `.dict()` ⏮️ 🚮 `exclude_unset` 🔢 🏆 👉. + FastAPI ⚙️ Pydantic 🏷 `.dict()` ⏮️ 🚮 `exclude_unset` 🔢 🏆 👉. !!! info 👆 💪 ⚙️: @@ -386,7 +386,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 * `response_model_exclude_defaults=True` * `response_model_exclude_none=True` - 🔬 Pydantic 🩺 `exclude_defaults` & `exclude_none`. + 🔬 Pydantic 🩺 `exclude_defaults` & `exclude_none`. #### 📊 ⏮️ 💲 🏑 ⏮️ 🔢 diff --git a/docs/em/docs/tutorial/schema-extra-example.md b/docs/em/docs/tutorial/schema-extra-example.md index d5bf8810aa26c..114d5a84a6619 100644 --- a/docs/em/docs/tutorial/schema-extra-example.md +++ b/docs/em/docs/tutorial/schema-extra-example.md @@ -6,7 +6,7 @@ ## Pydantic `schema_extra` -👆 💪 📣 `example` Pydantic 🏷 ⚙️ `Config` & `schema_extra`, 🔬 Pydantic 🩺: 🔗 🛃: +👆 💪 📣 `example` Pydantic 🏷 ⚙️ `Config` & `schema_extra`, 🔬 Pydantic 🩺: 🔗 🛃: === "🐍 3️⃣.6️⃣ & 🔛" diff --git a/docs/em/docs/tutorial/security/first-steps.md b/docs/em/docs/tutorial/security/first-steps.md index 6dec6f2c343a1..8c2c95cfd4acf 100644 --- a/docs/em/docs/tutorial/security/first-steps.md +++ b/docs/em/docs/tutorial/security/first-steps.md @@ -27,7 +27,7 @@ ## 🏃 ⚫️ !!! info - 🥇 ❎ `python-multipart`. + 🥇 ❎ `python-multipart`. 🤶 Ⓜ. `pip install python-multipart`. diff --git a/docs/em/docs/tutorial/security/oauth2-jwt.md b/docs/em/docs/tutorial/security/oauth2-jwt.md index bc207c5666d90..bc3c943f86dc6 100644 --- a/docs/em/docs/tutorial/security/oauth2-jwt.md +++ b/docs/em/docs/tutorial/security/oauth2-jwt.md @@ -192,13 +192,13 @@ $ openssl rand -hex 32 === "🐍 3️⃣.6️⃣ & 🔛" - ```Python hl_lines="115-128" + ```Python hl_lines="115-130" {!> ../../../docs_src/security/tutorial004.py!} ``` === "🐍 3️⃣.1️⃣0️⃣ & 🔛" - ```Python hl_lines="114-127" + ```Python hl_lines="114-129" {!> ../../../docs_src/security/tutorial004_py310.py!} ``` diff --git a/docs/em/docs/tutorial/sql-databases.md b/docs/em/docs/tutorial/sql-databases.md index 9d46c2460843a..ef08fcf4b5cd0 100644 --- a/docs/em/docs/tutorial/sql-databases.md +++ b/docs/em/docs/tutorial/sql-databases.md @@ -331,7 +331,7 @@ name: str 🔜, Pydantic *🏷* 👂, `Item` & `User`, 🚮 🔗 `Config` 🎓. -👉 `Config` 🎓 ⚙️ 🚚 📳 Pydantic. +👉 `Config` 🎓 ⚙️ 🚚 📳 Pydantic. `Config` 🎓, ⚒ 🔢 `orm_mode = True`. @@ -501,7 +501,7 @@ current_user.items "🛠️" ⚒ 🔁 💪 🕐❔ 👆 🔀 📊 👆 🇸🇲 🏷, 🚮 🆕 🔢, ♒️. 🔁 👈 🔀 💽, 🚮 🆕 🏓, 🆕 🏓, ♒️. -👆 💪 🔎 🖼 ⚗ FastAPI 🏗 📄 ⚪️➡️ [🏗 ⚡ - 📄](../project-generation.md){.internal-link target=_blank}. 🎯 `alembic` 📁 ℹ 📟. +👆 💪 🔎 🖼 ⚗ FastAPI 🏗 📄 ⚪️➡️ [🏗 ⚡ - 📄](../project-generation.md){.internal-link target=_blank}. 🎯 `alembic` 📁 ℹ 📟. ### ✍ 🔗 diff --git a/docs/en/data/external_links.yml b/docs/en/data/external_links.yml index ad738df3531e3..827581de5789d 100644 --- a/docs/en/data/external_links.yml +++ b/docs/en/data/external_links.yml @@ -1,5 +1,54 @@ -articles: - english: +Articles: + English: + - author: Kurtis Pykes - NVIDIA + link: https://developer.nvidia.com/blog/building-a-machine-learning-microservice-with-fastapi/ + title: Building a Machine Learning Microservice with FastAPI + - author: Ravgeet Dhillon - Twilio + link: https://www.twilio.com/en-us/blog/booking-appointments-twilio-notion-fastapi + title: Booking Appointments with Twilio, Notion, and FastAPI + - author: Abhinav Tripathi - Microsoft Blogs + link: https://devblogs.microsoft.com/cosmosdb/azure-cosmos-db-python-and-fastapi/ + title: Write a Python data layer with Azure Cosmos DB and FastAPI + - author: Donny Peeters + author_link: https://github.com/Donnype + link: https://bitestreams.com/blog/fastapi-sqlalchemy/ + title: 10 Tips for adding SQLAlchemy to FastAPI + - author: Jessica Temporal + author_link: https://jtemporal.com/socials + link: https://jtemporal.com/tips-on-migrating-from-flask-to-fastapi-and-vice-versa/ + title: Tips on migrating from Flask to FastAPI and vice-versa + - author: Ankit Anchlia + author_link: https://linkedin.com/in/aanchlia21 + link: https://hackernoon.com/explore-how-to-effectively-use-jwt-with-fastapi + title: Explore How to Effectively Use JWT With FastAPI + - author: Nicoló Lino + author_link: https://www.nlino.com + link: https://github.com/softwarebloat/python-tracing-demo + title: Instrument a FastAPI service adding tracing with OpenTelemetry and send/show traces in Grafana Tempo + - author: Mikhail Rozhkov, Elena Samuylova + author_link: https://www.linkedin.com/in/mnrozhkov/ + link: https://www.evidentlyai.com/blog/fastapi-tutorial + title: ML serving and monitoring with FastAPI and Evidently + - author: Visual Studio Code Team + author_link: https://code.visualstudio.com/ + link: https://code.visualstudio.com/docs/python/tutorial-fastapi + title: FastAPI Tutorial in Visual Studio Code + - author: Apitally + author_link: https://apitally.io + link: https://blog.apitally.io/fastapi-application-monitoring-made-easy + title: FastAPI application monitoring made easy + - author: John Philip + author_link: https://medium.com/@amjohnphilip + link: https://python.plainenglish.io/building-a-restful-api-with-fastapi-secure-signup-and-login-functionality-included-45cdbcb36106 + title: "Building a RESTful API with FastAPI: Secure Signup and Login Functionality Included" + - author: Keshav Malik + author_link: https://theinfosecguy.xyz/ + link: https://blog.theinfosecguy.xyz/building-a-crud-api-with-fastapi-and-supabase-a-step-by-step-guide + title: Building a CRUD API with FastAPI and Supabase + - author: Adejumo Ridwan Suleiman + author_link: https://www.linkedin.com/in/adejumoridwan/ + link: https://medium.com/python-in-plain-english/build-an-sms-spam-classifier-serverless-database-with-faunadb-and-fastapi-23dbb275bc5b + title: Build an SMS Spam Classifier Serverless Database with FaunaDB and FastAPI - author: Raf Rasenberg author_link: https://rafrasenberg.com/about/ link: https://rafrasenberg.com/fastapi-lambda/ @@ -8,10 +57,6 @@ articles: author_link: https://dev.to/ link: https://dev.to/teresafds/authorization-on-fastapi-with-casbin-41og title: Authorization on FastAPI with Casbin - - author: WayScript - author_link: https://www.wayscript.com - link: https://blog.wayscript.com/fast-api-quickstart/ - title: Quickstart Guide to Build and Host Responsive APIs with Fast API and WayScript - author: New Relic author_link: https://newrelic.com link: https://newrelic.com/instant-observability/fastapi/e559ec64-f765-4470-a15f-1901fcebb468 @@ -64,10 +109,6 @@ articles: author_link: https://dev.to/factorlive link: https://dev.to/factorlive/python-facebook-messenger-webhook-with-fastapi-on-glitch-4n90 title: Python Facebook messenger webhook with FastAPI on Glitch - - author: Dom Patmore - author_link: https://twitter.com/dompatmore - link: https://dompatmore.com/blog/authenticate-your-fastapi-app-with-auth0 - title: Authenticate Your FastAPI App with auth0 - author: Valon Januzaj author_link: https://www.linkedin.com/in/valon-januzaj-b02692187/ link: https://valonjanuzaj.medium.com/deploy-a-dockerized-fastapi-application-to-aws-cc757830ba1b @@ -80,10 +121,6 @@ articles: author_link: https://twitter.com/louis_guitton link: https://guitton.co/posts/fastapi-monitoring/ title: How to monitor your FastAPI service - - author: Julien Harbulot - author_link: https://julienharbulot.com/ - link: https://julienharbulot.com/notification-server.html - title: HTTP server to display desktop notifications - author: Precious Ndubueze author_link: https://medium.com/@gabbyprecious2000 link: https://medium.com/@gabbyprecious2000/creating-a-crud-app-with-fastapi-part-one-7c049292ad37 @@ -132,18 +169,10 @@ articles: author_link: https://wuilly.com/ link: https://wuilly.com/2019/10/real-time-notifications-with-python-and-postgres/ title: Real-time Notifications with Python and Postgres - - author: Benjamin Ramser - author_link: https://iwpnd.pw - link: https://iwpnd.pw/articles/2020-03/apache-kafka-fastapi-geostream - title: Apache Kafka producer and consumer with FastAPI and aiokafka - author: Navule Pavan Kumar Rao author_link: https://www.linkedin.com/in/navule/ link: https://www.tutlinks.com/create-and-deploy-fastapi-app-to-heroku/ title: Create and Deploy FastAPI app to Heroku without using Docker - - author: Benjamin Ramser - author_link: https://iwpnd.pw - link: https://iwpnd.pw/articles/2020-01/deploy-fastapi-to-aws-lambda - title: How to continuously deploy a FastAPI to AWS Lambda with AWS SAM - author: Arthur Henrique author_link: https://twitter.com/arthurheinrique link: https://medium.com/@arthur393/another-boilerplate-to-fastapi-azure-pipeline-ci-pytest-3c8d9a4be0bb @@ -168,10 +197,6 @@ articles: author_link: https://dev.to/dbanty link: https://dev.to/dbanty/why-i-m-leaving-flask-3ki6 title: Why I'm Leaving Flask - - author: Rob Wagner - author_link: https://robwagner.dev/ - link: https://robwagner.dev/tortoise-fastapi-setup/ - title: Setting up Tortoise ORM with FastAPI - author: Mike Moritz author_link: https://medium.com/@mike.p.moritz link: https://medium.com/@mike.p.moritz/using-docker-compose-to-deploy-a-lightweight-python-rest-api-with-a-job-queue-37e6072a209b @@ -232,7 +257,7 @@ articles: author_link: https://medium.com/@krishnardt365 link: https://medium.com/@krishnardt365/fastapi-docker-and-postgres-91943e71be92 title: Fastapi, Docker(Docker compose) and Postgres - german: + German: - author: Marcel Sander (actidoo) author_link: https://www.actidoo.com link: https://www.actidoo.com/de/blog/python-fastapi-domain-driven-design @@ -245,7 +270,7 @@ articles: author_link: https://hellocoding.de/autor/felix-schuermeyer/ link: https://hellocoding.de/blog/coding-language/python/fastapi title: REST-API Programmieren mittels Python und dem FastAPI Modul - japanese: + Japanese: - author: '@bee2' author_link: https://qiita.com/bee2 link: https://qiita.com/bee2/items/75d9c0d7ba20e7a4a0e9 @@ -294,7 +319,12 @@ articles: author_link: https://qiita.com/mtitg link: https://qiita.com/mtitg/items/47770e9a562dd150631d title: FastAPI|DB接続してCRUDするPython製APIサーバーを構築 - russian: + Portuguese: + - author: Jessica Temporal + author_link: https://jtemporal.com/socials + link: https://jtemporal.com/dicas-para-migrar-de-flask-para-fastapi-e-vice-versa/ + title: Dicas para migrar uma aplicação de Flask para FastAPI e vice-versa + Russian: - author: Troy Köhler author_link: https://www.linkedin.com/in/trkohler/ link: https://trkohler.com/fast-api-introduction-to-framework @@ -307,18 +337,26 @@ articles: author_link: https://habr.com/ru/users/57uff3r/ link: https://habr.com/ru/post/454440/ title: 'Мелкая питонячая радость #2: Starlette - Солидная примочка – FastAPI' - vietnamese: + Vietnamese: - author: Nguyễn Nhân 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: + Taiwanese: - author: Leon author_link: http://editor.leonh.space/ link: https://editor.leonh.space/2022/tortoise/ title: 'Tortoise ORM / FastAPI 整合快速筆記' -podcasts: - english: +Podcasts: + English: + - author: Real Python + author_link: https://realpython.com/ + link: https://realpython.com/podcasts/rpp/72/ + title: Starting With FastAPI and Examining Python's Import System - Episode 72 + - author: Python Bytes FM + author_link: https://pythonbytes.fm/ + link: https://www.pythonpodcast.com/fastapi-web-application-framework-episode-259/ + title: 'Do you dare to press "."? - Episode 247 - Dan #6: SQLModel - use the same models for SQL and FastAPI' - author: Podcast.`__init__` author_link: https://www.pythonpodcast.com/ link: https://www.pythonpodcast.com/fastapi-web-application-framework-episode-259/ @@ -327,8 +365,12 @@ podcasts: author_link: https://pythonbytes.fm/ link: https://pythonbytes.fm/episodes/show/123/time-to-right-the-py-wrongs?time_in_sec=855 title: FastAPI on PythonBytes -talks: - english: +Talks: + English: + - author: Jeny Sadadia + author_link: https://github.com/JenySadadia + link: https://www.youtube.com/watch?v=uZdTe8_Z6BQ + title: 'PyCon AU 2023: Testing asynchronous applications with FastAPI and pytest' - author: Sebastián Ramírez (tiangolo) author_link: https://twitter.com/tiangolo link: https://www.youtube.com/watch?v=PnpTY1f4k2U diff --git a/docs/en/data/github_sponsors.yml b/docs/en/data/github_sponsors.yml index 71afb66b14951..fb690708fc8a4 100644 --- a/docs/en/data/github_sponsors.yml +++ b/docs/en/data/github_sponsors.yml @@ -1,40 +1,49 @@ sponsors: -- - login: cryptapi +- - login: bump-sh + avatarUrl: https://avatars.githubusercontent.com/u/33217836?v=4 + url: https://github.com/bump-sh + - login: Alek99 + avatarUrl: https://avatars.githubusercontent.com/u/38776361?u=bd6c163fe787c2de1a26c881598e54b67e2482dd&v=4 + url: https://github.com/Alek99 + - login: porter-dev + avatarUrl: https://avatars.githubusercontent.com/u/62078005?v=4 + url: https://github.com/porter-dev + - login: andrew-propelauth + avatarUrl: https://avatars.githubusercontent.com/u/89474256?u=1188c27cb744bbec36447a2cfd4453126b2ddb5c&v=4 + url: https://github.com/andrew-propelauth + - login: zanfaruqui + avatarUrl: https://avatars.githubusercontent.com/u/104461687?v=4 + url: https://github.com/zanfaruqui + - login: cryptapi avatarUrl: https://avatars.githubusercontent.com/u/44925437?u=61369138589bc7fee6c417f3fbd50fbd38286cc4&v=4 url: https://github.com/cryptapi -- - login: nihpo - avatarUrl: https://avatars.githubusercontent.com/u/1841030?u=0264956d7580f7e46687a762a7baa629f84cf97c&v=4 - url: https://github.com/nihpo - - login: ObliviousAI + - login: codacy + avatarUrl: https://avatars.githubusercontent.com/u/1834093?v=4 + url: https://github.com/codacy + - login: scalar + avatarUrl: https://avatars.githubusercontent.com/u/301879?v=4 + url: https://github.com/scalar +- - login: ObliviousAI avatarUrl: https://avatars.githubusercontent.com/u/65656077?v=4 url: https://github.com/ObliviousAI -- - login: mikeckennedy - avatarUrl: https://avatars.githubusercontent.com/u/2035561?u=1bb18268bcd4d9249e1f783a063c27df9a84c05b&v=4 - url: https://github.com/mikeckennedy - - login: deta - avatarUrl: https://avatars.githubusercontent.com/u/47275976?v=4 - url: https://github.com/deta - - login: deepset-ai - avatarUrl: https://avatars.githubusercontent.com/u/51827949?v=4 - url: https://github.com/deepset-ai +- - login: databento + avatarUrl: https://avatars.githubusercontent.com/u/64141749?v=4 + url: https://github.com/databento - login: svix avatarUrl: https://avatars.githubusercontent.com/u/80175132?v=4 url: https://github.com/svix - - login: databento-bot - avatarUrl: https://avatars.githubusercontent.com/u/98378480?u=494f679996e39427f7ddb1a7de8441b7c96fb670&v=4 - url: https://github.com/databento-bot - - login: VincentParedes - avatarUrl: https://avatars.githubusercontent.com/u/103889729?v=4 - url: https://github.com/VincentParedes -- - login: getsentry - avatarUrl: https://avatars.githubusercontent.com/u/1396951?v=4 - url: https://github.com/getsentry + - login: deepset-ai + avatarUrl: https://avatars.githubusercontent.com/u/51827949?v=4 + url: https://github.com/deepset-ai + - login: mikeckennedy + avatarUrl: https://avatars.githubusercontent.com/u/2035561?u=ce6165b799ea3164cb6f5ff54ea08042057442af&v=4 + url: https://github.com/mikeckennedy + - login: ndimares + avatarUrl: https://avatars.githubusercontent.com/u/6267663?u=cfb27efde7a7212be8142abb6c058a1aeadb41b1&v=4 + url: https://github.com/ndimares - - 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 @@ -44,63 +53,168 @@ sponsors: - login: BoostryJP avatarUrl: https://avatars.githubusercontent.com/u/57932412?v=4 url: https://github.com/BoostryJP -- - login: HiredScore - avatarUrl: https://avatars.githubusercontent.com/u/3908850?v=4 - url: https://github.com/HiredScore - - login: Trivie + - login: acsone + avatarUrl: https://avatars.githubusercontent.com/u/7601056?v=4 + url: https://github.com/acsone +- - login: Trivie avatarUrl: https://avatars.githubusercontent.com/u/8161763?v=4 url: https://github.com/Trivie -- - login: JonasKs - avatarUrl: https://avatars.githubusercontent.com/u/5310116?u=98a049f3e1491bffb91e1feb7e93def6881a9389&v=4 - url: https://github.com/JonasKs -- - 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 - - login: RodneyU215 - avatarUrl: https://avatars.githubusercontent.com/u/3329665?u=ec6a9adf8e7e8e306eed7d49687c398608d1604f&v=4 - url: https://github.com/RodneyU215 - - login: tizz98 - avatarUrl: https://avatars.githubusercontent.com/u/5739698?u=f095a3659e3a8e7c69ccd822696990b521ea25f9&v=4 - url: https://github.com/tizz98 - - login: americanair +- - login: americanair avatarUrl: https://avatars.githubusercontent.com/u/12281813?v=4 url: https://github.com/americanair + - login: 84adam + avatarUrl: https://avatars.githubusercontent.com/u/13172004?u=293f3cc6bb7e6f6ecfcdd64489a3202468321254&v=4 + url: https://github.com/84adam + - login: CanoaPBC + avatarUrl: https://avatars.githubusercontent.com/u/64223768?v=4 + url: https://github.com/CanoaPBC - login: mainframeindustries avatarUrl: https://avatars.githubusercontent.com/u/55092103?v=4 url: https://github.com/mainframeindustries -- - login: povilasb - avatarUrl: https://avatars.githubusercontent.com/u/1213442?u=b11f58ed6ceea6e8297c9b310030478ebdac894d&v=4 - url: https://github.com/povilasb - - login: primer-io + - login: doseiai + avatarUrl: https://avatars.githubusercontent.com/u/57115726?v=4 + url: https://github.com/doseiai + - login: AccentDesign + avatarUrl: https://avatars.githubusercontent.com/u/2429332?v=4 + url: https://github.com/AccentDesign + - login: mangualero + avatarUrl: https://avatars.githubusercontent.com/u/3422968?u=c59272d7b5a912d6126fd6c6f17db71e20f506eb&v=4 + url: https://github.com/mangualero + - login: birkjernstrom + avatarUrl: https://avatars.githubusercontent.com/u/281715?u=4be14b43f76b4bd497b1941309bb390250b405e6&v=4 + url: https://github.com/birkjernstrom + - login: yasyf + avatarUrl: https://avatars.githubusercontent.com/u/709645?u=f36736b3c6a85f578886ecc42a740e7b436e7a01&v=4 + url: https://github.com/yasyf +- - login: primer-io avatarUrl: https://avatars.githubusercontent.com/u/62146168?v=4 url: https://github.com/primer-io -- - login: indeedeng - avatarUrl: https://avatars.githubusercontent.com/u/2905043?v=4 - url: https://github.com/indeedeng -- - login: Kludex + - login: povilasb + avatarUrl: https://avatars.githubusercontent.com/u/1213442?u=b11f58ed6ceea6e8297c9b310030478ebdac894d&v=4 + url: https://github.com/povilasb +- - login: upciti + avatarUrl: https://avatars.githubusercontent.com/u/43346262?v=4 + url: https://github.com/upciti +- - login: samuelcolvin + avatarUrl: https://avatars.githubusercontent.com/u/4039449?u=42eb3b833047c8c4b4f647a031eaef148c16d93f&v=4 + url: https://github.com/samuelcolvin + - login: Kludex avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex - - login: samuelcolvin - avatarUrl: https://avatars.githubusercontent.com/u/4039449?u=807390ba9cfe23906c3bf8a0d56aaca3cf2bfa0d&v=4 - url: https://github.com/samuelcolvin - - login: jefftriplett - avatarUrl: https://avatars.githubusercontent.com/u/50527?u=af1ddfd50f6afd6d99f333ba2ac8d0a5b245ea74&v=4 - url: https://github.com/jefftriplett - - login: medecau - avatarUrl: https://avatars.githubusercontent.com/u/59870?u=f9341c95adaba780828162fd4c7442357ecfcefa&v=4 - url: https://github.com/medecau - - login: kamalgill - avatarUrl: https://avatars.githubusercontent.com/u/133923?u=0df9181d97436ce330e9acf90ab8a54b7022efe7&v=4 - url: https://github.com/kamalgill - - login: dekoza - avatarUrl: https://avatars.githubusercontent.com/u/210980?u=c03c78a8ae1039b500dfe343665536ebc51979b2&v=4 - url: https://github.com/dekoza + - login: koconder + avatarUrl: https://avatars.githubusercontent.com/u/25068?u=582657b23622aaa3dfe68bd028a780f272f456fa&v=4 + url: https://github.com/koconder + - login: ehaca + avatarUrl: https://avatars.githubusercontent.com/u/25950317?u=cec1a3e0643b785288ae8260cc295a85ab344995&v=4 + url: https://github.com/ehaca + - login: timlrx + avatarUrl: https://avatars.githubusercontent.com/u/28362229?u=9a745ca31372ee324af682715ae88ce8522f9094&v=4 + url: https://github.com/timlrx + - login: mattmalcher + avatarUrl: https://avatars.githubusercontent.com/u/31312775?v=4 + url: https://github.com/mattmalcher + - login: Leay15 + avatarUrl: https://avatars.githubusercontent.com/u/32212558?u=c4aa9c1737e515959382a5515381757b1fd86c53&v=4 + url: https://github.com/Leay15 + - login: ygorpontelo + avatarUrl: https://avatars.githubusercontent.com/u/32963605?u=35f7103f9c4c4c2589ae5737ee882e9375ef072e&v=4 + url: https://github.com/ygorpontelo + - login: ProteinQure + avatarUrl: https://avatars.githubusercontent.com/u/33707203?v=4 + url: https://github.com/ProteinQure + - login: jsoques + avatarUrl: https://avatars.githubusercontent.com/u/12414216?u=620921d94196546cc8b9eae2cc4cbc3f95bab42f&v=4 + url: https://github.com/jsoques + - login: joeds13 + avatarUrl: https://avatars.githubusercontent.com/u/13631604?u=628eb122e08bef43767b3738752b883e8e7f6259&v=4 + url: https://github.com/joeds13 + - login: dannywade + avatarUrl: https://avatars.githubusercontent.com/u/13680237?u=418ee985bd41577b20fde81417fb2d901e875e8a&v=4 + url: https://github.com/dannywade + - login: khadrawy + avatarUrl: https://avatars.githubusercontent.com/u/13686061?u=59f25ef42ecf04c22657aac4238ce0e2d3d30304&v=4 + url: https://github.com/khadrawy + - login: mjohnsey + avatarUrl: https://avatars.githubusercontent.com/u/16784016?u=38fad2e6b411244560b3af99c5f5a4751bc81865&v=4 + url: https://github.com/mjohnsey + - login: wedwardbeck + avatarUrl: https://avatars.githubusercontent.com/u/19333237?u=1de4ae2bf8d59eb4c013f21d863cbe0f2010575f&v=4 + url: https://github.com/wedwardbeck + - login: RaamEEIL + avatarUrl: https://avatars.githubusercontent.com/u/20320552?v=4 + url: https://github.com/RaamEEIL + - login: Filimoa + avatarUrl: https://avatars.githubusercontent.com/u/21352040?u=0be845711495bbd7b756e13fcaeb8efc1ebd78ba&v=4 + url: https://github.com/Filimoa + - login: b-rad-c + avatarUrl: https://avatars.githubusercontent.com/u/25362581?u=5bb10629f4015b62bec1f9a366675d5085551af9&v=4 + url: https://github.com/b-rad-c + - login: patsatsia + avatarUrl: https://avatars.githubusercontent.com/u/61111267?u=3271b85f7a37b479c8d0ae0a235182e83c166edf&v=4 + url: https://github.com/patsatsia + - login: anthonycepeda + avatarUrl: https://avatars.githubusercontent.com/u/72019805?u=60bdf46240cff8fca482ff0fc07d963fd5e1a27c&v=4 + url: https://github.com/anthonycepeda + - login: patricioperezv + avatarUrl: https://avatars.githubusercontent.com/u/73832292?u=5f471f156e19ee7920e62ae0f4a47b95580e61cf&v=4 + url: https://github.com/patricioperezv + - login: kaoru0310 + avatarUrl: https://avatars.githubusercontent.com/u/80977929?u=1b61d10142b490e56af932ddf08a390fae8ee94f&v=4 + url: https://github.com/kaoru0310 + - login: DelfinaCare + avatarUrl: https://avatars.githubusercontent.com/u/83734439?v=4 + url: https://github.com/DelfinaCare + - login: apitally + avatarUrl: https://avatars.githubusercontent.com/u/138365043?v=4 + url: https://github.com/apitally + - login: thenickben + avatarUrl: https://avatars.githubusercontent.com/u/40610922?u=1e907d904041b7c91213951a3cb344cd37c14aaf&v=4 + url: https://github.com/thenickben + - login: ddilidili + avatarUrl: https://avatars.githubusercontent.com/u/42176885?u=c0a849dde06987434653197b5f638d3deb55fc6c&v=4 + url: https://github.com/ddilidili + - login: ramonalmeidam + avatarUrl: https://avatars.githubusercontent.com/u/45269580?u=3358750b3a5854d7c3ed77aaca7dd20a0f529d32&v=4 + url: https://github.com/ramonalmeidam + - login: dudikbender + avatarUrl: https://avatars.githubusercontent.com/u/53487583?u=3a57542938ebfd57579a0111db2b297e606d9681&v=4 + url: https://github.com/dudikbender + - login: prodhype + avatarUrl: https://avatars.githubusercontent.com/u/60444672?u=3f278cff25ea37ead487d7861d4a984795de819e&v=4 + url: https://github.com/prodhype + - login: yakkonaut + avatarUrl: https://avatars.githubusercontent.com/u/60633704?u=90a71fd631aa998ba4a96480788f017c9904e07b&v=4 + url: https://github.com/yakkonaut + - login: tcsmith + avatarUrl: https://avatars.githubusercontent.com/u/989034?u=7d8d741552b3279e8f4d3878679823a705a46f8f&v=4 + url: https://github.com/tcsmith + - login: mickaelandrieu + avatarUrl: https://avatars.githubusercontent.com/u/1247388?u=599f6e73e452a9453f2bd91e5c3100750e731ad4&v=4 + url: https://github.com/mickaelandrieu + - login: dodo5522 + avatarUrl: https://avatars.githubusercontent.com/u/1362607?u=9bf1e0e520cccc547c046610c468ce6115bbcf9f&v=4 + url: https://github.com/dodo5522 + - login: nihpo + avatarUrl: https://avatars.githubusercontent.com/u/1841030?u=0264956d7580f7e46687a762a7baa629f84cf97c&v=4 + url: https://github.com/nihpo + - login: knallgelb + avatarUrl: https://avatars.githubusercontent.com/u/2358812?u=c48cb6362b309d74cbf144bd6ad3aed3eb443e82&v=4 + url: https://github.com/knallgelb + - login: johannquerne + avatarUrl: https://avatars.githubusercontent.com/u/2736484?u=9b3381546a25679913a2b08110e4373c98840821&v=4 + url: https://github.com/johannquerne + - login: Shark009 + avatarUrl: https://avatars.githubusercontent.com/u/3163309?u=0c6f4091b0eda05c44c390466199826e6dc6e431&v=4 + url: https://github.com/Shark009 + - login: dblackrun + avatarUrl: https://avatars.githubusercontent.com/u/3528486?v=4 + url: https://github.com/dblackrun + - login: jstanden + avatarUrl: https://avatars.githubusercontent.com/u/63288?u=c3658d57d2862c607a0e19c2101c3c51876e36ad&v=4 + url: https://github.com/jstanden + - login: andreaso + avatarUrl: https://avatars.githubusercontent.com/u/285964?u=837265cc7562c0685f25b2d81cd9de0434fe107c&v=4 + url: https://github.com/andreaso - login: pamelafox avatarUrl: https://avatars.githubusercontent.com/u/297042?v=4 url: https://github.com/pamelafox @@ -116,33 +230,33 @@ sponsors: - login: falkben avatarUrl: https://avatars.githubusercontent.com/u/653031?u=ad9838e089058c9e5a0bab94c0eec7cc181e0cd0&v=4 url: https://github.com/falkben - - login: jqueguiner - avatarUrl: https://avatars.githubusercontent.com/u/690878?u=bd65cc1f228ce6455e56dfaca3ef47c33bc7c3b0&v=4 - url: https://github.com/jqueguiner - - 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: mrkmcknz - avatarUrl: https://avatars.githubusercontent.com/u/1089376?u=2b9b8a8c25c33a4f6c220095638bd821cdfd13a3&v=4 - url: https://github.com/mrkmcknz - - login: mickaelandrieu - avatarUrl: https://avatars.githubusercontent.com/u/1247388?u=599f6e73e452a9453f2bd91e5c3100750e731ad4&v=4 - url: https://github.com/mickaelandrieu - - login: jonakoudijs - avatarUrl: https://avatars.githubusercontent.com/u/1906344?u=5ca0c9a1a89b6a2ba31abe35c66bdc07af60a632&v=4 - url: https://github.com/jonakoudijs - - login: Shark009 - avatarUrl: https://avatars.githubusercontent.com/u/3163309?u=0c6f4091b0eda05c44c390466199826e6dc6e431&v=4 - url: https://github.com/Shark009 - - login: dblackrun - avatarUrl: https://avatars.githubusercontent.com/u/3528486?v=4 - url: https://github.com/dblackrun + - login: mintuhouse + avatarUrl: https://avatars.githubusercontent.com/u/769950?u=ecfbd79a97d33177e0d093ddb088283cf7fe8444&v=4 + url: https://github.com/mintuhouse + - login: simw + avatarUrl: https://avatars.githubusercontent.com/u/6322526?v=4 + url: https://github.com/simw + - login: Rehket + avatarUrl: https://avatars.githubusercontent.com/u/7015688?u=3afb0ba200feebbc7f958950e92db34df2a3c172&v=4 + url: https://github.com/Rehket + - login: hiancdtrsnm + avatarUrl: https://avatars.githubusercontent.com/u/7343177?v=4 + url: https://github.com/hiancdtrsnm + - login: TrevorBenson + avatarUrl: https://avatars.githubusercontent.com/u/9167887?u=afdd1766fdb79e04e59094cc6a54cd011ee7f686&v=4 + url: https://github.com/TrevorBenson + - login: wdwinslow + avatarUrl: https://avatars.githubusercontent.com/u/11562137?u=dc01daafb354135603a263729e3d26d939c0c452&v=4 + url: https://github.com/wdwinslow + - login: drcat101 + avatarUrl: https://avatars.githubusercontent.com/u/11951946?u=e714b957185b8cf3d301cced7fc3ad2842122c6a&v=4 + url: https://github.com/drcat101 - login: zsinx6 avatarUrl: https://avatars.githubusercontent.com/u/3532625?u=ba75a5dc744d1116ccfeaaf30d41cb2fe81fe8dd&v=4 url: https://github.com/zsinx6 + - login: kennywakeland + avatarUrl: https://avatars.githubusercontent.com/u/3631417?u=7c8f743f1ae325dfadea7c62bbf1abd6a824fc55&v=4 + url: https://github.com/kennywakeland - login: aacayaco avatarUrl: https://avatars.githubusercontent.com/u/3634801?u=eaadda178c964178fcb64886f6c732172c8f8219&v=4 url: https://github.com/aacayaco @@ -150,7 +264,7 @@ sponsors: avatarUrl: https://avatars.githubusercontent.com/u/3654837?v=4 url: https://github.com/anomaly - login: jgreys - avatarUrl: https://avatars.githubusercontent.com/u/4136890?u=c66ae617d614f6c886f1f1c1799d22100b3c848d&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/4136890?u=096820d1ef89877d57d0f68e669ead8b0fde84df&v=4 url: https://github.com/jgreys - login: jaredtrog avatarUrl: https://avatars.githubusercontent.com/u/4381365?v=4 @@ -170,126 +284,132 @@ sponsors: - login: Yaleesa avatarUrl: https://avatars.githubusercontent.com/u/6135475?v=4 url: https://github.com/Yaleesa - - login: iwpnd - avatarUrl: https://avatars.githubusercontent.com/u/6152183?u=c485eefca5c6329600cae63dd35e4f5682ce6924&v=4 - url: https://github.com/iwpnd - - login: simw - avatarUrl: https://avatars.githubusercontent.com/u/6322526?v=4 - url: https://github.com/simw - - login: Rehket - avatarUrl: https://avatars.githubusercontent.com/u/7015688?u=3afb0ba200feebbc7f958950e92db34df2a3c172&v=4 - url: https://github.com/Rehket - - login: hiancdtrsnm - avatarUrl: https://avatars.githubusercontent.com/u/7343177?v=4 - url: https://github.com/hiancdtrsnm - - login: Shackelford-Arden - avatarUrl: https://avatars.githubusercontent.com/u/7362263?v=4 - url: https://github.com/Shackelford-Arden - - login: savannahostrowski - avatarUrl: https://avatars.githubusercontent.com/u/8949415?u=c3177aa099fb2b8c36aeba349278b77f9a8df211&v=4 - url: https://github.com/savannahostrowski - - login: wdwinslow - avatarUrl: https://avatars.githubusercontent.com/u/11562137?u=dc01daafb354135603a263729e3d26d939c0c452&v=4 - url: https://github.com/wdwinslow - - login: dannywade - avatarUrl: https://avatars.githubusercontent.com/u/13680237?u=418ee985bd41577b20fde81417fb2d901e875e8a&v=4 - url: https://github.com/dannywade - - login: khadrawy - avatarUrl: https://avatars.githubusercontent.com/u/13686061?u=59f25ef42ecf04c22657aac4238ce0e2d3d30304&v=4 - url: https://github.com/khadrawy - - login: mjohnsey - avatarUrl: https://avatars.githubusercontent.com/u/16784016?u=38fad2e6b411244560b3af99c5f5a4751bc81865&v=4 - url: https://github.com/mjohnsey - - login: wedwardbeck - avatarUrl: https://avatars.githubusercontent.com/u/19333237?u=1de4ae2bf8d59eb4c013f21d863cbe0f2010575f&v=4 - url: https://github.com/wedwardbeck - - login: RaamEEIL - avatarUrl: https://avatars.githubusercontent.com/u/20320552?v=4 - url: https://github.com/RaamEEIL - - login: Filimoa - avatarUrl: https://avatars.githubusercontent.com/u/21352040?u=0be845711495bbd7b756e13fcaeb8efc1ebd78ba&v=4 - url: https://github.com/Filimoa + - login: FernandoCelmer + avatarUrl: https://avatars.githubusercontent.com/u/6262214?u=d29fff3fd862fda4ca752079f13f32e84c762ea4&v=4 + url: https://github.com/FernandoCelmer +- - login: getsentry + avatarUrl: https://avatars.githubusercontent.com/u/1396951?v=4 + url: https://github.com/getsentry +- - login: pawamoy + avatarUrl: https://avatars.githubusercontent.com/u/3999221?u=b030e4c89df2f3a36bc4710b925bdeb6745c9856&v=4 + url: https://github.com/pawamoy + - 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 + - login: rlnchow + avatarUrl: https://avatars.githubusercontent.com/u/28018479?u=a93ca9cf1422b9ece155784a72d5f2fdbce7adff&v=4 + url: https://github.com/rlnchow + - login: HosamAlmoghraby + avatarUrl: https://avatars.githubusercontent.com/u/32025281?u=aa1b09feabccbf9dc506b81c71155f32d126cefa&v=4 + url: https://github.com/HosamAlmoghraby + - login: dvlpjrs + avatarUrl: https://avatars.githubusercontent.com/u/32254642?u=fbd6ad0324d4f1eb6231cf775be1c7bd4404e961&v=4 + url: https://github.com/dvlpjrs + - login: engineerjoe440 + 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=fa1dc8db3e920cf5c5636b97180a6f811fa01aaf&v=4 + url: https://github.com/bnkc + - login: curegit + avatarUrl: https://avatars.githubusercontent.com/u/37978051?u=1733c322079118c0cdc573c03d92813f50a9faec&v=4 + url: https://github.com/curegit + - login: JimFawkes + avatarUrl: https://avatars.githubusercontent.com/u/12075115?u=dc58ecfd064d72887c34bf500ddfd52592509acd&v=4 + url: https://github.com/JimFawkes + - login: artempronevskiy + avatarUrl: https://avatars.githubusercontent.com/u/12235104?u=03df6e1e55c9c6fe5d230adabb8dd7d43d8bbe8f&v=4 + url: https://github.com/artempronevskiy + - login: TheR1D + avatarUrl: https://avatars.githubusercontent.com/u/16740832?u=b0dfdbdb27b79729430c71c6128962f77b7b53f7&v=4 + url: https://github.com/TheR1D + - login: joshuatz + avatarUrl: https://avatars.githubusercontent.com/u/17817563?u=f1bf05b690d1fc164218f0b420cdd3acb7913e21&v=4 + url: https://github.com/joshuatz + - login: jangia + avatarUrl: https://avatars.githubusercontent.com/u/17927101?u=9261b9bb0c3e3bb1ecba43e8915dc58d8c9a077e&v=4 + url: https://github.com/jangia - login: shuheng-liu avatarUrl: https://avatars.githubusercontent.com/u/22414322?u=813c45f30786c6b511b21a661def025d8f7b609e&v=4 url: https://github.com/shuheng-liu + - login: pers0n4 + 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: LarryGF - avatarUrl: https://avatars.githubusercontent.com/u/26148349?u=431bb34d36d41c172466252242175281ae132152&v=4 - url: https://github.com/LarryGF - - login: BrettskiPy - avatarUrl: https://avatars.githubusercontent.com/u/30988215?u=d8a94a67e140d5ee5427724b292cc52d8827087a&v=4 - url: https://github.com/BrettskiPy - - login: mauroalejandrojm - avatarUrl: https://avatars.githubusercontent.com/u/31569442?u=cdada990a1527926a36e95f62c30a8b48bbc49a1&v=4 - url: https://github.com/mauroalejandrojm - - login: Leay15 - avatarUrl: https://avatars.githubusercontent.com/u/32212558?u=c4aa9c1737e515959382a5515381757b1fd86c53&v=4 - url: https://github.com/Leay15 - - login: ygorpontelo - avatarUrl: https://avatars.githubusercontent.com/u/32963605?u=35f7103f9c4c4c2589ae5737ee882e9375ef072e&v=4 - url: https://github.com/ygorpontelo - - login: AlrasheedA - avatarUrl: https://avatars.githubusercontent.com/u/33544979?u=7fe66bf62b47682612b222e3e8f4795ef3be769b&v=4 - url: https://github.com/AlrasheedA - - login: ProteinQure - avatarUrl: https://avatars.githubusercontent.com/u/33707203?v=4 - url: https://github.com/ProteinQure - - 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: thenickben - avatarUrl: https://avatars.githubusercontent.com/u/40610922?u=1e907d904041b7c91213951a3cb344cd37c14aaf&v=4 - url: https://github.com/thenickben - - login: ybressler - avatarUrl: https://avatars.githubusercontent.com/u/40807730?u=41e2c00f1eebe3c402635f0325e41b4e6511462c&v=4 - url: https://github.com/ybressler - - login: ddilidili - avatarUrl: https://avatars.githubusercontent.com/u/42176885?u=c0a849dde06987434653197b5f638d3deb55fc6c&v=4 - url: https://github.com/ddilidili - - login: dudikbender - avatarUrl: https://avatars.githubusercontent.com/u/53487583?u=3a57542938ebfd57579a0111db2b297e606d9681&v=4 - url: https://github.com/dudikbender - - login: thisistheplace - avatarUrl: https://avatars.githubusercontent.com/u/57633545?u=a3f3a7f8ace8511c6c067753f6eb6aee0db11ac6&v=4 - url: https://github.com/thisistheplace - - 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 - - login: patsatsia - avatarUrl: https://avatars.githubusercontent.com/u/61111267?u=3271b85f7a37b479c8d0ae0a235182e83c166edf&v=4 - url: https://github.com/patsatsia - - 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: DelfinaCare - avatarUrl: https://avatars.githubusercontent.com/u/83734439?v=4 - url: https://github.com/DelfinaCare - - 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: Yarden-zamir - avatarUrl: https://avatars.githubusercontent.com/u/8178413?u=ee177a8b0f87ea56747f4d96f34cd4e9604a8217&v=4 - url: https://github.com/Yarden-zamir -- - login: pawamoy - avatarUrl: https://avatars.githubusercontent.com/u/3999221?u=b030e4c89df2f3a36bc4710b925bdeb6745c9856&v=4 - url: https://github.com/pawamoy + - login: nisutec + avatarUrl: https://avatars.githubusercontent.com/u/25281462?u=e562484c451fdfc59053163f64405f8eb262b8b0&v=4 + url: https://github.com/nisutec + - login: 0417taehyun + avatarUrl: https://avatars.githubusercontent.com/u/63915557?u=47debaa860fd52c9b98c97ef357ddcec3b3fb399&v=4 + url: https://github.com/0417taehyun + - login: fernandosmither + avatarUrl: https://avatars.githubusercontent.com/u/66154723?u=a76a037b5d674938a75d2cff862fb6dfd63ec214&v=4 + url: https://github.com/fernandosmither + - login: romabozhanovgithub + avatarUrl: https://avatars.githubusercontent.com/u/67696229?u=e4b921eef096415300425aca249348f8abb78ad7&v=4 + url: https://github.com/romabozhanovgithub + - login: PelicanQ + avatarUrl: https://avatars.githubusercontent.com/u/77930606?v=4 + url: https://github.com/PelicanQ + - login: tim-habitat + avatarUrl: https://avatars.githubusercontent.com/u/86600518?u=7389dd77fe6a0eb8d13933356120b7d2b32d7bb4&v=4 + url: https://github.com/tim-habitat + - login: jugeeem + avatarUrl: https://avatars.githubusercontent.com/u/116043716?u=ae590d79c38ac79c91b9c5caa6887d061e865a3d&v=4 + url: https://github.com/jugeeem + - login: tahmarrrr23 + avatarUrl: https://avatars.githubusercontent.com/u/138208610?u=465a46b0ff72a74252d3e3a71ac7d2f1919cda28&v=4 + url: https://github.com/tahmarrrr23 + - login: lukzmu + avatarUrl: https://avatars.githubusercontent.com/u/155924127?u=2e52e40b3134bef370b52bf2e40a524f307c2a05&v=4 + url: https://github.com/lukzmu + - login: kristiangronberg + avatarUrl: https://avatars.githubusercontent.com/u/42678548?v=4 + url: https://github.com/kristiangronberg + - login: leonardo-holguin + avatarUrl: https://avatars.githubusercontent.com/u/43093055?u=b59013d52fb6c4e0954aaaabc0882bd844985b38&v=4 + url: https://github.com/leonardo-holguin + - login: arrrrrmin + avatarUrl: https://avatars.githubusercontent.com/u/43553423?u=36a3880a6eb29309c19e6cadbb173bafbe91deb1&v=4 + url: https://github.com/arrrrrmin + - login: rbtrsv + avatarUrl: https://avatars.githubusercontent.com/u/43938206?u=09955f324da271485a7edaf9241f449e88a1388a&v=4 + url: https://github.com/rbtrsv + - login: mobyw + avatarUrl: https://avatars.githubusercontent.com/u/44370805?v=4 + url: https://github.com/mobyw + - login: ArtyomVancyan + avatarUrl: https://avatars.githubusercontent.com/u/44609997?v=4 + url: https://github.com/ArtyomVancyan + - login: hgalytoby + avatarUrl: https://avatars.githubusercontent.com/u/50397689?u=f4888c2c54929bd86eed0d3971d09fcb306e5088&v=4 + url: https://github.com/hgalytoby + - login: conservative-dude + avatarUrl: https://avatars.githubusercontent.com/u/55538308?u=f250c44942ea6e73a6bd90739b381c470c192c11&v=4 + url: https://github.com/conservative-dude + - login: miguelgr + avatarUrl: https://avatars.githubusercontent.com/u/1484589?u=54556072b8136efa12ae3b6902032ea2a39ace4b&v=4 + url: https://github.com/miguelgr + - 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: leobiscassi + avatarUrl: https://avatars.githubusercontent.com/u/1977418?u=f9f82445a847ab479bd7223debd677fcac6c49a0&v=4 + url: https://github.com/leobiscassi + - login: cbonoz + avatarUrl: https://avatars.githubusercontent.com/u/2351087?u=fd3e8030b2cc9fbfbb54a65e9890c548a016f58b&v=4 + url: https://github.com/cbonoz + - login: anthonycorletti + avatarUrl: https://avatars.githubusercontent.com/u/3477132?u=dfe51d2080fbd3fee81e05911cd8d50da9dcc709&v=4 + url: https://github.com/anthonycorletti - login: ddanier avatarUrl: https://avatars.githubusercontent.com/u/113563?u=ed1dc79de72f93bd78581f88ebc6952b62f472da&v=4 url: https://github.com/ddanier @@ -311,77 +431,29 @@ sponsors: - login: securancy avatarUrl: https://avatars.githubusercontent.com/u/606673?v=4 url: https://github.com/securancy - - login: hardbyte - avatarUrl: https://avatars.githubusercontent.com/u/855189?u=aa29e92f34708814d6b67fcd47ca4cf2ce1c04ed&v=4 - url: https://github.com/hardbyte + - login: tochikuji + avatarUrl: https://avatars.githubusercontent.com/u/851759?v=4 + url: https://github.com/tochikuji - login: browniebroke avatarUrl: https://avatars.githubusercontent.com/u/861044?u=5abfca5588f3e906b31583d7ee62f6de4b68aa24&v=4 url: https://github.com/browniebroke - - login: janfilips - avatarUrl: https://avatars.githubusercontent.com/u/870699?u=96df18ad355e58b9397accc55f4eeb7a86e959b0&v=4 - url: https://github.com/janfilips - - 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: Patechoc - avatarUrl: https://avatars.githubusercontent.com/u/2376641?u=23b49e9eda04f078cb74fa3f93593aa6a57bb138&v=4 - url: https://github.com/Patechoc - - 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: nikeee - avatarUrl: https://avatars.githubusercontent.com/u/4068864?u=bbe73151f2b409c120160d032dc9aa6875ef0c4b&v=4 - url: https://github.com/nikeee - - login: Alisa-lisa - avatarUrl: https://avatars.githubusercontent.com/u/4137964?u=e7e393504f554f4ff15863a1e01a5746863ef9ce&v=4 - url: https://github.com/Alisa-lisa - - login: danielunderwood - avatarUrl: https://avatars.githubusercontent.com/u/4472301?v=4 - url: https://github.com/danielunderwood - - login: yuawn - avatarUrl: https://avatars.githubusercontent.com/u/5111198?u=5315576f3fe1a70fd2d0f02181588f4eea5d353d&v=4 - url: https://github.com/yuawn - - login: sdevkota - avatarUrl: https://avatars.githubusercontent.com/u/5250987?u=4ed9a120c89805a8aefda1cbdc0cf6512e64d1b4&v=4 - url: https://github.com/sdevkota - - login: unredundant - avatarUrl: https://avatars.githubusercontent.com/u/5607577?u=1ffbf39f5bb8736b75c0d235707d6e8f803725c5&v=4 - url: https://github.com/unredundant - - 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: katnoria avatarUrl: https://avatars.githubusercontent.com/u/7674948?u=09767eb13e07e09496c5fee4e5ce21d9eac34a56&v=4 url: https://github.com/katnoria - - login: mattwelke - avatarUrl: https://avatars.githubusercontent.com/u/7719209?u=80f02a799323b1472b389b836d95957c93a6d856&v=4 - url: https://github.com/mattwelke + - login: harsh183 + avatarUrl: https://avatars.githubusercontent.com/u/7780198?v=4 + url: https://github.com/harsh183 - login: hcristea avatarUrl: https://avatars.githubusercontent.com/u/7814406?u=61d7a4fcf846983a4606788eac25e1c6c1209ba8&v=4 url: https://github.com/hcristea - login: moonape1226 avatarUrl: https://avatars.githubusercontent.com/u/8532038?u=d9f8b855a429fff9397c3833c2ff83849ebf989d&v=4 url: https://github.com/moonape1226 - - login: albertkun - avatarUrl: https://avatars.githubusercontent.com/u/8574425?u=aad2a9674273c9275fe414d99269b7418d144089&v=4 - url: https://github.com/albertkun - login: xncbf - avatarUrl: https://avatars.githubusercontent.com/u/9462045?u=866a1311e4bd3ec5ae84185c4fcc99f397c883d7&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/9462045?u=ee91e210ae93b9cdd8f248b21cb028316cc0b747&v=4 url: https://github.com/xncbf - login: DMantis avatarUrl: https://avatars.githubusercontent.com/u/9536869?v=4 @@ -401,96 +473,45 @@ sponsors: - login: pheanex avatarUrl: https://avatars.githubusercontent.com/u/10408624?u=5b6bab6ee174aa6e991333e06eb29f628741013d&v=4 url: https://github.com/pheanex - - login: JimFawkes - avatarUrl: https://avatars.githubusercontent.com/u/12075115?u=dc58ecfd064d72887c34bf500ddfd52592509acd&v=4 - url: https://github.com/JimFawkes - - login: giuliano-oliveira - avatarUrl: https://avatars.githubusercontent.com/u/13181797?u=0ef2dfbf7fc9a9726d45c21d32b5d1038a174870&v=4 - url: https://github.com/giuliano-oliveira - - login: TheR1D - avatarUrl: https://avatars.githubusercontent.com/u/16740832?u=b0dfdbdb27b79729430c71c6128962f77b7b53f7&v=4 - url: https://github.com/TheR1D - - login: jangia - avatarUrl: https://avatars.githubusercontent.com/u/17927101?u=9261b9bb0c3e3bb1ecba43e8915dc58d8c9a077e&v=4 - url: https://github.com/jangia - - login: ghandic - avatarUrl: https://avatars.githubusercontent.com/u/23500353?u=e2e1d736f924d9be81e8bfc565b6d8836ba99773&v=4 - url: https://github.com/ghandic - - login: pers0n4 - avatarUrl: https://avatars.githubusercontent.com/u/24864600?u=f211a13a7b572cbbd7779b9c8d8cb428cc7ba07e&v=4 - url: https://github.com/pers0n4 - - login: kadekillary - avatarUrl: https://avatars.githubusercontent.com/u/25046261?u=e185e58080090f9e678192cd214a14b14a2b232b&v=4 - url: https://github.com/kadekillary - - 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 - - login: rlnchow - avatarUrl: https://avatars.githubusercontent.com/u/28018479?u=a93ca9cf1422b9ece155784a72d5f2fdbce7adff&v=4 - url: https://github.com/rlnchow - - login: mertguvencli - avatarUrl: https://avatars.githubusercontent.com/u/29762151?u=16a906d90df96c8cff9ea131a575c4bc171b1523&v=4 - url: https://github.com/mertguvencli - - login: HosamAlmoghraby - avatarUrl: https://avatars.githubusercontent.com/u/32025281?u=aa1b09feabccbf9dc506b81c71155f32d126cefa&v=4 - url: https://github.com/HosamAlmoghraby - - login: engineerjoe440 - 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=9fbf76b9bf7786275e2900efa51d1394bcf1f06a&v=4 - url: https://github.com/bnkc - - login: declon - avatarUrl: https://avatars.githubusercontent.com/u/36180226?v=4 - url: https://github.com/declon - - login: miraedbswo - avatarUrl: https://avatars.githubusercontent.com/u/36796047?u=9e7a5b3e558edc61d35d0f9dfac37541bae7f56d&v=4 - url: https://github.com/miraedbswo - - login: kristiangronberg - avatarUrl: https://avatars.githubusercontent.com/u/42678548?v=4 - url: https://github.com/kristiangronberg - - login: arrrrrmin - avatarUrl: https://avatars.githubusercontent.com/u/43553423?u=36a3880a6eb29309c19e6cadbb173bafbe91deb1&v=4 - url: https://github.com/arrrrrmin - - login: ArtyomVancyan - avatarUrl: https://avatars.githubusercontent.com/u/44609997?v=4 - url: https://github.com/ArtyomVancyan - - login: hgalytoby - avatarUrl: https://avatars.githubusercontent.com/u/50397689?u=f4888c2c54929bd86eed0d3971d09fcb306e5088&v=4 - url: https://github.com/hgalytoby - - login: eladgunders - avatarUrl: https://avatars.githubusercontent.com/u/52347338?u=83d454817cf991a035c8827d46ade050c813e2d6&v=4 - url: https://github.com/eladgunders - - login: conservative-dude - avatarUrl: https://avatars.githubusercontent.com/u/55538308?u=f250c44942ea6e73a6bd90739b381c470c192c11&v=4 - url: https://github.com/conservative-dude - - login: leo-jp-edwards - avatarUrl: https://avatars.githubusercontent.com/u/58213433?u=2c128e8b0794b7a66211cd7d8ebe05db20b7e9c0&v=4 - url: https://github.com/leo-jp-edwards - - login: tamtam-fitness - avatarUrl: https://avatars.githubusercontent.com/u/62091034?u=8da19a6bd3d02f5d6ba30c7247d5b46c98dd1403&v=4 - url: https://github.com/tamtam-fitness - - login: 0417taehyun - avatarUrl: https://avatars.githubusercontent.com/u/63915557?u=47debaa860fd52c9b98c97ef357ddcec3b3fb399&v=4 - url: https://github.com/0417taehyun -- - login: ssbarnea - avatarUrl: https://avatars.githubusercontent.com/u/102495?u=b4bf6818deefe59952ac22fec6ed8c76de1b8f7c&v=4 - url: https://github.com/ssbarnea + - login: dzoladz + avatarUrl: https://avatars.githubusercontent.com/u/10561752?u=5ee314d54aa79592c18566827ad8914debd5630d&v=4 + url: https://github.com/dzoladz + - login: Alisa-lisa + avatarUrl: https://avatars.githubusercontent.com/u/4137964?u=e7e393504f554f4ff15863a1e01a5746863ef9ce&v=4 + url: https://github.com/Alisa-lisa + - login: danielunderwood + avatarUrl: https://avatars.githubusercontent.com/u/4472301?v=4 + url: https://github.com/danielunderwood + - login: rangulvers + avatarUrl: https://avatars.githubusercontent.com/u/5235430?v=4 + url: https://github.com/rangulvers + - login: sdevkota + avatarUrl: https://avatars.githubusercontent.com/u/5250987?u=4ed9a120c89805a8aefda1cbdc0cf6512e64d1b4&v=4 + url: https://github.com/sdevkota + - login: brizzbuzz + avatarUrl: https://avatars.githubusercontent.com/u/5607577?u=1ffbf39f5bb8736b75c0d235707d6e8f803725c5&v=4 + url: https://github.com/brizzbuzz + - login: Baghdady92 + avatarUrl: https://avatars.githubusercontent.com/u/5708590?v=4 + url: https://github.com/Baghdady92 + - login: jakeecolution + avatarUrl: https://avatars.githubusercontent.com/u/5884696?u=4a7c7883fb064b593b50cb6697b54687e6f7aafe&v=4 + url: https://github.com/jakeecolution +- - login: danburonline + avatarUrl: https://avatars.githubusercontent.com/u/34251194?u=94935cccfbec58083ab1e535212d54f1bf2c978a&v=4 + url: https://github.com/danburonline - login: sadikkuzu avatarUrl: https://avatars.githubusercontent.com/u/23168063?u=d179c06bb9f65c4167fcab118526819f8e0dac17&v=4 url: https://github.com/sadikkuzu - - login: ruizdiazever - avatarUrl: https://avatars.githubusercontent.com/u/29817086?u=2df54af55663d246e3a4dc8273711c37f1adb117&v=4 - url: https://github.com/ruizdiazever - - login: danburonline - avatarUrl: https://avatars.githubusercontent.com/u/34251194?u=2cad4388c1544e539ecb732d656e42fb07b4ff2d&v=4 - url: https://github.com/danburonline - login: rwxd avatarUrl: https://avatars.githubusercontent.com/u/40308458?u=cd04a39e3655923be4f25c2ba8a5a07b3da3230a&v=4 url: https://github.com/rwxd - - login: xNykram - avatarUrl: https://avatars.githubusercontent.com/u/55030025?u=2c1ba313fd79d29273b5ff7c9c5cf4edfb271b29&v=4 - url: https://github.com/xNykram + - login: Patechoc + avatarUrl: https://avatars.githubusercontent.com/u/2376641?u=23b49e9eda04f078cb74fa3f93593aa6a57bb138&v=4 + url: https://github.com/Patechoc + - login: ssbarnea + avatarUrl: https://avatars.githubusercontent.com/u/102495?u=c2efbf6fea2737e21dfc6b1113c4edc9644e9eaa&v=4 + url: https://github.com/ssbarnea + - login: yuawn + avatarUrl: https://avatars.githubusercontent.com/u/5111198?u=5315576f3fe1a70fd2d0f02181588f4eea5d353d&v=4 + url: https://github.com/yuawn diff --git a/docs/en/data/people.yml b/docs/en/data/people.yml index 2da1c968b2683..710c650fdcc37 100644 --- a/docs/en/data/people.yml +++ b/docs/en/data/people.yml @@ -1,18 +1,22 @@ maintainers: - login: tiangolo - answers: 1839 - prs: 398 + answers: 1878 + prs: 550 avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=740f11212a731f56798f558ceddb0bd07642afa7&v=4 url: https://github.com/tiangolo experts: - login: Kludex - count: 410 + count: 596 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex - login: dmontagu - count: 237 - avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=58ed2a45798a4339700e2f62b2e12e6e54bf0396&v=4 + count: 241 + avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=540f30c937a6450812628b9592a1dfe91bbe148e&v=4 url: https://github.com/dmontagu +- login: jgould22 + count: 232 + avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 + url: https://github.com/jgould22 - login: Mause count: 220 avatarUrl: https://avatars.githubusercontent.com/u/1405026?v=4 @@ -26,21 +30,17 @@ experts: avatarUrl: https://avatars.githubusercontent.com/u/13659033?u=e8bea32d07a5ef72f7dde3b2079ceb714923ca05&v=4 url: https://github.com/JarroVGIT - login: euri10 - count: 152 + count: 153 avatarUrl: https://avatars.githubusercontent.com/u/1104190?u=321a2e953e6645a7d09b732786c7a8061e0f8a8b&v=4 url: https://github.com/euri10 +- login: iudeen + count: 128 + avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 + url: https://github.com/iudeen - login: phy25 count: 126 avatarUrl: https://avatars.githubusercontent.com/u/331403?v=4 url: https://github.com/phy25 -- login: jgould22 - count: 124 - avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 - url: https://github.com/jgould22 -- login: iudeen - count: 118 - avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 - url: https://github.com/iudeen - login: raphaelauv count: 83 avatarUrl: https://avatars.githubusercontent.com/u/10202690?u=e6f86f5c0c3026a15d6b51792fa3e532b12f1371&v=4 @@ -54,23 +54,27 @@ experts: avatarUrl: https://avatars.githubusercontent.com/u/31127044?u=b0f2c37142f4b762e41ad65dc49581813422bd71&v=4 url: https://github.com/ArcLightSlavik - login: falkben - count: 57 + count: 59 avatarUrl: https://avatars.githubusercontent.com/u/653031?u=ad9838e089058c9e5a0bab94c0eec7cc181e0cd0&v=4 url: https://github.com/falkben +- login: JavierSanchezCastro + count: 52 + avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 + url: https://github.com/JavierSanchezCastro +- login: n8sty + count: 52 + avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 + url: https://github.com/n8sty - login: sm-Fifteen count: 49 avatarUrl: https://avatars.githubusercontent.com/u/516999?u=437c0c5038558c67e887ccd863c1ba0f846c03da&v=4 url: https://github.com/sm-Fifteen - login: yinziyan1206 - count: 45 + count: 48 avatarUrl: https://avatars.githubusercontent.com/u/37829370?u=da44ca53aefd5c23f346fab8e9fd2e108294c179&v=4 url: https://github.com/yinziyan1206 -- login: insomnes - count: 45 - avatarUrl: https://avatars.githubusercontent.com/u/16958893?u=f8be7088d5076d963984a21f95f44e559192d912&v=4 - url: https://github.com/insomnes - login: acidjunk - count: 45 + count: 47 avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 url: https://github.com/acidjunk - login: Dustyposa @@ -78,21 +82,29 @@ experts: avatarUrl: https://avatars.githubusercontent.com/u/27180793?u=5cf2877f50b3eb2bc55086089a78a36f07042889&v=4 url: https://github.com/Dustyposa - login: adriangb - count: 43 - avatarUrl: https://avatars.githubusercontent.com/u/1755071?u=1e2c2c9b39f5c9b780fb933d8995cf08ec235a47&v=4 + count: 45 + avatarUrl: https://avatars.githubusercontent.com/u/1755071?u=612704256e38d6ac9cbed24f10e4b6ac2da74ecb&v=4 url: https://github.com/adriangb +- 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 + avatarUrl: https://avatars.githubusercontent.com/u/1144727?u=c159fe047727aedecbbeeaa96a1b03ceb9d39add&v=4 url: https://github.com/frankie567 - login: odiseo0 - count: 42 - avatarUrl: https://avatars.githubusercontent.com/u/87550035?u=2da05dab6cc8e1ade557801634760a56e4101796&v=4 + count: 43 + avatarUrl: https://avatars.githubusercontent.com/u/87550035?u=241a71f6b7068738b81af3e57f45ffd723538401&v=4 url: https://github.com/odiseo0 - login: includeamin count: 40 avatarUrl: https://avatars.githubusercontent.com/u/11836741?u=8bd5ef7e62fe6a82055e33c4c0e0a7879ff8cfb6&v=4 url: https://github.com/includeamin +- login: chbndrhnns + count: 38 + avatarUrl: https://avatars.githubusercontent.com/u/7534547?v=4 + url: https://github.com/chbndrhnns - login: STeveShary count: 37 avatarUrl: https://avatars.githubusercontent.com/u/5167622?u=de8f597c81d6336fcebc37b32dfd61a3f877160c&v=4 @@ -101,10 +113,6 @@ experts: count: 35 avatarUrl: https://avatars.githubusercontent.com/u/31960541?u=47f4829c77f4962ab437ffb7995951e41eeebe9b&v=4 url: https://github.com/krishnardt -- login: chbndrhnns - count: 35 - avatarUrl: https://avatars.githubusercontent.com/u/7534547?v=4 - url: https://github.com/chbndrhnns - login: panla count: 32 avatarUrl: https://avatars.githubusercontent.com/u/41326348?u=ba2fda6b30110411ecbf406d187907e2b420ac19&v=4 @@ -121,42 +129,58 @@ experts: count: 25 avatarUrl: https://avatars.githubusercontent.com/u/365303?u=07ca03c5ee811eb0920e633cc3c3db73dbec1aa5&v=4 url: https://github.com/wshayes +- login: YuriiMotov + count: 24 + avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 + url: https://github.com/YuriiMotov +- login: acnebs + count: 23 + avatarUrl: https://avatars.githubusercontent.com/u/9054108?v=4 + url: https://github.com/acnebs - login: SirTelemak count: 23 avatarUrl: https://avatars.githubusercontent.com/u/9435877?u=719327b7d2c4c62212456d771bfa7c6b8dbb9eac&v=4 url: https://github.com/SirTelemak -- login: acnebs +- login: chrisK824 count: 22 - avatarUrl: https://avatars.githubusercontent.com/u/9054108?u=c27e50269f1ef8ea950cc6f0268c8ec5cebbe9c9&v=4 - url: https://github.com/acnebs + avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 + url: https://github.com/chrisK824 +- login: nymous + count: 21 + avatarUrl: https://avatars.githubusercontent.com/u/4216559?u=360a36fb602cded27273cbfc0afc296eece90662&v=4 + url: https://github.com/nymous - login: rafsaf count: 21 - avatarUrl: https://avatars.githubusercontent.com/u/51059348?u=f8f0d6d6e90fac39fa786228158ba7f013c74271&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/51059348?u=5fe59a56e1f2f9ccd8005d71752a8276f133ae1a&v=4 url: https://github.com/rafsaf - login: nsidnev count: 20 avatarUrl: https://avatars.githubusercontent.com/u/22559461?u=a9cc3238217e21dc8796a1a500f01b722adb082c&v=4 url: https://github.com/nsidnev +- login: ebottos94 + count: 20 + avatarUrl: https://avatars.githubusercontent.com/u/100039558?u=e2c672da5a7977fd24d87ce6ab35f8bf5b1ed9fa&v=4 + url: https://github.com/ebottos94 - login: chris-allnutt count: 20 avatarUrl: https://avatars.githubusercontent.com/u/565544?v=4 url: https://github.com/chris-allnutt -- login: zoliknemet - count: 18 - avatarUrl: https://avatars.githubusercontent.com/u/22326718?u=31ba446ac290e23e56eea8e4f0c558aaf0b40779&v=4 - url: https://github.com/zoliknemet +- login: hasansezertasan + count: 19 + avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 + url: https://github.com/hasansezertasan - login: retnikt count: 18 avatarUrl: https://avatars.githubusercontent.com/u/24581770?v=4 url: https://github.com/retnikt +- login: zoliknemet + count: 18 + avatarUrl: https://avatars.githubusercontent.com/u/22326718?u=31ba446ac290e23e56eea8e4f0c558aaf0b40779&v=4 + url: https://github.com/zoliknemet - login: Hultner count: 17 avatarUrl: https://avatars.githubusercontent.com/u/2669034?u=115e53df959309898ad8dc9443fbb35fee71df07&v=4 url: https://github.com/Hultner -- login: n8sty - count: 17 - avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 - url: https://github.com/n8sty - login: harunyasar count: 17 avatarUrl: https://avatars.githubusercontent.com/u/1765494?u=5b1ab7c582db4b4016fa31affe977d10af108ad4&v=4 @@ -173,76 +197,655 @@ experts: count: 16 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: ghost - count: 15 - 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: jorgerpo - count: 15 - avatarUrl: https://avatars.githubusercontent.com/u/12537771?u=7444d20019198e34911082780cc7ad73f2b97cb3&v=4 - url: https://github.com/jorgerpo -- login: ebottos94 - count: 14 - avatarUrl: https://avatars.githubusercontent.com/u/100039558?u=e2c672da5a7977fd24d87ce6ab35f8bf5b1ed9fa&v=4 - url: https://github.com/ebottos94 -- login: hellocoldworld - count: 14 - avatarUrl: https://avatars.githubusercontent.com/u/47581948?u=3d2186796434c507a6cb6de35189ab0ad27c356f&v=4 - url: https://github.com/hellocoldworld -last_month_active: -- login: jgould22 +last_month_experts: +- login: YuriiMotov + count: 24 + avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 + url: https://github.com/YuriiMotov +- login: Kludex + count: 17 + avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 + url: https://github.com/Kludex +- login: JavierSanchezCastro count: 13 + avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 + url: https://github.com/JavierSanchezCastro +- login: jgould22 + count: 11 avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 url: https://github.com/jgould22 +- login: GodMoonGoodman + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/29688727?u=7b251da620d999644c37c1feeb292d033eed7ad6&v=4 + url: https://github.com/GodMoonGoodman +- login: n8sty + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 + url: https://github.com/n8sty +- login: flo-at + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/564288?v=4 + url: https://github.com/flo-at +- login: estebanx64 + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 + url: https://github.com/estebanx64 +- login: ahmedabdou14 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/104530599?u=05365b155a1ff911532e8be316acfad2e0736f98&v=4 + url: https://github.com/ahmedabdou14 +- login: chrisK824 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 + url: https://github.com/chrisK824 +- login: ThirVondukr + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/50728601?u=167c0bd655e52817082e50979a86d2f98f95b1a3&v=4 + url: https://github.com/ThirVondukr +- login: richin13 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/8370058?u=8e37a4cdbc78983a5f4b4847f6d1879fb39c851c&v=4 + url: https://github.com/richin13 +- login: hussein-awala + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/21311487?u=cbbc60943d3fedfb869e49b604020a821f589659&v=4 + url: https://github.com/hussein-awala +- login: admo1 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/14835916?v=4 + url: https://github.com/admo1 +three_months_experts: - login: Kludex - count: 7 + count: 90 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex -- login: abhint +- login: JavierSanchezCastro + count: 28 + avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 + url: https://github.com/JavierSanchezCastro +- login: jgould22 + count: 28 + avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 + url: https://github.com/jgould22 +- login: YuriiMotov + count: 24 + avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 + url: https://github.com/YuriiMotov +- login: n8sty + count: 12 + avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 + url: https://github.com/n8sty +- login: hasansezertasan + count: 12 + avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 + url: https://github.com/hasansezertasan +- login: dolfinus + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/4661021?u=a51b39001a2e5e7529b45826980becf786de2327&v=4 + url: https://github.com/dolfinus +- login: aanchlia + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/2835374?u=3c3ed29aa8b09ccaf8d66def0ce82bc2f7e5aab6&v=4 + url: https://github.com/aanchlia +- login: Ventura94 + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/43103937?u=ccb837005aaf212a449c374618c4339089e2f733&v=4 + url: https://github.com/Ventura94 +- login: shashstormer count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/25699289?u=5b9f9f6192c83ca86a411eafd4be46d9e5828585&v=4 - url: https://github.com/abhint + avatarUrl: https://avatars.githubusercontent.com/u/90090313?v=4 + url: https://github.com/shashstormer +- login: GodMoonGoodman + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/29688727?u=7b251da620d999644c37c1feeb292d033eed7ad6&v=4 + url: https://github.com/GodMoonGoodman +- login: flo-at + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/564288?v=4 + url: https://github.com/flo-at +- login: estebanx64 + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 + url: https://github.com/estebanx64 +- login: ahmedabdou14 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/104530599?u=05365b155a1ff911532e8be316acfad2e0736f98&v=4 + url: https://github.com/ahmedabdou14 +- login: chrisK824 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 + url: https://github.com/chrisK824 +- login: fmelihh + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/99879453?u=f76c4460556e41a59eb624acd0cf6e342d660700&v=4 + url: https://github.com/fmelihh +- login: acidjunk + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 + url: https://github.com/acidjunk +- login: agn-7 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/14202344?u=a1d05998ceaf4d06d1063575a7c4ef6e7ae5890e&v=4 + url: https://github.com/agn-7 +- login: ThirVondukr + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/50728601?u=167c0bd655e52817082e50979a86d2f98f95b1a3&v=4 + url: https://github.com/ThirVondukr +- login: richin13 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/8370058?u=8e37a4cdbc78983a5f4b4847f6d1879fb39c851c&v=4 + url: https://github.com/richin13 +- login: hussein-awala + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/21311487?u=cbbc60943d3fedfb869e49b604020a821f589659&v=4 + url: https://github.com/hussein-awala +- login: JoshYuJump + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/5901894?u=cdbca6296ac4cdcdf6945c112a1ce8d5342839ea&v=4 + url: https://github.com/JoshYuJump +- login: bhumkong + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/13270137?u=1490432e6a0184fbc3d5c8d1b5df553ca92e7e5b&v=4 + url: https://github.com/bhumkong +- login: falkben + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/653031?u=ad9838e089058c9e5a0bab94c0eec7cc181e0cd0&v=4 + url: https://github.com/falkben +- login: mielvds + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/1032980?u=722c96b0a234752df23f04df150ef36441ceb43c&v=4 + url: https://github.com/mielvds +- login: admo1 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/14835916?v=4 + url: https://github.com/admo1 +- login: pbasista + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/1535892?u=e9a8bd5b3b2f95340cfeb4bc97886e9334911669&v=4 + url: https://github.com/pbasista +- login: bogdan-coman-uv + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/92912507?v=4 + url: https://github.com/bogdan-coman-uv +- login: leonidktoto + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/159561986?v=4 + url: https://github.com/leonidktoto +- login: DJoepie + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/78362619?u=fe6e8d05f94d8d4c0679a4da943955a686f96177&v=4 + url: https://github.com/DJoepie +- login: alex-pobeditel-2004 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/14791483?v=4 + url: https://github.com/alex-pobeditel-2004 +- login: binbjz + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/8213913?u=22b68b7a0d5bf5e09c02084c0f5f53d7503114cd&v=4 + url: https://github.com/binbjz +- login: JonnyBootsNpants + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/155071540?u=2d3a72b74a2c4c8eaacdb625c7ac850369579352&v=4 + url: https://github.com/JonnyBootsNpants +- login: TarasKuzyo + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/7178184?v=4 + url: https://github.com/TarasKuzyo +- login: kiraware + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/117554978?v=4 + url: https://github.com/kiraware +- login: iudeen + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 + url: https://github.com/iudeen +- login: msehnout + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/9369632?u=8c988f1b008a3f601385a3616f9327820f66e3a5&v=4 + url: https://github.com/msehnout +- login: rafalkrupinski + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/3732079?u=929e95d40d524301cb481da05208a25ed059400d&v=4 + url: https://github.com/rafalkrupinski +- login: morian + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/1735308?u=8ef15491399b040bd95e2675bb8c8f2462e977b0&v=4 + url: https://github.com/morian +- login: garg10may + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/8787120?u=7028d2b3a2a26534c1806eb76c7425a3fac9732f&v=4 + url: https://github.com/garg10may +- login: taegyunum + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/16094650?v=4 + url: https://github.com/taegyunum +six_months_experts: +- login: Kludex + count: 112 + avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 + url: https://github.com/Kludex +- login: jgould22 + count: 66 + avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 + url: https://github.com/jgould22 +- login: JavierSanchezCastro + count: 32 + avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 + url: https://github.com/JavierSanchezCastro +- login: YuriiMotov + count: 24 + avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 + url: https://github.com/YuriiMotov +- login: n8sty + count: 24 + avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 + url: https://github.com/n8sty +- login: hasansezertasan + count: 19 + avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 + url: https://github.com/hasansezertasan +- login: WilliamStam + count: 9 + avatarUrl: https://avatars.githubusercontent.com/u/182800?v=4 + url: https://github.com/WilliamStam +- login: iudeen + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 + url: https://github.com/iudeen +- login: dolfinus + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/4661021?u=a51b39001a2e5e7529b45826980becf786de2327&v=4 + url: https://github.com/dolfinus +- login: aanchlia + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/2835374?u=3c3ed29aa8b09ccaf8d66def0ce82bc2f7e5aab6&v=4 + url: https://github.com/aanchlia +- login: Ventura94 + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/43103937?u=ccb837005aaf212a449c374618c4339089e2f733&v=4 + url: https://github.com/Ventura94 +- login: nymous + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/4216559?u=360a36fb602cded27273cbfc0afc296eece90662&v=4 + url: https://github.com/nymous +- login: White-Mask + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/31826970?u=8625355dc25ddf9c85a8b2b0b9932826c4c8f44c&v=4 + url: https://github.com/White-Mask - login: chrisK824 + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 + url: https://github.com/chrisK824 +- login: alex-pobeditel-2004 + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/14791483?v=4 + url: https://github.com/alex-pobeditel-2004 +- login: shashstormer + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/90090313?v=4 + url: https://github.com/shashstormer +- login: GodMoonGoodman + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/29688727?u=7b251da620d999644c37c1feeb292d033eed7ad6&v=4 + url: https://github.com/GodMoonGoodman +- login: JoshYuJump + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/5901894?u=cdbca6296ac4cdcdf6945c112a1ce8d5342839ea&v=4 + url: https://github.com/JoshYuJump +- login: flo-at + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/564288?v=4 + url: https://github.com/flo-at +- login: ebottos94 + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/100039558?u=e2c672da5a7977fd24d87ce6ab35f8bf5b1ed9fa&v=4 + url: https://github.com/ebottos94 +- login: estebanx64 + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 + url: https://github.com/estebanx64 +- login: pythonweb2 count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/32141163?v=4 + url: https://github.com/pythonweb2 +- login: ahmedabdou14 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/104530599?u=05365b155a1ff911532e8be316acfad2e0736f98&v=4 + url: https://github.com/ahmedabdou14 +- login: fmelihh + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/99879453?u=f76c4460556e41a59eb624acd0cf6e342d660700&v=4 + url: https://github.com/fmelihh +- login: binbjz + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/8213913?u=22b68b7a0d5bf5e09c02084c0f5f53d7503114cd&v=4 + url: https://github.com/binbjz +- login: theobouwman + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/16098190?u=dc70db88a7a99b764c9a89a6e471e0b7ca478a35&v=4 + url: https://github.com/theobouwman +- login: Ryandaydev + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/4292423?u=48f68868db8886fce31a1d802c1003914c6cd7c6&v=4 + url: https://github.com/Ryandaydev +- login: sriram-kondakindi + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/32274323?v=4 + url: https://github.com/sriram-kondakindi +- login: NeilBotelho + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/39030675?u=16fea2ff90a5c67b974744528a38832a6d1bb4f7&v=4 + url: https://github.com/NeilBotelho +- login: yinziyan1206 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/37829370?u=da44ca53aefd5c23f346fab8e9fd2e108294c179&v=4 + url: https://github.com/yinziyan1206 +- login: pcorvoh + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/48502122?u=89fe3e55f3cfd15d34ffac239b32af358cca6481&v=4 + url: https://github.com/pcorvoh +- login: acidjunk + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 + url: https://github.com/acidjunk +- login: shashiwtt + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/87797476?v=4 + url: https://github.com/shashiwtt +- login: yavuzakyazici + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/148442912?u=1d2d150172c53daf82020b950c6483a6c6a77b7e&v=4 + url: https://github.com/yavuzakyazici +- login: AntonioBarral + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/22151181?u=64416447a37a420e6dfd16e675cf74f66c9f204d&v=4 + url: https://github.com/AntonioBarral +- login: agn-7 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/14202344?u=a1d05998ceaf4d06d1063575a7c4ef6e7ae5890e&v=4 + url: https://github.com/agn-7 +- login: ThirVondukr + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/50728601?u=167c0bd655e52817082e50979a86d2f98f95b1a3&v=4 + url: https://github.com/ThirVondukr +- login: richin13 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/8370058?u=8e37a4cdbc78983a5f4b4847f6d1879fb39c851c&v=4 + url: https://github.com/richin13 +- login: hussein-awala + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/21311487?u=cbbc60943d3fedfb869e49b604020a821f589659&v=4 + url: https://github.com/hussein-awala +- login: jcphlux + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/996689?v=4 + url: https://github.com/jcphlux +- login: Matthieu-LAURENT39 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/91389613?v=4 + url: https://github.com/Matthieu-LAURENT39 +- login: bhumkong + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/13270137?u=1490432e6a0184fbc3d5c8d1b5df553ca92e7e5b&v=4 + url: https://github.com/bhumkong +- login: falkben + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/653031?u=ad9838e089058c9e5a0bab94c0eec7cc181e0cd0&v=4 + url: https://github.com/falkben +- login: mielvds + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/1032980?u=722c96b0a234752df23f04df150ef36441ceb43c&v=4 + url: https://github.com/mielvds +- login: admo1 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/14835916?v=4 + url: https://github.com/admo1 +- login: pbasista + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/1535892?u=e9a8bd5b3b2f95340cfeb4bc97886e9334911669&v=4 + url: https://github.com/pbasista +- login: osangu + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/80697064?u=de9bae685e2228bffd4e202274e1df1afaf54a0d&v=4 + url: https://github.com/osangu +- login: bogdan-coman-uv + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/92912507?v=4 + url: https://github.com/bogdan-coman-uv +- login: leonidktoto + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/159561986?v=4 + url: https://github.com/leonidktoto +one_year_experts: +- login: Kludex + count: 231 + avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 + url: https://github.com/Kludex +- login: jgould22 + count: 132 + avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 + url: https://github.com/jgould22 +- login: JavierSanchezCastro + count: 52 + avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 + url: https://github.com/JavierSanchezCastro +- login: n8sty + count: 39 + avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 + url: https://github.com/n8sty +- login: YuriiMotov + count: 24 + avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 + url: https://github.com/YuriiMotov +- login: chrisK824 + count: 22 avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 url: https://github.com/chrisK824 +- login: hasansezertasan + count: 19 + avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 + url: https://github.com/hasansezertasan +- login: abhint + count: 14 + avatarUrl: https://avatars.githubusercontent.com/u/25699289?u=b5d219277b4d001ac26fb8be357fddd88c29d51b&v=4 + url: https://github.com/abhint +- login: ahmedabdou14 + count: 13 + avatarUrl: https://avatars.githubusercontent.com/u/104530599?u=05365b155a1ff911532e8be316acfad2e0736f98&v=4 + url: https://github.com/ahmedabdou14 +- login: nymous + count: 13 + avatarUrl: https://avatars.githubusercontent.com/u/4216559?u=360a36fb602cded27273cbfc0afc296eece90662&v=4 + url: https://github.com/nymous +- login: iudeen + count: 12 + avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 + url: https://github.com/iudeen +- login: arjwilliams + count: 12 + avatarUrl: https://avatars.githubusercontent.com/u/22227620?v=4 + url: https://github.com/arjwilliams +- login: ebottos94 + count: 10 + avatarUrl: https://avatars.githubusercontent.com/u/100039558?u=e2c672da5a7977fd24d87ce6ab35f8bf5b1ed9fa&v=4 + url: https://github.com/ebottos94 +- login: Viicos + count: 10 + avatarUrl: https://avatars.githubusercontent.com/u/65306057?u=fcd677dc1b9bef12aa103613e5ccb3f8ce305af9&v=4 + url: https://github.com/Viicos +- login: WilliamStam + count: 10 + avatarUrl: https://avatars.githubusercontent.com/u/182800?v=4 + url: https://github.com/WilliamStam +- login: yinziyan1206 + count: 10 + avatarUrl: https://avatars.githubusercontent.com/u/37829370?u=da44ca53aefd5c23f346fab8e9fd2e108294c179&v=4 + url: https://github.com/yinziyan1206 +- login: mateoradman + count: 7 + avatarUrl: https://avatars.githubusercontent.com/u/48420316?u=066f36b8e8e263b0d90798113b0f291d3266db7c&v=4 + url: https://github.com/mateoradman +- login: dolfinus + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/4661021?u=a51b39001a2e5e7529b45826980becf786de2327&v=4 + url: https://github.com/dolfinus +- login: aanchlia + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/2835374?u=3c3ed29aa8b09ccaf8d66def0ce82bc2f7e5aab6&v=4 + url: https://github.com/aanchlia +- login: romabozhanovgithub + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/67696229?u=e4b921eef096415300425aca249348f8abb78ad7&v=4 + url: https://github.com/romabozhanovgithub +- login: Ventura94 + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/43103937?u=ccb837005aaf212a449c374618c4339089e2f733&v=4 + url: https://github.com/Ventura94 +- login: White-Mask + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/31826970?u=8625355dc25ddf9c85a8b2b0b9932826c4c8f44c&v=4 + url: https://github.com/White-Mask +- login: mikeedjones + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/4087139?u=cc4a242896ac2fcf88a53acfaf190d0fe0a1f0c9&v=4 + url: https://github.com/mikeedjones +- login: ThirVondukr + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/50728601?u=167c0bd655e52817082e50979a86d2f98f95b1a3&v=4 + url: https://github.com/ThirVondukr +- login: dmontagu + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=540f30c937a6450812628b9592a1dfe91bbe148e&v=4 + url: https://github.com/dmontagu +- login: alex-pobeditel-2004 + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/14791483?v=4 + url: https://github.com/alex-pobeditel-2004 +- login: shashstormer + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/90090313?v=4 + url: https://github.com/shashstormer +- login: nzig + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/7372858?u=e769add36ed73c778cdb136eb10bf96b1e119671&v=4 + url: https://github.com/nzig +- login: wu-clan + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/52145145?u=f8c9e5c8c259d248e1683fedf5027b4ee08a0967&v=4 + url: https://github.com/wu-clan +- login: adriangb + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/1755071?u=612704256e38d6ac9cbed24f10e4b6ac2da74ecb&v=4 + url: https://github.com/adriangb +- login: 8thgencore + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/30128845?u=a747e840f751a1d196d70d0ecf6d07a530d412a1&v=4 + url: https://github.com/8thgencore +- login: acidjunk + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 + url: https://github.com/acidjunk +- login: GodMoonGoodman + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/29688727?u=7b251da620d999644c37c1feeb292d033eed7ad6&v=4 + url: https://github.com/GodMoonGoodman +- login: JoshYuJump + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/5901894?u=cdbca6296ac4cdcdf6945c112a1ce8d5342839ea&v=4 + url: https://github.com/JoshYuJump +- login: flo-at + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/564288?v=4 + url: https://github.com/flo-at +- login: commonism + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/164513?v=4 + url: https://github.com/commonism +- login: estebanx64 + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 + url: https://github.com/estebanx64 - login: djimontyp count: 4 avatarUrl: https://avatars.githubusercontent.com/u/53098395?u=583bade70950b277c322d35f1be2b75c7b0f189c&v=4 url: https://github.com/djimontyp -- login: JavierSanchezCastro +- login: sanzoghenzo + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/977953?u=d94445b7b87b7096a92a2d4b652ca6c560f34039&v=4 + url: https://github.com/sanzoghenzo +- login: hochstibe + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/48712216?u=1862e0265e06be7ff710f7dc12094250c0616313&v=4 + url: https://github.com/hochstibe +- login: pythonweb2 + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/32141163?v=4 + url: https://github.com/pythonweb2 +- login: nameer + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/3931725?u=6199fb065df098fc13ac0a5e649f89672b586732&v=4 + url: https://github.com/nameer +- login: anthonycepeda + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/72019805?u=60bdf46240cff8fca482ff0fc07d963fd5e1a27c&v=4 + url: https://github.com/anthonycepeda +- login: 9en9i + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/44907258?u=297d0f31ea99c22b718118c1deec82001690cadb&v=4 + url: https://github.com/9en9i +- login: AlexanderPodorov + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/54511144?v=4 + url: https://github.com/AlexanderPodorov +- login: sharonyogev + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/31185192?u=b13ea64b3cdaf3903390c555793aba4aff45c5e6&v=4 + url: https://github.com/sharonyogev +- login: fmelihh count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 - url: https://github.com/JavierSanchezCastro + avatarUrl: https://avatars.githubusercontent.com/u/99879453?u=f76c4460556e41a59eb624acd0cf6e342d660700&v=4 + url: https://github.com/fmelihh +- login: jinluyang + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/15670327?v=4 + url: https://github.com/jinluyang +- login: mht2953658596 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/59814105?v=4 + url: https://github.com/mht2953658596 top_contributors: +- login: nilslindemann + count: 30 + avatarUrl: https://avatars.githubusercontent.com/u/6892179?u=1dca6a22195d6cd1ab20737c0e19a4c55d639472&v=4 + url: https://github.com/nilslindemann +- login: jaystone776 + count: 27 + avatarUrl: https://avatars.githubusercontent.com/u/11191137?u=299205a95e9b6817a43144a48b643346a5aac5cc&v=4 + url: https://github.com/jaystone776 - login: waynerv count: 25 avatarUrl: https://avatars.githubusercontent.com/u/39515546?u=ec35139777597cdbbbddda29bf8b9d4396b429a9&v=4 url: https://github.com/waynerv - login: tokusumi - count: 22 + count: 23 avatarUrl: https://avatars.githubusercontent.com/u/41147016?u=55010621aece725aa702270b54fed829b6a1fe60&v=4 url: https://github.com/tokusumi - login: Kludex - count: 17 + count: 22 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 - url: https://github.com/jaystone776 +- login: SwftAlpc + count: 21 + avatarUrl: https://avatars.githubusercontent.com/u/52768429?u=6a3aa15277406520ad37f6236e89466ed44bc5b8&v=4 + url: https://github.com/SwftAlpc - login: dmontagu - count: 16 - avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=58ed2a45798a4339700e2f62b2e12e6e54bf0396&v=4 + count: 17 + avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=540f30c937a6450812628b9592a1dfe91bbe148e&v=4 url: https://github.com/dmontagu +- login: Xewus + count: 14 + avatarUrl: https://avatars.githubusercontent.com/u/85196001?u=f8e2dc7e5104f109cef944af79050ea8d1b8f914&v=4 + url: https://github.com/Xewus - login: euri10 count: 13 avatarUrl: https://avatars.githubusercontent.com/u/1104190?u=321a2e953e6645a7d09b732786c7a8061e0f8a8b&v=4 @@ -251,14 +854,30 @@ top_contributors: count: 12 avatarUrl: https://avatars.githubusercontent.com/u/11489395?u=4adb6986bf3debfc2b8216ae701f2bd47d73da7d&v=4 url: https://github.com/mariacamilagl -- login: Xewus +- login: hasansezertasan count: 12 - avatarUrl: https://avatars.githubusercontent.com/u/85196001?u=f8e2dc7e5104f109cef944af79050ea8d1b8f914&v=4 - url: https://github.com/Xewus + avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 + url: https://github.com/hasansezertasan - login: Smlep - count: 10 + count: 11 avatarUrl: https://avatars.githubusercontent.com/u/16785985?v=4 url: https://github.com/Smlep +- login: AlertRED + count: 11 + avatarUrl: https://avatars.githubusercontent.com/u/15695000?u=f5a4944c6df443030409c88da7d7fa0b7ead985c&v=4 + url: https://github.com/AlertRED +- login: hard-coders + count: 10 + avatarUrl: https://avatars.githubusercontent.com/u/9651103?u=95db33927bbff1ed1c07efddeb97ac2ff33068ed&v=4 + url: https://github.com/hard-coders +- login: KaniKim + count: 10 + avatarUrl: https://avatars.githubusercontent.com/u/19832624?u=d8ff6fca8542d22f94388cd2c4292e76e3898584&v=4 + url: https://github.com/KaniKim +- login: xzmeng + count: 9 + avatarUrl: https://avatars.githubusercontent.com/u/40202897?v=4 + url: https://github.com/xzmeng - login: Serrones count: 8 avatarUrl: https://avatars.githubusercontent.com/u/22691749?u=4795b880e13ca33a73e52fc0ef7dc9c60c8fce47&v=4 @@ -267,30 +886,38 @@ top_contributors: count: 8 avatarUrl: https://avatars.githubusercontent.com/u/56785022?u=d5c3a02567c8649e146fcfc51b6060ccaf8adef8&v=4 url: https://github.com/rjNemo +- login: pablocm83 + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/28315068?u=3310fbb05bb8bfc50d2c48b6cb64ac9ee4a14549&v=4 + url: https://github.com/pablocm83 - login: RunningIkkyu count: 7 avatarUrl: https://avatars.githubusercontent.com/u/31848542?u=494ecc298e3f26197495bb357ad0f57cfd5f7a32&v=4 url: https://github.com/RunningIkkyu -- login: hard-coders +- login: Alexandrhub count: 7 - avatarUrl: https://avatars.githubusercontent.com/u/9651103?u=95db33927bbff1ed1c07efddeb97ac2ff33068ed&v=4 - url: https://github.com/hard-coders + avatarUrl: https://avatars.githubusercontent.com/u/119126536?u=9fc0d48f3307817bafecc5861eb2168401a6cb04&v=4 + url: https://github.com/Alexandrhub +- login: NinaHwang + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/79563565?u=eee6bfe9224c71193025ab7477f4f96ceaa05c62&v=4 + url: https://github.com/NinaHwang - login: batlopes count: 6 avatarUrl: https://avatars.githubusercontent.com/u/33462923?u=0fb3d7acb316764616f11e4947faf080e49ad8d9&v=4 url: https://github.com/batlopes +- login: alejsdev + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=1ee3a9fbef27abc9448ef5951350f99c7d76f7af&v=4 + url: https://github.com/alejsdev - login: wshayes count: 5 avatarUrl: https://avatars.githubusercontent.com/u/365303?u=07ca03c5ee811eb0920e633cc3c3db73dbec1aa5&v=4 url: https://github.com/wshayes - login: samuelcolvin count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/4039449?u=807390ba9cfe23906c3bf8a0d56aaca3cf2bfa0d&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/4039449?u=42eb3b833047c8c4b4f647a031eaef148c16d93f&v=4 url: https://github.com/samuelcolvin -- login: SwftAlpc - count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/52768429?u=6a3aa15277406520ad37f6236e89466ed44bc5b8&v=4 - url: https://github.com/SwftAlpc - login: Attsun1031 count: 5 avatarUrl: https://avatars.githubusercontent.com/u/1175560?v=4 @@ -299,10 +926,14 @@ top_contributors: count: 5 avatarUrl: https://avatars.githubusercontent.com/u/43503750?u=f440bc9062afb3c43b9b9c6cdfdcfe31d58699ef&v=4 url: https://github.com/ComicShrimp -- login: NinaHwang +- login: rostik1410 count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/79563565?u=eee6bfe9224c71193025ab7477f4f96ceaa05c62&v=4 - url: https://github.com/NinaHwang + avatarUrl: https://avatars.githubusercontent.com/u/11443899?u=e26a635c2ba220467b308a326a579b8ccf4a8701&v=4 + url: https://github.com/rostik1410 +- login: tamtam-fitness + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/62091034?u=8da19a6bd3d02f5d6ba30c7247d5b46c98dd1403&v=4 + url: https://github.com/tamtam-fitness - login: jekirl count: 4 avatarUrl: https://avatars.githubusercontent.com/u/2546697?u=a027452387d85bd4a14834e19d716c99255fb3b7&v=4 @@ -323,31 +954,75 @@ top_contributors: count: 4 avatarUrl: https://avatars.githubusercontent.com/u/3360631?u=5fa1f475ad784d64eb9666bdd43cc4d285dcc773&v=4 url: https://github.com/hitrust +- login: JulianMaurin + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/63545168?u=b7d15ac865268cbefc2d739e2f23d9aeeac1a622&v=4 + url: https://github.com/JulianMaurin - login: lsglucas count: 4 avatarUrl: https://avatars.githubusercontent.com/u/61513630?u=320e43fe4dc7bc6efc64e9b8f325f8075634fd20&v=4 url: https://github.com/lsglucas +- login: BilalAlpaslan + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/47563997?u=63ed66e304fe8d765762c70587d61d9196e5c82d&v=4 + url: https://github.com/BilalAlpaslan +- login: adriangb + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/1755071?u=612704256e38d6ac9cbed24f10e4b6ac2da74ecb&v=4 + url: https://github.com/adriangb +- login: iudeen + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 + url: https://github.com/iudeen - login: axel584 count: 4 avatarUrl: https://avatars.githubusercontent.com/u/1334088?u=9667041f5b15dc002b6f9665fda8c0412933ac04&v=4 url: https://github.com/axel584 +- login: ivan-abc + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/36765187?u=c6e0ba571c1ccb6db9d94e62e4b8b5eda811a870&v=4 + url: https://github.com/ivan-abc +- login: divums + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/1397556?v=4 + url: https://github.com/divums +- login: prostomarkeloff + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/28061158?u=72309cc1f2e04e40fa38b29969cb4e9d3f722e7b&v=4 + url: https://github.com/prostomarkeloff +- login: nsidnev + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/22559461?u=a9cc3238217e21dc8796a1a500f01b722adb082c&v=4 + url: https://github.com/nsidnev +- login: pawamoy + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/3999221?u=b030e4c89df2f3a36bc4710b925bdeb6745c9856&v=4 + url: https://github.com/pawamoy top_reviewers: - login: Kludex - count: 117 + count: 155 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex - login: BilalAlpaslan - count: 75 + count: 86 avatarUrl: https://avatars.githubusercontent.com/u/47563997?u=63ed66e304fe8d765762c70587d61d9196e5c82d&v=4 url: https://github.com/BilalAlpaslan - login: yezz123 - count: 74 + count: 84 avatarUrl: https://avatars.githubusercontent.com/u/52716203?u=d7062cbc6eb7671d5dc9cc0e32a24ae335e0f225&v=4 url: https://github.com/yezz123 +- login: iudeen + count: 55 + avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 + url: https://github.com/iudeen - login: tokusumi count: 51 avatarUrl: https://avatars.githubusercontent.com/u/41147016?u=55010621aece725aa702270b54fed829b6a1fe60&v=4 url: https://github.com/tokusumi +- login: Xewus + count: 50 + avatarUrl: https://avatars.githubusercontent.com/u/85196001?u=f8e2dc7e5104f109cef944af79050ea8d1b8f914&v=4 + url: https://github.com/Xewus - login: waynerv count: 47 avatarUrl: https://avatars.githubusercontent.com/u/39515546?u=ec35139777597cdbbbddda29bf8b9d4396b429a9&v=4 @@ -360,14 +1035,18 @@ 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 url: https://github.com/cikay +- login: hasansezertasan + count: 41 + avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 + url: https://github.com/hasansezertasan +- login: alejsdev + count: 37 + avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=1ee3a9fbef27abc9448ef5951350f99c7d76f7af&v=4 + url: https://github.com/alejsdev - login: JarroVGIT count: 34 avatarUrl: https://avatars.githubusercontent.com/u/13659033?u=e8bea32d07a5ef72f7dde3b2079ceb714923ca05&v=4 @@ -376,49 +1055,53 @@ top_reviewers: count: 33 avatarUrl: https://avatars.githubusercontent.com/u/1024932?u=b2ea249c6b41ddf98679c8d110d0f67d4a3ebf93&v=4 url: https://github.com/AdrianDeAnda -- login: Xewus - count: 32 - avatarUrl: https://avatars.githubusercontent.com/u/85196001?u=f8e2dc7e5104f109cef944af79050ea8d1b8f914&v=4 - url: https://github.com/Xewus - 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 + avatarUrl: https://avatars.githubusercontent.com/u/3127847?u=a08022b191ddbd0a6159b2981d9d878b6d5bb71f&v=4 url: https://github.com/cassiobotaro +- login: lsglucas + count: 27 + avatarUrl: https://avatars.githubusercontent.com/u/61513630?u=320e43fe4dc7bc6efc64e9b8f325f8075634fd20&v=4 + url: https://github.com/lsglucas - login: komtaki count: 27 avatarUrl: https://avatars.githubusercontent.com/u/39375566?u=260ad6b1a4b34c07dbfa728da5e586f16f6d1824&v=4 url: https://github.com/komtaki -- login: lsglucas - count: 26 - avatarUrl: https://avatars.githubusercontent.com/u/61513630?u=320e43fe4dc7bc6efc64e9b8f325f8075634fd20&v=4 - url: https://github.com/lsglucas - login: Ryandaydev - count: 24 - avatarUrl: https://avatars.githubusercontent.com/u/4292423?u=809f3d1074d04bbc28012a7f17f06ea56f5bd71a&v=4 + count: 25 + avatarUrl: https://avatars.githubusercontent.com/u/4292423?u=48f68868db8886fce31a1d802c1003914c6cd7c6&v=4 url: https://github.com/Ryandaydev +- login: LorhanSohaky + count: 24 + avatarUrl: https://avatars.githubusercontent.com/u/16273730?u=095b66f243a2cd6a0aadba9a095009f8aaf18393&v=4 + url: https://github.com/LorhanSohaky - login: dmontagu count: 23 - avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=58ed2a45798a4339700e2f62b2e12e6e54bf0396&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=540f30c937a6450812628b9592a1dfe91bbe148e&v=4 url: https://github.com/dmontagu -- login: LorhanSohaky +- login: nilslindemann count: 23 - avatarUrl: https://avatars.githubusercontent.com/u/16273730?u=095b66f243a2cd6a0aadba9a095009f8aaf18393&v=4 - url: https://github.com/LorhanSohaky + avatarUrl: https://avatars.githubusercontent.com/u/6892179?u=1dca6a22195d6cd1ab20737c0e19a4c55d639472&v=4 + url: https://github.com/nilslindemann +- login: hard-coders + count: 23 + avatarUrl: https://avatars.githubusercontent.com/u/9651103?u=95db33927bbff1ed1c07efddeb97ac2ff33068ed&v=4 + url: https://github.com/hard-coders +- login: YuriiMotov + count: 23 + avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 + url: https://github.com/YuriiMotov - login: rjNemo count: 21 avatarUrl: https://avatars.githubusercontent.com/u/56785022?u=d5c3a02567c8649e146fcfc51b6060ccaf8adef8&v=4 url: https://github.com/rjNemo -- login: hard-coders - count: 21 - avatarUrl: https://avatars.githubusercontent.com/u/9651103?u=95db33927bbff1ed1c07efddeb97ac2ff33068ed&v=4 - url: https://github.com/hard-coders - login: odiseo0 count: 20 - avatarUrl: https://avatars.githubusercontent.com/u/87550035?u=2da05dab6cc8e1ade557801634760a56e4101796&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/87550035?u=241a71f6b7068738b81af3e57f45ffd723538401&v=4 url: https://github.com/odiseo0 - login: 0417taehyun count: 19 @@ -432,6 +1115,10 @@ top_reviewers: count: 17 avatarUrl: https://avatars.githubusercontent.com/u/67154681?u=5d634834cc514028ea3f9115f7030b99a1f4d5a4&v=4 url: https://github.com/zy7y +- login: peidrao + count: 17 + avatarUrl: https://avatars.githubusercontent.com/u/32584628?u=a66902b40c13647d0ed0e573d598128240a4dd04&v=4 + url: https://github.com/peidrao - login: yanever count: 16 avatarUrl: https://avatars.githubusercontent.com/u/21978760?v=4 @@ -440,6 +1127,14 @@ top_reviewers: count: 16 avatarUrl: https://avatars.githubusercontent.com/u/52768429?u=6a3aa15277406520ad37f6236e89466ed44bc5b8&v=4 url: https://github.com/SwftAlpc +- login: axel584 + count: 16 + avatarUrl: https://avatars.githubusercontent.com/u/1334088?u=9667041f5b15dc002b6f9665fda8c0412933ac04&v=4 + url: https://github.com/axel584 +- login: Alexandrhub + count: 16 + avatarUrl: https://avatars.githubusercontent.com/u/119126536?u=9fc0d48f3307817bafecc5861eb2168401a6cb04&v=4 + url: https://github.com/Alexandrhub - login: DevDae count: 16 avatarUrl: https://avatars.githubusercontent.com/u/87962045?u=08e10fa516e844934f4b3fc7c38b33c61697e4a1&v=4 @@ -452,30 +1147,46 @@ top_reviewers: count: 15 avatarUrl: https://avatars.githubusercontent.com/u/63476957?u=6c86e59b48e0394d4db230f37fc9ad4d7e2c27c7&v=4 url: https://github.com/delhi09 +- login: Aruelius + count: 14 + avatarUrl: https://avatars.githubusercontent.com/u/25380989?u=574f8cfcda3ea77a3f81884f6b26a97068e36a9d&v=4 + url: https://github.com/Aruelius - login: sh0nk count: 13 avatarUrl: https://avatars.githubusercontent.com/u/6478810?u=af15d724875cec682ed8088a86d36b2798f981c0&v=4 url: https://github.com/sh0nk -- login: peidrao +- login: wdh99 count: 13 - avatarUrl: https://avatars.githubusercontent.com/u/32584628?u=5b94b548ef0002ef3219d7c07ac0fac17c6201a2&v=4 - url: https://github.com/peidrao + avatarUrl: https://avatars.githubusercontent.com/u/108172295?u=8a8fb95d5afe3e0fa33257b2aecae88d436249eb&v=4 + url: https://github.com/wdh99 - login: r0b2g1t count: 13 avatarUrl: https://avatars.githubusercontent.com/u/5357541?u=6428442d875d5d71aaa1bb38bb11c4be1a526bc2&v=4 url: https://github.com/r0b2g1t +- login: JavierSanchezCastro + count: 13 + avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 + url: https://github.com/JavierSanchezCastro - login: RunningIkkyu count: 12 avatarUrl: https://avatars.githubusercontent.com/u/31848542?u=494ecc298e3f26197495bb357ad0f57cfd5f7a32&v=4 url: https://github.com/RunningIkkyu -- login: axel584 +- login: ivan-abc count: 12 - avatarUrl: https://avatars.githubusercontent.com/u/1334088?u=9667041f5b15dc002b6f9665fda8c0412933ac04&v=4 - url: https://github.com/axel584 + avatarUrl: https://avatars.githubusercontent.com/u/36765187?u=c6e0ba571c1ccb6db9d94e62e4b8b5eda811a870&v=4 + url: https://github.com/ivan-abc +- login: AlertRED + count: 12 + avatarUrl: https://avatars.githubusercontent.com/u/15695000?u=f5a4944c6df443030409c88da7d7fa0b7ead985c&v=4 + url: https://github.com/AlertRED - login: solomein-sv count: 11 avatarUrl: https://avatars.githubusercontent.com/u/46193920?u=789927ee09cfabd752d3bd554fa6baf4850d2777&v=4 url: https://github.com/solomein-sv +- login: dpinezich + count: 11 + avatarUrl: https://avatars.githubusercontent.com/u/3204540?u=a2e1465e3ee10d537614d513589607eddefde09f&v=4 + url: https://github.com/dpinezich - login: mariacamilagl count: 10 avatarUrl: https://avatars.githubusercontent.com/u/11489395?u=4adb6986bf3debfc2b8216ae701f2bd47d73da7d&v=4 @@ -484,47 +1195,200 @@ top_reviewers: count: 10 avatarUrl: https://avatars.githubusercontent.com/u/10202690?u=e6f86f5c0c3026a15d6b51792fa3e532b12f1371&v=4 url: https://github.com/raphaelauv -- login: Attsun1031 - count: 10 - avatarUrl: https://avatars.githubusercontent.com/u/1175560?v=4 - url: https://github.com/Attsun1031 +top_translations_reviewers: +- login: Xewus + count: 128 + avatarUrl: https://avatars.githubusercontent.com/u/85196001?u=f8e2dc7e5104f109cef944af79050ea8d1b8f914&v=4 + url: https://github.com/Xewus +- login: s111d + count: 122 + avatarUrl: https://avatars.githubusercontent.com/u/4954856?v=4 + url: https://github.com/s111d +- login: tokusumi + count: 104 + avatarUrl: https://avatars.githubusercontent.com/u/41147016?u=55010621aece725aa702270b54fed829b6a1fe60&v=4 + url: https://github.com/tokusumi +- login: hasansezertasan + count: 84 + avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 + url: https://github.com/hasansezertasan +- login: AlertRED + count: 70 + avatarUrl: https://avatars.githubusercontent.com/u/15695000?u=f5a4944c6df443030409c88da7d7fa0b7ead985c&v=4 + url: https://github.com/AlertRED +- login: Alexandrhub + count: 68 + avatarUrl: https://avatars.githubusercontent.com/u/119126536?u=9fc0d48f3307817bafecc5861eb2168401a6cb04&v=4 + url: https://github.com/Alexandrhub +- login: waynerv + count: 63 + avatarUrl: https://avatars.githubusercontent.com/u/39515546?u=ec35139777597cdbbbddda29bf8b9d4396b429a9&v=4 + url: https://github.com/waynerv +- login: hard-coders + count: 53 + avatarUrl: https://avatars.githubusercontent.com/u/9651103?u=95db33927bbff1ed1c07efddeb97ac2ff33068ed&v=4 + url: https://github.com/hard-coders +- login: Laineyzhang55 + count: 48 + avatarUrl: https://avatars.githubusercontent.com/u/59285379?v=4 + url: https://github.com/Laineyzhang55 +- login: Kludex + count: 46 + avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 + url: https://github.com/Kludex +- login: komtaki + count: 45 + avatarUrl: https://avatars.githubusercontent.com/u/39375566?u=260ad6b1a4b34c07dbfa728da5e586f16f6d1824&v=4 + url: https://github.com/komtaki +- login: Winand + count: 40 + avatarUrl: https://avatars.githubusercontent.com/u/53390?u=bb0e71a2fc3910a8e0ee66da67c33de40ea695f8&v=4 + url: https://github.com/Winand +- login: solomein-sv + count: 38 + avatarUrl: https://avatars.githubusercontent.com/u/46193920?u=789927ee09cfabd752d3bd554fa6baf4850d2777&v=4 + url: https://github.com/solomein-sv +- login: alperiox + count: 37 + avatarUrl: https://avatars.githubusercontent.com/u/34214152?u=0688c1dc00988150a82d299106062c062ed1ba13&v=4 + url: https://github.com/alperiox +- login: lsglucas + count: 36 + avatarUrl: https://avatars.githubusercontent.com/u/61513630?u=320e43fe4dc7bc6efc64e9b8f325f8075634fd20&v=4 + url: https://github.com/lsglucas +- login: SwftAlpc + count: 36 + avatarUrl: https://avatars.githubusercontent.com/u/52768429?u=6a3aa15277406520ad37f6236e89466ed44bc5b8&v=4 + url: https://github.com/SwftAlpc +- login: nilslindemann + count: 35 + avatarUrl: https://avatars.githubusercontent.com/u/6892179?u=1dca6a22195d6cd1ab20737c0e19a4c55d639472&v=4 + url: https://github.com/nilslindemann +- login: rjNemo + count: 34 + avatarUrl: https://avatars.githubusercontent.com/u/56785022?u=d5c3a02567c8649e146fcfc51b6060ccaf8adef8&v=4 + url: https://github.com/rjNemo +- login: akarev0 + count: 33 + avatarUrl: https://avatars.githubusercontent.com/u/53393089?u=6e528bb4789d56af887ce6fe237bea4010885406&v=4 + url: https://github.com/akarev0 +- login: romashevchenko + count: 32 + avatarUrl: https://avatars.githubusercontent.com/u/132477732?v=4 + url: https://github.com/romashevchenko +- login: LorhanSohaky + count: 30 + avatarUrl: https://avatars.githubusercontent.com/u/16273730?u=095b66f243a2cd6a0aadba9a095009f8aaf18393&v=4 + url: https://github.com/LorhanSohaky +- login: cassiobotaro + count: 29 + avatarUrl: https://avatars.githubusercontent.com/u/3127847?u=a08022b191ddbd0a6159b2981d9d878b6d5bb71f&v=4 + url: https://github.com/cassiobotaro +- login: wdh99 + count: 29 + avatarUrl: https://avatars.githubusercontent.com/u/108172295?u=8a8fb95d5afe3e0fa33257b2aecae88d436249eb&v=4 + url: https://github.com/wdh99 +- login: pedabraham + count: 28 + avatarUrl: https://avatars.githubusercontent.com/u/16860088?u=abf922a7b920bf8fdb7867d8b43e091f1e796178&v=4 + url: https://github.com/pedabraham +- login: Smlep + count: 28 + avatarUrl: https://avatars.githubusercontent.com/u/16785985?v=4 + url: https://github.com/Smlep +- login: dedkot01 + count: 28 + avatarUrl: https://avatars.githubusercontent.com/u/26196675?u=e2966887124e67932853df4f10f86cb526edc7b0&v=4 + url: https://github.com/dedkot01 +- login: dpinezich + count: 28 + avatarUrl: https://avatars.githubusercontent.com/u/3204540?u=a2e1465e3ee10d537614d513589607eddefde09f&v=4 + url: https://github.com/dpinezich - login: maoyibo - count: 10 + count: 27 avatarUrl: https://avatars.githubusercontent.com/u/7887703?v=4 url: https://github.com/maoyibo +- login: 0417taehyun + count: 27 + avatarUrl: https://avatars.githubusercontent.com/u/63915557?u=47debaa860fd52c9b98c97ef357ddcec3b3fb399&v=4 + url: https://github.com/0417taehyun +- login: BilalAlpaslan + count: 26 + avatarUrl: https://avatars.githubusercontent.com/u/47563997?u=63ed66e304fe8d765762c70587d61d9196e5c82d&v=4 + url: https://github.com/BilalAlpaslan +- login: zy7y + count: 25 + avatarUrl: https://avatars.githubusercontent.com/u/67154681?u=5d634834cc514028ea3f9115f7030b99a1f4d5a4&v=4 + url: https://github.com/zy7y +- login: mycaule + count: 25 + avatarUrl: https://avatars.githubusercontent.com/u/6161385?u=e3cec75bd6d938a0d73fae0dc5534d1ab2ed1b0e&v=4 + url: https://github.com/mycaule +- login: sh0nk + count: 23 + avatarUrl: https://avatars.githubusercontent.com/u/6478810?u=af15d724875cec682ed8088a86d36b2798f981c0&v=4 + url: https://github.com/sh0nk +- login: axel584 + count: 23 + avatarUrl: https://avatars.githubusercontent.com/u/1334088?u=9667041f5b15dc002b6f9665fda8c0412933ac04&v=4 + url: https://github.com/axel584 +- login: AGolicyn + count: 21 + avatarUrl: https://avatars.githubusercontent.com/u/86262613?u=3c21606ab8d210a061a1673decff1e7d5592b380&v=4 + url: https://github.com/AGolicyn +- login: Attsun1031 + count: 20 + avatarUrl: https://avatars.githubusercontent.com/u/1175560?v=4 + url: https://github.com/Attsun1031 +- login: ycd + count: 20 + avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=bba5af018423a2858d49309bed2a899bb5c34ac5&v=4 + url: https://github.com/ycd +- login: delhi09 + count: 20 + avatarUrl: https://avatars.githubusercontent.com/u/63476957?u=6c86e59b48e0394d4db230f37fc9ad4d7e2c27c7&v=4 + url: https://github.com/delhi09 +- login: rogerbrinkmann + count: 20 + avatarUrl: https://avatars.githubusercontent.com/u/5690226?v=4 + url: https://github.com/rogerbrinkmann +- login: DevDae + count: 20 + avatarUrl: https://avatars.githubusercontent.com/u/87962045?u=08e10fa516e844934f4b3fc7c38b33c61697e4a1&v=4 + url: https://github.com/DevDae +- login: sattosan + count: 19 + avatarUrl: https://avatars.githubusercontent.com/u/20574756?u=b0d8474d2938189c6954423ae8d81d91013f80a8&v=4 + url: https://github.com/sattosan - login: ComicShrimp - count: 10 + count: 18 avatarUrl: https://avatars.githubusercontent.com/u/43503750?u=f440bc9062afb3c43b9b9c6cdfdcfe31d58699ef&v=4 url: https://github.com/ComicShrimp -- login: Alexandrhub - count: 10 - avatarUrl: https://avatars.githubusercontent.com/u/119126536?u=9fc0d48f3307817bafecc5861eb2168401a6cb04&v=4 - url: https://github.com/Alexandrhub -- login: izaguerreiro - count: 9 - avatarUrl: https://avatars.githubusercontent.com/u/2241504?v=4 - url: https://github.com/izaguerreiro -- login: graingert - count: 9 - avatarUrl: https://avatars.githubusercontent.com/u/413772?u=64b77b6aa405c68a9c6bcf45f84257c66eea5f32&v=4 - url: https://github.com/graingert -- login: PandaHun - count: 9 - avatarUrl: https://avatars.githubusercontent.com/u/13096845?u=646eba44db720e37d0dbe8e98e77ab534ea78a20&v=4 - url: https://github.com/PandaHun -- login: kty4119 - count: 9 - avatarUrl: https://avatars.githubusercontent.com/u/49435654?v=4 - url: https://github.com/kty4119 +- login: simatheone + count: 18 + avatarUrl: https://avatars.githubusercontent.com/u/78508673?u=1b9658d9ee0bde33f56130dd52275493ddd38690&v=4 + url: https://github.com/simatheone +- login: ivan-abc + count: 18 + avatarUrl: https://avatars.githubusercontent.com/u/36765187?u=c6e0ba571c1ccb6db9d94e62e4b8b5eda811a870&v=4 + url: https://github.com/ivan-abc - login: bezaca - count: 9 + count: 17 avatarUrl: https://avatars.githubusercontent.com/u/69092910?u=4ac58eab99bd37d663f3d23551df96d4fbdbf760&v=4 url: https://github.com/bezaca -- login: oandersonmagalhaes - count: 9 - avatarUrl: https://avatars.githubusercontent.com/u/83456692?v=4 - url: https://github.com/oandersonmagalhaes -- login: NinaHwang - count: 9 - avatarUrl: https://avatars.githubusercontent.com/u/79563565?u=eee6bfe9224c71193025ab7477f4f96ceaa05c62&v=4 - url: https://github.com/NinaHwang +- login: lbmendes + count: 17 + avatarUrl: https://avatars.githubusercontent.com/u/80999926?u=646619e2f07ac5a7c3f65fe7834197461a4fff9f&v=4 + url: https://github.com/lbmendes +- login: rostik1410 + count: 17 + avatarUrl: https://avatars.githubusercontent.com/u/11443899?u=e26a635c2ba220467b308a326a579b8ccf4a8701&v=4 + url: https://github.com/rostik1410 +- login: spacesphere + count: 17 + avatarUrl: https://avatars.githubusercontent.com/u/34628304?u=cde91f6002dd33156e1bf8005f11a7a3ed76b790&v=4 + url: https://github.com/spacesphere +- login: panko + count: 17 + avatarUrl: https://avatars.githubusercontent.com/u/1569515?u=a84a5d255621ed82f8e1ca052f5f2eeb75997da2&v=4 + url: https://github.com/panko diff --git a/docs/en/data/sponsors.yml b/docs/en/data/sponsors.yml index 1b5240b5e340f..85ac30d6d9888 100644 --- a/docs/en/data/sponsors.yml +++ b/docs/en/data/sponsors.yml @@ -5,32 +5,50 @@ gold: - url: https://platform.sh/try-it-now/?utm_source=fastapi-signup&utm_medium=banner&utm_campaign=FastAPI-signup-June-2023 title: "Build, run and scale your apps on a modern, reliable, and secure PaaS." img: https://fastapi.tiangolo.com/img/sponsors/platform-sh.png + - url: https://www.porter.run + title: Deploy FastAPI on AWS with a few clicks + img: https://fastapi.tiangolo.com/img/sponsors/porter.png + - url: https://bump.sh/fastapi?utm_source=fastapi&utm_medium=referral&utm_campaign=sponsor + title: Automate FastAPI documentation generation with Bump.sh + img: https://fastapi.tiangolo.com/img/sponsors/bump-sh.svg + - url: https://reflex.dev + title: Reflex + img: https://fastapi.tiangolo.com/img/sponsors/reflex.png + - url: https://github.com/scalar/scalar/?utm_source=fastapi&utm_medium=website&utm_campaign=main-badge + title: "Scalar: Beautiful Open-Source API References from Swagger/OpenAPI files" + img: https://fastapi.tiangolo.com/img/sponsors/scalar.svg + - url: https://www.propelauth.com/?utm_source=fastapi&utm_campaign=1223&utm_medium=mainbadge + title: Auth, user management and more for your B2B product + img: https://fastapi.tiangolo.com/img/sponsors/propelauth.png + - url: https://www.withcoherence.com/?utm_medium=advertising&utm_source=fastapi&utm_campaign=banner%20january%2024 + title: Coherence + img: https://fastapi.tiangolo.com/img/sponsors/coherence.png + - url: https://www.mongodb.com/developer/languages/python/python-quickstart-fastapi/?utm_campaign=fastapi_framework&utm_source=fastapi_sponsorship&utm_medium=web_referral + title: Simplify Full Stack Development with FastAPI & MongoDB + img: https://fastapi.tiangolo.com/img/sponsors/mongodb.png silver: - - url: https://www.deta.sh/?ref=fastapi - title: The launchpad for all your (team's) ideas - img: https://fastapi.tiangolo.com/img/sponsors/deta.svg - url: https://training.talkpython.fm/fastapi-courses title: FastAPI video courses on demand from people you trust - img: https://fastapi.tiangolo.com/img/sponsors/talkpython.png - - url: https://testdriven.io/courses/tdd-fastapi/ - title: Learn to build high-quality web apps with best practices - img: https://fastapi.tiangolo.com/img/sponsors/testdriven.svg + img: https://fastapi.tiangolo.com/img/sponsors/talkpython-v2.jpg - 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://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 + - url: https://speakeasyapi.dev?utm_source=fastapi+repo&utm_medium=github+sponsorship + title: SDKs for your API | Speakeasy + img: https://fastapi.tiangolo.com/img/sponsors/speakeasy.png + - url: https://www.svix.com/ + title: Svix - Webhooks as a service + img: https://fastapi.tiangolo.com/img/sponsors/svix.svg + - url: https://www.codacy.com/?utm_source=github&utm_medium=sponsors&utm_id=pioneers + title: Take code reviews from hours to minutes + img: https://fastapi.tiangolo.com/img/sponsors/codacy.png 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://www.flint.sh - title: IT expertise, consulting and development by passionate people - img: https://fastapi.tiangolo.com/img/sponsors/flint.png + - url: https://testdriven.io/courses/tdd-fastapi/ + title: Learn to build high-quality web apps with best practices + img: https://fastapi.tiangolo.com/img/sponsors/testdriven.svg diff --git a/docs/en/data/sponsors_badge.yml b/docs/en/data/sponsors_badge.yml index b3cb06327004b..00cbec7d28355 100644 --- a/docs/en/data/sponsors_badge.yml +++ b/docs/en/data/sponsors_badge.yml @@ -12,8 +12,19 @@ logins: - ObliviousAI - Doist - nihpo - - svix - armand-sauzay - databento-bot + - databento - nanram22 - Flint-company + - porter-dev + - fern-api + - ndimares + - svixhq + - Alek99 + - codacy + - zanfaruqui + - scalar + - bump-sh + - andrew-propelauth + - svix diff --git a/docs/en/docs/about/index.md b/docs/en/docs/about/index.md new file mode 100644 index 0000000000000..27b78696b55b0 --- /dev/null +++ b/docs/en/docs/about/index.md @@ -0,0 +1,3 @@ +# About + +About FastAPI, its design, inspiration and more. 🤓 diff --git a/docs/en/docs/advanced/additional-responses.md b/docs/en/docs/advanced/additional-responses.md index dca5f6a985cc1..41b39c18e6bc1 100644 --- a/docs/en/docs/advanced/additional-responses.md +++ b/docs/en/docs/advanced/additional-responses.md @@ -28,7 +28,7 @@ For example, to declare another response with a status code `404` and a Pydantic ``` !!! note - Have in mind that you have to return the `JSONResponse` directly. + Keep in mind that you have to return the `JSONResponse` directly. !!! info The `model` key is not part of OpenAPI. @@ -236,5 +236,5 @@ For example: To see what exactly you can include in the responses, you can check these sections in the OpenAPI specification: -* OpenAPI Responses Object, it includes the `Response Object`. -* OpenAPI Response Object, you can include anything from this directly in each response inside your `responses` parameter. Including `description`, `headers`, `content` (inside of this is that you declare different media types and JSON Schemas), and `links`. +* OpenAPI Responses Object, it includes the `Response Object`. +* OpenAPI Response Object, you can include anything from this directly in each response inside your `responses` parameter. Including `description`, `headers`, `content` (inside of this is that you declare different media types and JSON Schemas), and `links`. diff --git a/docs/en/docs/advanced/additional-status-codes.md b/docs/en/docs/advanced/additional-status-codes.md index 416444d3bdaae..0ce27534310c5 100644 --- a/docs/en/docs/advanced/additional-status-codes.md +++ b/docs/en/docs/advanced/additional-status-codes.md @@ -26,7 +26,7 @@ To achieve that, import `JSONResponse`, and return your content there directly, {!> ../../../docs_src/additional_status_codes/tutorial001_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="4 26" {!> ../../../docs_src/additional_status_codes/tutorial001_an.py!} @@ -41,7 +41,7 @@ To achieve that, import `JSONResponse`, and return your content there directly, {!> ../../../docs_src/additional_status_codes/tutorial001_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. diff --git a/docs/en/docs/advanced/advanced-dependencies.md b/docs/en/docs/advanced/advanced-dependencies.md index 402c5d7553f9b..0cffab56db9be 100644 --- a/docs/en/docs/advanced/advanced-dependencies.md +++ b/docs/en/docs/advanced/advanced-dependencies.md @@ -24,13 +24,13 @@ To do that, we declare a method `__call__`: {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="11" {!> ../../../docs_src/dependencies/tutorial011_an.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -51,13 +51,13 @@ And now, we can use `__init__` to declare the parameters of the instance that we {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="8" {!> ../../../docs_src/dependencies/tutorial011_an.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -78,13 +78,13 @@ We could create an instance of this class with: {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="17" {!> ../../../docs_src/dependencies/tutorial011_an.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -113,13 +113,13 @@ checker(q="somequery") {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="21" {!> ../../../docs_src/dependencies/tutorial011_an.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. diff --git a/docs/en/docs/advanced/async-tests.md b/docs/en/docs/advanced/async-tests.md index 9b39d70fca6a8..f9c82e6ab4602 100644 --- a/docs/en/docs/advanced/async-tests.md +++ b/docs/en/docs/advanced/async-tests.md @@ -84,6 +84,9 @@ response = client.get('/') !!! tip Note that we're using async/await with the new `AsyncClient` - the request is asynchronous. +!!! warning + If your application relies on lifespan events, the `AsyncClient` won't trigger these events. To ensure they are triggered, use `LifespanManager` from florimondmanca/asgi-lifespan. + ## Other Asynchronous Function Calls As the testing function is now asynchronous, you can now also call (and `await`) other `async` functions apart from sending requests to your FastAPI application in your tests, exactly as you would call them anywhere else in your code. diff --git a/docs/en/docs/advanced/behind-a-proxy.md b/docs/en/docs/advanced/behind-a-proxy.md index 03198851a394d..4da2ddefc4d51 100644 --- a/docs/en/docs/advanced/behind-a-proxy.md +++ b/docs/en/docs/advanced/behind-a-proxy.md @@ -18,7 +18,11 @@ In this case, the original path `/app` would actually be served at `/api/v1/app` Even though all your code is written assuming there's just `/app`. -And the proxy would be **"stripping"** the **path prefix** on the fly before transmitting the request to Uvicorn, keep your application convinced that it is serving at `/app`, so that you don't have to update all your code to include the prefix `/api/v1`. +```Python hl_lines="6" +{!../../../docs_src/behind_a_proxy/tutorial001.py!} +``` + +And the proxy would be **"stripping"** the **path prefix** on the fly before transmitting the request to Uvicorn, keeping your application convinced that it is being served at `/app`, so that you don't have to update all your code to include the prefix `/api/v1`. Up to here, everything would work as normally. @@ -46,7 +50,7 @@ The docs UI would also need the OpenAPI schema to declare that this API `server` ```JSON hl_lines="4-8" { - "openapi": "3.0.2", + "openapi": "3.1.0", // More stuff here "servers": [ { @@ -125,7 +129,7 @@ Passing the `root_path` to `FastAPI` would be the equivalent of passing the `--r ### About `root_path` -Have in mind that the server (Uvicorn) won't use that `root_path` for anything else than passing it to the app. +Keep in mind that the server (Uvicorn) won't use that `root_path` for anything else than passing it to the app. But if you go with your browser to http://127.0.0.1:8000/app you will see the normal response: @@ -142,7 +146,7 @@ Uvicorn will expect the proxy to access Uvicorn at `http://127.0.0.1:8000/app`, ## About proxies with a stripped path prefix -Have in mind that a proxy with stripped path prefix is only one of the ways to configure it. +Keep in mind that a proxy with stripped path prefix is only one of the ways to configure it. Probably in many cases the default will be that the proxy doesn't have a stripped path prefix. @@ -298,7 +302,7 @@ Will generate an OpenAPI schema like: ```JSON hl_lines="5-7" { - "openapi": "3.0.2", + "openapi": "3.1.0", // More stuff here "servers": [ { diff --git a/docs/en/docs/advanced/custom-response.md b/docs/en/docs/advanced/custom-response.md index ce2619e8de5fc..827776f5e52b6 100644 --- a/docs/en/docs/advanced/custom-response.md +++ b/docs/en/docs/advanced/custom-response.md @@ -101,7 +101,7 @@ But as you passed the `HTMLResponse` in the `response_class` too, **FastAPI** wi Here are some of the available responses. -Have in mind that you can use `Response` to return anything else, or even create a custom sub-class. +Keep in mind that you can use `Response` to return anything else, or even create a custom sub-class. !!! note "Technical Details" You could also use `from starlette.responses import HTMLResponse`. diff --git a/docs/en/docs/advanced/dataclasses.md b/docs/en/docs/advanced/dataclasses.md index 72daca06ad9f7..481bf5e6910da 100644 --- a/docs/en/docs/advanced/dataclasses.md +++ b/docs/en/docs/advanced/dataclasses.md @@ -8,7 +8,7 @@ But FastAPI also supports using internal support for `dataclasses`. +This is still supported thanks to **Pydantic**, as it has internal support for `dataclasses`. So, even with the code above that doesn't use Pydantic explicitly, FastAPI is using Pydantic to convert those standard dataclasses to Pydantic's own flavor of dataclasses. @@ -21,7 +21,7 @@ And of course, it supports the same: This works the same way as with Pydantic models. And it is actually achieved in the same way underneath, using Pydantic. !!! info - Have in mind that dataclasses can't do everything Pydantic models can do. + Keep in mind that dataclasses can't do everything Pydantic models can do. So, you might still need to use Pydantic models. @@ -91,7 +91,7 @@ Check the in-code annotation tips above to see more specific details. You can also combine `dataclasses` with other Pydantic models, inherit from them, include them in your own models, etc. -To learn more, check the Pydantic docs about dataclasses. +To learn more, check the Pydantic docs about dataclasses. ## Version diff --git a/docs/en/docs/advanced/events.md b/docs/en/docs/advanced/events.md index 6b7de41309bbe..ca9d86ae41e99 100644 --- a/docs/en/docs/advanced/events.md +++ b/docs/en/docs/advanced/events.md @@ -92,7 +92,7 @@ The `lifespan` parameter of the `FastAPI` app takes an **async context manager** ## Alternative Events (deprecated) !!! warning - The recommended way to handle the *startup* and *shutdown* is using the `lifespan` parameter of the `FastAPI` app as described above. + The recommended way to handle the *startup* and *shutdown* is using the `lifespan` parameter of the `FastAPI` app as described above. If you provide a `lifespan` parameter, `startup` and `shutdown` event handlers will no longer be called. It's all `lifespan` or all events, not both. You can probably skip this part. @@ -159,4 +159,4 @@ Underneath, in the ASGI technical specification, this is part of the ReDoc's OpenAPI extension to include a custom logo. - -### Normal **FastAPI** - -First, write all your **FastAPI** application as normally: - -```Python hl_lines="1 4 7-9" -{!../../../docs_src/extending_openapi/tutorial001.py!} -``` - -### Generate the OpenAPI schema - -Then, use the same utility function to generate the OpenAPI schema, inside a `custom_openapi()` function: - -```Python hl_lines="2 15-20" -{!../../../docs_src/extending_openapi/tutorial001.py!} -``` - -### Modify the OpenAPI schema - -Now you can add the ReDoc extension, adding a custom `x-logo` to the `info` "object" in the OpenAPI schema: - -```Python hl_lines="21-23" -{!../../../docs_src/extending_openapi/tutorial001.py!} -``` - -### Cache the OpenAPI schema - -You can use the property `.openapi_schema` as a "cache", to store your generated schema. - -That way, your application won't have to generate the schema every time a user opens your API docs. - -It will be generated only once, and then the same cached schema will be used for the next requests. - -```Python hl_lines="13-14 24-25" -{!../../../docs_src/extending_openapi/tutorial001.py!} -``` - -### Override the method - -Now you can replace the `.openapi()` method with your new function. - -```Python hl_lines="28" -{!../../../docs_src/extending_openapi/tutorial001.py!} -``` - -### Check it - -Once you go to http://127.0.0.1:8000/redoc you will see that you are using your custom logo (in this example, **FastAPI**'s logo): - - - -## Self-hosting JavaScript and CSS for docs - -The API docs use **Swagger UI** and **ReDoc**, and each of those need some JavaScript and CSS files. - -By default, those files are served from a CDN. - -But it's possible to customize it, you can set a specific CDN, or serve the files yourself. - -That's useful, for example, if you need your app to keep working even while offline, without open Internet access, or in a local network. - -Here you'll see how to serve those files yourself, in the same FastAPI app, and configure the docs to use them. - -### Project file structure - -Let's say your project file structure looks like this: - -``` -. -├── app -│ ├── __init__.py -│ ├── main.py -``` - -Now create a directory to store those static files. - -Your new file structure could look like this: - -``` -. -├── app -│   ├── __init__.py -│   ├── main.py -└── static/ -``` - -### Download the files - -Download the static files needed for the docs and put them on that `static/` directory. - -You can probably right-click each link and select an option similar to `Save link as...`. - -**Swagger UI** uses the files: - -* `swagger-ui-bundle.js` -* `swagger-ui.css` - -And **ReDoc** uses the file: - -* `redoc.standalone.js` - -After that, your file structure could look like: - -``` -. -├── app -│   ├── __init__.py -│   ├── main.py -└── static - ├── redoc.standalone.js - ├── swagger-ui-bundle.js - └── swagger-ui.css -``` - -### Serve the static files - -* Import `StaticFiles`. -* "Mount" a `StaticFiles()` instance in a specific path. - -```Python hl_lines="7 11" -{!../../../docs_src/extending_openapi/tutorial002.py!} -``` - -### Test the static files - -Start your application and go to http://127.0.0.1:8000/static/redoc.standalone.js. - -You should see a very long JavaScript file for **ReDoc**. - -It could start with something like: - -```JavaScript -/*! - * ReDoc - OpenAPI/Swagger-generated API Reference Documentation - * ------------------------------------------------------------- - * Version: "2.0.0-rc.18" - * Repo: https://github.com/Redocly/redoc - */ -!function(e,t){"object"==typeof exports&&"object"==typeof m - -... -``` - -That confirms that you are being able to serve static files from your app, and that you placed the static files for the docs in the correct place. - -Now we can configure the app to use those static files for the docs. - -### Disable the automatic docs - -The first step is to disable the automatic docs, as those use the CDN by default. - -To disable them, set their URLs to `None` when creating your `FastAPI` app: - -```Python hl_lines="9" -{!../../../docs_src/extending_openapi/tutorial002.py!} -``` - -### Include the custom docs - -Now you can create the *path operations* for the custom docs. - -You can re-use FastAPI's internal functions to create the HTML pages for the docs, and pass them the needed arguments: - -* `openapi_url`: the URL where the HTML page for the docs can get the OpenAPI schema for your API. You can use here the attribute `app.openapi_url`. -* `title`: the title of your API. -* `oauth2_redirect_url`: you can use `app.swagger_ui_oauth2_redirect_url` here to use the default. -* `swagger_js_url`: the URL where the HTML for your Swagger UI docs can get the **JavaScript** file. This is the one that your own app is now serving. -* `swagger_css_url`: the URL where the HTML for your Swagger UI docs can get the **CSS** file. This is the one that your own app is now serving. - -And similarly for ReDoc... - -```Python hl_lines="2-6 14-22 25-27 30-36" -{!../../../docs_src/extending_openapi/tutorial002.py!} -``` - -!!! tip - The *path operation* for `swagger_ui_redirect` is a helper for when you use OAuth2. - - If you integrate your API with an OAuth2 provider, you will be able to authenticate and come back to the API docs with the acquired credentials. And interact with it using the real OAuth2 authentication. - - Swagger UI will handle it behind the scenes for you, but it needs this "redirect" helper. - -### Create a *path operation* to test it - -Now, to be able to test that everything works, create a *path operation*: - -```Python hl_lines="39-41" -{!../../../docs_src/extending_openapi/tutorial002.py!} -``` - -### Test it - -Now, you should be able to disconnect your WiFi, go to your docs at http://127.0.0.1:8000/docs, and reload the page. - -And even without Internet, you would be able to see the docs for your API and interact with it. - -## Configuring Swagger UI - -You can configure some extra Swagger UI parameters. - -To configure them, pass the `swagger_ui_parameters` argument when creating the `FastAPI()` app object or to the `get_swagger_ui_html()` function. - -`swagger_ui_parameters` receives a dictionary with the configurations passed to Swagger UI directly. - -FastAPI converts the configurations to **JSON** to make them compatible with JavaScript, as that's what Swagger UI needs. - -### Disable Syntax Highlighting - -For example, you could disable syntax highlighting in Swagger UI. - -Without changing the settings, syntax highlighting is enabled by default: - - - -But you can disable it by setting `syntaxHighlight` to `False`: - -```Python hl_lines="3" -{!../../../docs_src/extending_openapi/tutorial003.py!} -``` - -...and then Swagger UI won't show the syntax highlighting anymore: - - - -### Change the Theme - -The same way you could set the syntax highlighting theme with the key `"syntaxHighlight.theme"` (notice that it has a dot in the middle): - -```Python hl_lines="3" -{!../../../docs_src/extending_openapi/tutorial004.py!} -``` - -That configuration would change the syntax highlighting color theme: - - - -### Change Default Swagger UI Parameters - -FastAPI includes some default configuration parameters appropriate for most of the use cases. - -It includes these default configurations: - -```Python -{!../../../fastapi/openapi/docs.py[ln:7-13]!} -``` - -You can override any of them by setting a different value in the argument `swagger_ui_parameters`. - -For example, to disable `deepLinking` you could pass these settings to `swagger_ui_parameters`: - -```Python hl_lines="3" -{!../../../docs_src/extending_openapi/tutorial005.py!} -``` - -### Other Swagger UI Parameters - -To see all the other possible configurations you can use, read the official docs for Swagger UI parameters. - -### JavaScript-only settings - -Swagger UI also allows other configurations to be **JavaScript-only** objects (for example, JavaScript functions). - -FastAPI also includes these JavaScript-only `presets` settings: - -```JavaScript -presets: [ - SwaggerUIBundle.presets.apis, - SwaggerUIBundle.SwaggerUIStandalonePreset -] -``` - -These are **JavaScript** objects, not strings, so you can't pass them from Python code directly. - -If you need to use JavaScript-only configurations like those, you can use one of the methods above. Override all the Swagger UI *path operation* and manually write any JavaScript you need. diff --git a/docs/en/docs/advanced/generate-clients.md b/docs/en/docs/advanced/generate-clients.md index f62c0b57c1818..3a810baee1957 100644 --- a/docs/en/docs/advanced/generate-clients.md +++ b/docs/en/docs/advanced/generate-clients.md @@ -12,6 +12,18 @@ A common tool is openapi-typescript-codegen. +## Client and SDK Generators - Sponsor + +There are also some **company-backed** Client and SDK generators based on OpenAPI (FastAPI), in some cases they can offer you **additional features** on top of high-quality generated SDKs/clients. + +Some of them also ✨ [**sponsor FastAPI**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨, this ensures the continued and healthy **development** of FastAPI and its **ecosystem**. + +And it shows their true commitment to FastAPI and its **community** (you), as they not only want to provide you a **good service** but also want to make sure you have a **good and healthy framework**, FastAPI. 🙇 + +For example, you might want to try Speakeasy. + +There are also several other companies offering similar services that you can search and find online. 🤓 + ## Generate a TypeScript Frontend Client Let's start with a simple FastAPI application: @@ -22,7 +34,7 @@ Let's start with a simple FastAPI application: {!> ../../../docs_src/generate_clients/tutorial001_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9-11 14-15 18 19 23" {!> ../../../docs_src/generate_clients/tutorial001.py!} @@ -75,7 +87,7 @@ It could look like this: "description": "", "main": "index.js", "scripts": { - "generate-client": "openapi --input http://localhost:8000/openapi.json --output ./src/client --client axios" + "generate-client": "openapi --input http://localhost:8000/openapi.json --output ./src/client --client axios --useOptions --useUnionTypes" }, "author": "", "license": "", @@ -94,7 +106,7 @@ After having that NPM `generate-client` script there, you can run it with: $ npm run generate-client frontend-app@1.0.0 generate-client /home/user/code/frontend-app -> openapi --input http://localhost:8000/openapi.json --output ./src/client --client axios +> openapi --input http://localhost:8000/openapi.json --output ./src/client --client axios --useOptions --useUnionTypes ```
@@ -134,7 +146,7 @@ For example, you could have a section for **items** and another section for **us {!> ../../../docs_src/generate_clients/tutorial002_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="23 28 36" {!> ../../../docs_src/generate_clients/tutorial002.py!} @@ -191,7 +203,7 @@ You can then pass that custom function to **FastAPI** as the `generate_unique_id {!> ../../../docs_src/generate_clients/tutorial003_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="8-9 12" {!> ../../../docs_src/generate_clients/tutorial003.py!} @@ -217,9 +229,17 @@ But for the generated client we could **modify** the OpenAPI operation IDs right We could download the OpenAPI JSON to a file `openapi.json` and then we could **remove that prefixed tag** with a script like this: -```Python -{!../../../docs_src/generate_clients/tutorial004.py!} -``` +=== "Python" + + ```Python + {!> ../../../docs_src/generate_clients/tutorial004.py!} + ``` + +=== "Node.js" + + ```Python + {!> ../../../docs_src/generate_clients/tutorial004.js!} + ``` With that, the operation IDs would be renamed from things like `items-get_items` to just `get_items`, that way the client generator can generate simpler method names. @@ -234,7 +254,7 @@ Now as the end result is in a file `openapi.json`, you would modify the `package "description": "", "main": "index.js", "scripts": { - "generate-client": "openapi --input ./openapi.json --output ./src/client --client axios" + "generate-client": "openapi --input ./openapi.json --output ./src/client --client axios --useOptions --useUnionTypes" }, "author": "", "license": "", diff --git a/docs/en/docs/advanced/index.md b/docs/en/docs/advanced/index.md index 467f0833e60a6..d8dcd4ca6790a 100644 --- a/docs/en/docs/advanced/index.md +++ b/docs/en/docs/advanced/index.md @@ -17,8 +17,17 @@ You could still use most of the features in **FastAPI** with the knowledge from And the next sections assume you already read it, and assume that you know those main ideas. -## TestDriven.io course +## External Courses -If you would like to take an advanced-beginner course to complement this section of the docs, you might want to check: Test-Driven Development with FastAPI and Docker by **TestDriven.io**. +Although the [Tutorial - User Guide](../tutorial/){.internal-link target=_blank} and this **Advanced User Guide** are written as a guided tutorial (like a book) and should be enough for you to **learn FastAPI**, you might want to complement it with additional courses. -They are currently donating 10% of all profits to the development of **FastAPI**. 🎉 😄 +Or it might be the case that you just prefer to take other courses because they adapt better to your learning style. + +Some course providers ✨ [**sponsor FastAPI**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨, this ensures the continued and healthy **development** of FastAPI and its **ecosystem**. + +And it shows their true commitment to FastAPI and its **community** (you), as they not only want to provide you a **good learning experience** but also want to make sure you have a **good and healthy framework**, FastAPI. 🙇 + +You might want to try their courses: + +* Talk Python Training +* Test-Driven Development diff --git a/docs/en/docs/advanced/openapi-callbacks.md b/docs/en/docs/advanced/openapi-callbacks.md index 71924ce8b2048..fb7a6d917d12b 100644 --- a/docs/en/docs/advanced/openapi-callbacks.md +++ b/docs/en/docs/advanced/openapi-callbacks.md @@ -36,9 +36,9 @@ This part is pretty normal, most of the code is probably already familiar to you ``` !!! tip - The `callback_url` query parameter uses a Pydantic URL type. + The `callback_url` query parameter uses a Pydantic URL type. -The only new thing is the `callbacks=messages_callback_router.routes` as an argument to the *path operation decorator*. We'll see what that is next. +The only new thing is the `callbacks=invoices_callback_router.routes` as an argument to the *path operation decorator*. We'll see what that is next. ## Documenting the callback @@ -103,11 +103,11 @@ It should look just like a normal FastAPI *path operation*: There are 2 main differences from a normal *path operation*: * It doesn't need to have any actual code, because your app will never call this code. It's only used to document the *external API*. So, the function could just have `pass`. -* The *path* can contain an OpenAPI 3 expression (see more below) where it can use variables with parameters and parts of the original request sent to *your API*. +* The *path* can contain an OpenAPI 3 expression (see more below) where it can use variables with parameters and parts of the original request sent to *your API*. ### The callback path expression -The callback *path* can have an OpenAPI 3 expression that can contain parts of the original request sent to *your API*. +The callback *path* can have an OpenAPI 3 expression that can contain parts of the original request sent to *your API*. In this case, it's the `str`: diff --git a/docs/en/docs/advanced/openapi-webhooks.md b/docs/en/docs/advanced/openapi-webhooks.md new file mode 100644 index 0000000000000..63cbdc6103c2f --- /dev/null +++ b/docs/en/docs/advanced/openapi-webhooks.md @@ -0,0 +1,51 @@ +# OpenAPI Webhooks + +There are cases where you want to tell your API **users** that your app could call *their* app (sending a request) with some data, normally to **notify** of some type of **event**. + +This means that instead of the normal process of your users sending requests to your API, it's **your API** (or your app) that could **send requests to their system** (to their API, their app). + +This is normally called a **webhook**. + +## Webhooks steps + +The process normally is that **you define** in your code what is the message that you will send, the **body of the request**. + +You also define in some way at which **moments** your app will send those requests or events. + +And **your users** define in some way (for example in a web dashboard somewhere) the **URL** where your app should send those requests. + +All the **logic** about how to register the URLs for webhooks and the code to actually send those requests is up to you. You write it however you want to in **your own code**. + +## Documenting webhooks with **FastAPI** and OpenAPI + +With **FastAPI**, using OpenAPI, you can define the names of these webhooks, the types of HTTP operations that your app can send (e.g. `POST`, `PUT`, etc.) and the request **bodies** that your app would send. + +This can make it a lot easier for your users to **implement their APIs** to receive your **webhook** requests, they might even be able to autogenerate some of their own API code. + +!!! info + Webhooks are available in OpenAPI 3.1.0 and above, supported by FastAPI `0.99.0` and above. + +## An app with webhooks + +When you create a **FastAPI** application, there is a `webhooks` attribute that you can use to define *webhooks*, the same way you would define *path operations*, for example with `@app.webhooks.post()`. + +```Python hl_lines="9-13 36-53" +{!../../../docs_src/openapi_webhooks/tutorial001.py!} +``` + +The webhooks that you define will end up in the **OpenAPI** schema and the automatic **docs UI**. + +!!! info + The `app.webhooks` object is actually just an `APIRouter`, the same type you would use when structuring your app with multiple files. + +Notice that with webhooks you are actually not declaring a *path* (like `/items/`), the text you pass there is just an **identifier** of the webhook (the name of the event), for example in `@app.webhooks.post("new-subscription")`, the webhook name is `new-subscription`. + +This is because it is expected that **your users** would define the actual **URL path** where they want to receive the webhook request in some other way (e.g. a web dashboard). + +### Check the docs + +Now you can start your app with Uvicorn and go to http://127.0.0.1:8000/docs. + +You will see your docs have the normal *path operations* and now also some **webhooks**: + + diff --git a/docs/en/docs/advanced/path-operation-advanced-configuration.md b/docs/en/docs/advanced/path-operation-advanced-configuration.md index a1c902ef2ccbb..8b79bfe22a213 100644 --- a/docs/en/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/en/docs/advanced/path-operation-advanced-configuration.md @@ -97,7 +97,7 @@ And if you see the resulting OpenAPI (at `/openapi.json` in your API), you will ```JSON hl_lines="22" { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": { "title": "FastAPI", "version": "0.1.0" @@ -150,9 +150,20 @@ And you could do this even if the data type in the request is not JSON. For example, in this application we don't use FastAPI's integrated functionality to extract the JSON Schema from Pydantic models nor the automatic validation for JSON. In fact, we are declaring the request content type as YAML, not JSON: -```Python hl_lines="17-22 24" -{!../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} -``` +=== "Pydantic v2" + + ```Python hl_lines="17-22 24" + {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} + ``` + +=== "Pydantic v1" + + ```Python hl_lines="17-22 24" + {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} + ``` + +!!! info + In Pydantic version 1 the method to get the JSON Schema for a model was called `Item.schema()`, in Pydantic version 2, the method is called `Item.model_json_schema()`. Nevertheless, although we are not using the default integrated functionality, we are still using a Pydantic model to manually generate the JSON Schema for the data that we want to receive in YAML. @@ -160,9 +171,20 @@ Then we use the request directly, and extract the body as `bytes`. This means th And then in our code, we parse that YAML content directly, and then we are again using the same Pydantic model to validate the YAML content: -```Python hl_lines="26-33" -{!../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} -``` +=== "Pydantic v2" + + ```Python hl_lines="26-33" + {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} + ``` + +=== "Pydantic v1" + + ```Python hl_lines="26-33" + {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} + ``` + +!!! info + In Pydantic version 1 the method to parse and validate an object was `Item.parse_obj()`, in Pydantic version 2, the method is called `Item.model_validate()`. !!! tip Here we re-use the same Pydantic model. diff --git a/docs/en/docs/advanced/response-change-status-code.md b/docs/en/docs/advanced/response-change-status-code.md index 979cef3f05367..b88d74a8af62e 100644 --- a/docs/en/docs/advanced/response-change-status-code.md +++ b/docs/en/docs/advanced/response-change-status-code.md @@ -30,4 +30,4 @@ And if you declared a `response_model`, it will still be used to filter and conv **FastAPI** will use that *temporal* response to extract the status code (also cookies and headers), and will put them in the final response that contains the value you returned, filtered by any `response_model`. -You can also declare the `Response` parameter in dependencies, and set the status code in them. But have in mind that the last one to be set will win. +You can also declare the `Response` parameter in dependencies, and set the status code in them. But keep in mind that the last one to be set will win. diff --git a/docs/en/docs/advanced/response-cookies.md b/docs/en/docs/advanced/response-cookies.md index 9178ef81621db..d53985dbba3f4 100644 --- a/docs/en/docs/advanced/response-cookies.md +++ b/docs/en/docs/advanced/response-cookies.md @@ -31,7 +31,7 @@ Then set Cookies in it, and then return it: ``` !!! tip - Have in mind that if you return a response directly instead of using the `Response` parameter, FastAPI will return it directly. + Keep in mind that if you return a response directly instead of using the `Response` parameter, FastAPI will return it directly. So, you will have to make sure your data is of the correct type. E.g. it is compatible with JSON, if you are returning a `JSONResponse`. diff --git a/docs/en/docs/advanced/response-headers.md b/docs/en/docs/advanced/response-headers.md index 758bd64556c85..49b5fe4766f3a 100644 --- a/docs/en/docs/advanced/response-headers.md +++ b/docs/en/docs/advanced/response-headers.md @@ -37,6 +37,6 @@ Create a response as described in [Return a Response Directly](response-directly ## Custom Headers -Have in mind that custom proprietary headers can be added using the 'X-' prefix. +Keep in mind that custom proprietary headers can be added using the 'X-' prefix. But if you have custom headers that you want a client in a browser to be able to see, you need to add them to your CORS configurations (read more in [CORS (Cross-Origin Resource Sharing)](../tutorial/cors.md){.internal-link target=_blank}), using the parameter `expose_headers` documented in Starlette's CORS docs. diff --git a/docs/en/docs/advanced/security/http-basic-auth.md b/docs/en/docs/advanced/security/http-basic-auth.md index 8177a4b289209..680f4dff53e6c 100644 --- a/docs/en/docs/advanced/security/http-basic-auth.md +++ b/docs/en/docs/advanced/security/http-basic-auth.md @@ -26,13 +26,13 @@ Then, when you type that username and password, the browser sends them in the he {!> ../../../docs_src/security/tutorial006_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="2 7 11" {!> ../../../docs_src/security/tutorial006_an.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -65,13 +65,13 @@ Then we can use `secrets.compare_digest()` to ensure that `credentials.username` {!> ../../../docs_src/security/tutorial007_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="1 12-24" {!> ../../../docs_src/security/tutorial007_an.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -105,7 +105,7 @@ if "johndoe" == "stanleyjobson" and "love123" == "swordfish": ... ``` -But right at the moment Python compares the first `j` in `johndoe` to the first `s` in `stanleyjobson`, it will return `False`, because it already knows that those two strings are not the same, thinking that "there's no need to waste more computation comparing the rest of the letters". And your application will say "incorrect user or password". +But right at the moment Python compares the first `j` in `johndoe` to the first `s` in `stanleyjobson`, it will return `False`, because it already knows that those two strings are not the same, thinking that "there's no need to waste more computation comparing the rest of the letters". And your application will say "Incorrect username or password". But then the attackers try with username `stanleyjobsox` and password `love123`. @@ -116,11 +116,11 @@ if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish": ... ``` -Python will have to compare the whole `stanleyjobso` in both `stanleyjobsox` and `stanleyjobson` before realizing that both strings are not the same. So it will take some extra microseconds to reply back "incorrect user or password". +Python will have to compare the whole `stanleyjobso` in both `stanleyjobsox` and `stanleyjobson` before realizing that both strings are not the same. So it will take some extra microseconds to reply back "Incorrect username or password". #### The time to answer helps the attackers -At that point, by noticing that the server took some microseconds longer to send the "incorrect user or password" response, the attackers will know that they got _something_ right, some of the initial letters were right. +At that point, by noticing that the server took some microseconds longer to send the "Incorrect username or password" response, the attackers will know that they got _something_ right, some of the initial letters were right. And then they can try again knowing that it's probably something more similar to `stanleyjobsox` than to `johndoe`. @@ -148,13 +148,13 @@ After detecting that the credentials are incorrect, return an `HTTPException` wi {!> ../../../docs_src/security/tutorial007_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="26-30" {!> ../../../docs_src/security/tutorial007_an.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. diff --git a/docs/en/docs/advanced/security/oauth2-scopes.md b/docs/en/docs/advanced/security/oauth2-scopes.md index 41cd61683dbb3..b93d2991c4dcb 100644 --- a/docs/en/docs/advanced/security/oauth2-scopes.md +++ b/docs/en/docs/advanced/security/oauth2-scopes.md @@ -68,7 +68,7 @@ First, let's quickly see the parts that change from the examples in the main **T {!> ../../../docs_src/security/tutorial005_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="2 4 8 12 47 65 106 108-116 122-125 129-135 140 156" {!> ../../../docs_src/security/tutorial005_an.py!} @@ -79,7 +79,7 @@ First, let's quickly see the parts that change from the examples in the main **T !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="3 7 11 45 63 104 106-114 120-123 127-133 138 152" + ```Python hl_lines="3 7 11 45 63 104 106-114 120-123 127-133 138 154" {!> ../../../docs_src/security/tutorial005_py310.py!} ``` @@ -88,16 +88,16 @@ First, let's quickly see the parts that change from the examples in the main **T !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 153" + ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" {!> ../../../docs_src/security/tutorial005_py39.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ 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" + ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" {!> ../../../docs_src/security/tutorial005.py!} ``` @@ -121,7 +121,7 @@ The `scopes` parameter receives a `dict` with each scope as a key and the descri {!> ../../../docs_src/security/tutorial005_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="63-66" {!> ../../../docs_src/security/tutorial005_an.py!} @@ -146,7 +146,7 @@ The `scopes` parameter receives a `dict` with each scope as a key and the descri {!> ../../../docs_src/security/tutorial005_py39.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -188,7 +188,7 @@ And we return the scopes as part of the JWT token. {!> ../../../docs_src/security/tutorial005_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="156" {!> ../../../docs_src/security/tutorial005_an.py!} @@ -199,7 +199,7 @@ And we return the scopes as part of the JWT token. !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="152" + ```Python hl_lines="154" {!> ../../../docs_src/security/tutorial005_py310.py!} ``` @@ -208,16 +208,16 @@ And we return the scopes as part of the JWT token. !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="153" + ```Python hl_lines="155" {!> ../../../docs_src/security/tutorial005_py39.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="153" + ```Python hl_lines="155" {!> ../../../docs_src/security/tutorial005.py!} ``` @@ -254,7 +254,7 @@ In this case, it requires the scope `me` (it could require more than one scope). {!> ../../../docs_src/security/tutorial005_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="4 140 171" {!> ../../../docs_src/security/tutorial005_an.py!} @@ -265,7 +265,7 @@ In this case, it requires the scope `me` (it could require more than one scope). !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="3 138 165" + ```Python hl_lines="3 138 167" {!> ../../../docs_src/security/tutorial005_py310.py!} ``` @@ -274,16 +274,16 @@ In this case, it requires the scope `me` (it could require more than one scope). !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="4 139 166" + ```Python hl_lines="4 139 168" {!> ../../../docs_src/security/tutorial005_py39.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="4 139 166" + ```Python hl_lines="4 139 168" {!> ../../../docs_src/security/tutorial005.py!} ``` @@ -320,7 +320,7 @@ This `SecurityScopes` class is similar to `Request` (`Request` was used to get t {!> ../../../docs_src/security/tutorial005_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="8 106" {!> ../../../docs_src/security/tutorial005_an.py!} @@ -344,7 +344,7 @@ This `SecurityScopes` class is similar to `Request` (`Request` was used to get t {!> ../../../docs_src/security/tutorial005_py39.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -377,7 +377,7 @@ In this exception, we include the scopes required (if any) as a string separated {!> ../../../docs_src/security/tutorial005_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="106 108-116" {!> ../../../docs_src/security/tutorial005_an.py!} @@ -401,7 +401,7 @@ In this exception, we include the scopes required (if any) as a string separated {!> ../../../docs_src/security/tutorial005_py39.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -436,7 +436,7 @@ We also verify that we have a user with that username, and if not, we raise that {!> ../../../docs_src/security/tutorial005_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="47 117-128" {!> ../../../docs_src/security/tutorial005_an.py!} @@ -460,7 +460,7 @@ We also verify that we have a user with that username, and if not, we raise that {!> ../../../docs_src/security/tutorial005_py39.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -487,7 +487,7 @@ For this, we use `security_scopes.scopes`, that contains a `list` with all these {!> ../../../docs_src/security/tutorial005_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="129-135" {!> ../../../docs_src/security/tutorial005_an.py!} @@ -511,7 +511,7 @@ For this, we use `security_scopes.scopes`, that contains a `list` with all these {!> ../../../docs_src/security/tutorial005_py39.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. diff --git a/docs/en/docs/advanced/settings.md b/docs/en/docs/advanced/settings.md index 60ec9c92c6208..f6db8d2b1527e 100644 --- a/docs/en/docs/advanced/settings.md +++ b/docs/en/docs/advanced/settings.md @@ -125,7 +125,34 @@ That means that any value read in Python from an environment variable will be a ## Pydantic `Settings` -Fortunately, Pydantic provides a great utility to handle these settings coming from environment variables with Pydantic: Settings management. +Fortunately, Pydantic provides a great utility to handle these settings coming from environment variables with Pydantic: Settings management. + +### Install `pydantic-settings` + +First, install the `pydantic-settings` package: + +
+ +```console +$ pip install pydantic-settings +---> 100% +``` + +
+ +It also comes included when you install the `all` extras with: + +
+ +```console +$ pip install "fastapi[all]" +---> 100% +``` + +
+ +!!! info + In Pydantic v1 it came included with the main package. Now it is distributed as this independent package so that you can choose to install it or not if you don't need that functionality. ### Create the `Settings` object @@ -135,9 +162,20 @@ The same way as with Pydantic models, you declare class attributes with type ann You can use all the same validation features and tools you use for Pydantic models, like different data types and additional validations with `Field()`. -```Python hl_lines="2 5-8 11" -{!../../../docs_src/settings/tutorial001.py!} -``` +=== "Pydantic v2" + + ```Python hl_lines="2 5-8 11" + {!> ../../../docs_src/settings/tutorial001.py!} + ``` + +=== "Pydantic v1" + + !!! info + In Pydantic v1 you would import `BaseSettings` directly from `pydantic` instead of from `pydantic_settings`. + + ```Python hl_lines="2 5-8 11" + {!> ../../../docs_src/settings/tutorial001_pv1.py!} + ``` !!! tip If you want something quick to copy and paste, don't use this example, use the last one below. @@ -222,13 +260,13 @@ Now we create a dependency that returns a new `config.Settings()`. {!> ../../../docs_src/settings/app02_an_py39/main.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="6 12-13" {!> ../../../docs_src/settings/app02_an/main.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -238,7 +276,7 @@ Now we create a dependency that returns a new `config.Settings()`. ``` !!! tip - We'll discuss the `@lru_cache()` in a bit. + We'll discuss the `@lru_cache` in a bit. For now you can assume `get_settings()` is a normal function. @@ -250,13 +288,13 @@ And then we can require it from the *path operation function* as a dependency an {!> ../../../docs_src/settings/app02_an_py39/main.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="17 19-21" {!> ../../../docs_src/settings/app02_an/main.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -288,7 +326,7 @@ This practice is common enough that it has a name, these environment variables a But a dotenv file doesn't really have to have that exact filename. -Pydantic has support for reading from these types of files using an external library. You can read more at Pydantic Settings: Dotenv (.env) support. +Pydantic has support for reading from these types of files using an external library. You can read more at Pydantic Settings: Dotenv (.env) support. !!! tip For this to work, you need to `pip install python-dotenv`. @@ -306,14 +344,28 @@ APP_NAME="ChimichangApp" And then update your `config.py` with: -```Python hl_lines="9-10" -{!../../../docs_src/settings/app03/config.py!} -``` +=== "Pydantic v2" + + ```Python hl_lines="9" + {!> ../../../docs_src/settings/app03_an/config.py!} + ``` -Here we create a class `Config` inside of your Pydantic `Settings` class, and set the `env_file` to the filename with the dotenv file we want to use. + !!! tip + The `model_config` attribute is used just for Pydantic configuration. You can read more at Pydantic Model Config. -!!! tip - The `Config` class is used just for Pydantic configuration. You can read more at Pydantic Model Config +=== "Pydantic v1" + + ```Python hl_lines="9-10" + {!> ../../../docs_src/settings/app03_an/config_pv1.py!} + ``` + + !!! tip + The `Config` class is used just for Pydantic configuration. You can read more at Pydantic Model Config. + +!!! info + In Pydantic version 1 the configuration was done in an internal class `Config`, in Pydantic version 2 it's done in an attribute `model_config`. This attribute takes a `dict`, and to get autocompletion and inline errors you can import and use `SettingsConfigDict` to define that `dict`. + +Here we define the config `env_file` inside of your Pydantic `Settings` class, and set the value to the filename with the dotenv file we want to use. ### Creating the `Settings` only once with `lru_cache` @@ -336,7 +388,7 @@ def get_settings(): we would create that object for each request, and we would be reading the `.env` file for each request. ⚠️ -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. ✔️ +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 3.9+" @@ -344,13 +396,13 @@ But as we are using the `@lru_cache()` decorator on top, the `Settings` object w {!> ../../../docs_src/settings/app03_an_py39/main.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="1 11" {!> ../../../docs_src/settings/app03_an/main.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -363,14 +415,14 @@ Then for any subsequent calls of `get_settings()` in the dependencies for the ne #### `lru_cache` Technical Details -`@lru_cache()` modifies the function it decorates to return the same value that was returned the first time, instead of computing it again, executing the code of the function every time. +`@lru_cache` modifies the function it decorates to return the same value that was returned the first time, instead of computing it again, executing the code of the function every time. So, the function below it will be executed once for each combination of arguments. And then the values returned by each of those combinations of arguments will be used again and again whenever the function is called with exactly the same combination of arguments. For example, if you have a function: ```Python -@lru_cache() +@lru_cache def say_hi(name: str, salutation: str = "Ms."): return f"Hello {salutation} {name}" ``` @@ -422,7 +474,7 @@ In the case of our dependency `get_settings()`, the function doesn't even take a That way, it behaves almost as if it was just a global variable. But as it uses a dependency function, then we can override it easily for testing. -`@lru_cache()` is part of `functools` which is part of Python's standard library, you can read more about it in the Python docs for `@lru_cache()`. +`@lru_cache` is part of `functools` which is part of Python's standard library, you can read more about it in the Python docs for `@lru_cache`. ## Recap @@ -430,4 +482,4 @@ You can use Pydantic Settings to handle the settings or configurations for your * By using a dependency you can simplify testing. * You can use `.env` files with it. -* Using `@lru_cache()` lets you avoid reading the dotenv file again and again for each request, while allowing you to override it during testing. +* Using `@lru_cache` lets you avoid reading the dotenv file again and again for each request, while allowing you to override it during testing. diff --git a/docs/en/docs/advanced/templates.md b/docs/en/docs/advanced/templates.md index 38618aeeb09cd..6055b30170db6 100644 --- a/docs/en/docs/advanced/templates.md +++ b/docs/en/docs/advanced/templates.md @@ -25,14 +25,16 @@ $ pip install jinja2 * Import `Jinja2Templates`. * Create a `templates` object that you can re-use later. * Declare a `Request` parameter in the *path operation* that will return a template. -* Use the `templates` you created to render and return a `TemplateResponse`, passing the `request` as one of the key-value pairs in the Jinja2 "context". +* Use the `templates` you created to render and return a `TemplateResponse`, pass the name of the template, the request object, and a "context" dictionary with key-value pairs to be used inside of the Jinja2 template. -```Python hl_lines="4 11 15-16" +```Python hl_lines="4 11 15-18" {!../../../docs_src/templates/tutorial001.py!} ``` !!! note - Notice that you have to pass the `request` as part of the key-value pairs in the context for Jinja2. So, you also have to declare it in your *path operation*. + Before FastAPI 0.108.0, Starlette 0.29.0, the `name` was the first parameter. + + Also, before that, in previous versions, the `request` object was passed as part of the key-value pairs in the context for Jinja2. !!! tip By declaring `response_class=HTMLResponse` the docs UI will be able to know that the response will be HTML. @@ -44,21 +46,61 @@ $ pip install jinja2 ## Writing templates -Then you can write a template at `templates/item.html` with: +Then you can write a template at `templates/item.html` with, for example: ```jinja hl_lines="7" {!../../../docs_src/templates/templates/item.html!} ``` -It will show the `id` taken from the "context" `dict` you passed: +### Template Context Values + +In the HTML that contains: + +{% raw %} + +```jinja +Item ID: {{ id }} +``` + +{% endraw %} + +...it will show the `id` taken from the "context" `dict` you passed: ```Python -{"request": request, "id": id} +{"id": id} +``` + +For example, with an ID of `42`, this would render: + +```html +Item ID: 42 +``` + +### Template `url_for` Arguments + +You can also use `url_for()` inside of the template, it takes as arguments the same arguments that would be used by your *path operation function*. + +So, the section with: + +{% raw %} + +```jinja + +``` + +{% endraw %} + +...will generate a link to the same URL that would be handled by the *path operation function* `read_item(id=id)`. + +For example, with an ID of `42`, this would render: + +```html + ``` ## Templates and static files -And you can also use `url_for()` inside of the template, and use it, for example, with the `StaticFiles` you mounted. +You can also use `url_for()` inside of the template, and use it, for example, with the `StaticFiles` you mounted with the `name="static"`. ```jinja hl_lines="4" {!../../../docs_src/templates/templates/item.html!} diff --git a/docs/en/docs/advanced/testing-database.md b/docs/en/docs/advanced/testing-database.md index 13a6959b6fca8..1c0669b9ce575 100644 --- a/docs/en/docs/advanced/testing-database.md +++ b/docs/en/docs/advanced/testing-database.md @@ -1,5 +1,12 @@ # Testing a Database +!!! info + These docs are about to be updated. 🎉 + + The current version assumes Pydantic v1, and SQLAlchemy versions less than 2.0. + + The new docs will include Pydantic v2 and will use SQLModel (which is also based on SQLAlchemy) once it is updated to use Pydantic v2 as well. + You can use the same dependency overrides from [Testing Dependencies with Overrides](testing-dependencies.md){.internal-link target=_blank} to alter a database for testing. You could want to set up a different database for testing, rollback the data after the tests, pre-fill it with some testing data, etc. diff --git a/docs/en/docs/advanced/testing-dependencies.md b/docs/en/docs/advanced/testing-dependencies.md index ee48a735d8b3d..57dd87f569632 100644 --- a/docs/en/docs/advanced/testing-dependencies.md +++ b/docs/en/docs/advanced/testing-dependencies.md @@ -40,7 +40,7 @@ And then **FastAPI** will call that override instead of the original dependency. {!> ../../../docs_src/dependency_testing/tutorial001_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="29-30 33" {!> ../../../docs_src/dependency_testing/tutorial001_an.py!} @@ -55,7 +55,7 @@ And then **FastAPI** will call that override instead of the original dependency. {!> ../../../docs_src/dependency_testing/tutorial001_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. diff --git a/docs/en/docs/advanced/websockets.md b/docs/en/docs/advanced/websockets.md index 94cf191d27050..b8dfab1d1f69f 100644 --- a/docs/en/docs/advanced/websockets.md +++ b/docs/en/docs/advanced/websockets.md @@ -124,7 +124,7 @@ They work the same way as for other FastAPI endpoints/*path operations*: {!> ../../../docs_src/websockets/tutorial002_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="69-70 83" {!> ../../../docs_src/websockets/tutorial002_an.py!} @@ -139,7 +139,7 @@ They work the same way as for other FastAPI endpoints/*path operations*: {!> ../../../docs_src/websockets/tutorial002_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -191,7 +191,7 @@ When a WebSocket connection is closed, the `await websocket.receive_text()` will {!> ../../../docs_src/websockets/tutorial003_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="81-83" {!> ../../../docs_src/websockets/tutorial003.py!} @@ -212,7 +212,7 @@ Client #1596980209979 left the chat !!! tip The app above is a minimal and simple example to demonstrate how to handle and broadcast messages to several WebSocket connections. - But have in mind that, as everything is handled in memory, in a single list, it will only work while the process is running, and will only work with a single process. + But keep in mind that, as everything is handled in memory, in a single list, it will only work while the process is running, and will only work with a single process. If you need something easy to integrate with FastAPI but that is more robust, supported by Redis, PostgreSQL or others, check encode/broadcaster. diff --git a/docs/en/docs/alternatives.md b/docs/en/docs/alternatives.md index 0f074ccf32dcc..d351c4e0b7d32 100644 --- a/docs/en/docs/alternatives.md +++ b/docs/en/docs/alternatives.md @@ -185,13 +185,13 @@ It's a Flask plug-in, that ties together Webargs, Marshmallow and APISpec. It uses the information from Webargs and Marshmallow to automatically generate OpenAPI schemas, using APISpec. -It's a great tool, very under-rated. It should be way more popular than many Flask plug-ins out there. It might be due to its documentation being too concise and abstract. +It's a great tool, very underrated. It should be way more popular than many Flask plug-ins out there. It might be due to its documentation being too concise and abstract. This solved having to write YAML (another syntax) inside of Python docstrings. This combination of Flask, Flask-apispec with Marshmallow and Webargs was my favorite backend stack until building **FastAPI**. -Using it led to the creation of several Flask full-stack generators. These are the main stack I (and several external teams) have been using up to now: +Using it led to the creation of several Flask full-stack generators. These are the main stacks I (and several external teams) have been using up to now: * https://github.com/tiangolo/full-stack * https://github.com/tiangolo/full-stack-flask-couchbase @@ -211,7 +211,7 @@ This isn't even Python, NestJS is a JavaScript (TypeScript) NodeJS framework ins It achieves something somewhat similar to what can be done with Flask-apispec. -It has an integrated dependency injection system, inspired by Angular two. It requires pre-registering the "injectables" (like all the other dependency injection systems I know), so, it adds to the verbosity and code repetition. +It has an integrated dependency injection system, inspired by Angular 2. It requires pre-registering the "injectables" (like all the other dependency injection systems I know), so, it adds to the verbosity and code repetition. As the parameters are described with TypeScript types (similar to Python type hints), editor support is quite good. @@ -263,7 +263,7 @@ I discovered Molten in the first stages of building **FastAPI**. And it has quit It doesn't use a data validation, serialization and documentation third-party library like Pydantic, it has its own. So, these data type definitions would not be reusable as easily. -It requires a little bit more verbose configurations. And as it is based on WSGI (instead of ASGI), it is not designed to take advantage of the high-performance provided by tools like Uvicorn, Starlette and Sanic. +It requires a little bit more verbose configurations. And as it is based on WSGI (instead of ASGI), it is not designed to take advantage of the high performance provided by tools like Uvicorn, Starlette and Sanic. The dependency injection system requires pre-registration of the dependencies and the dependencies are solved based on the declared types. So, it's not possible to declare more than one "component" that provides a certain type. @@ -342,7 +342,7 @@ Now APIStar is a set of tools to validate OpenAPI specifications, not a web fram ## Used by **FastAPI** -### Pydantic +### Pydantic Pydantic is a library to define data validation, serialization and documentation (using JSON Schema) based on Python type hints. @@ -357,7 +357,7 @@ It is comparable to Marshmallow. Although it's faster than Marshmallow in benchm ### Starlette -Starlette is a lightweight ASGI framework/toolkit, which is ideal for building high-performance asyncio services. +Starlette is a lightweight ASGI framework/toolkit, which is ideal for building high-performance asyncio services. It is very simple and intuitive. It's designed to be easily extensible, and have modular components. diff --git a/docs/en/docs/async.md b/docs/en/docs/async.md index 3d4b1956af477..2ead1f2db791c 100644 --- a/docs/en/docs/async.md +++ b/docs/en/docs/async.md @@ -409,11 +409,11 @@ Still, in both situations, chances are that **FastAPI** will [still be faster](/ ### Dependencies -The same applies for [dependencies](/tutorial/dependencies/index.md){.internal-link target=_blank}. If a dependency is a standard `def` function instead of `async def`, it is run in the external threadpool. +The same applies for [dependencies](./tutorial/dependencies/index.md){.internal-link target=_blank}. If a dependency is a standard `def` function instead of `async def`, it is run in the external threadpool. ### Sub-dependencies -You can have multiple dependencies and [sub-dependencies](/tutorial/dependencies/sub-dependencies.md){.internal-link target=_blank} requiring each other (as parameters of the function definitions), some of them might be created with `async def` and some with normal `def`. It would still work, and the ones created with normal `def` would be called on an external thread (from the threadpool) instead of being "awaited". +You can have multiple dependencies and [sub-dependencies](./tutorial/dependencies/sub-dependencies.md){.internal-link target=_blank} requiring each other (as parameters of the function definitions), some of them might be created with `async def` and some with normal `def`. It would still work, and the ones created with normal `def` would be called on an external thread (from the threadpool) instead of being "awaited". ### Other utility functions diff --git a/docs/en/docs/benchmarks.md b/docs/en/docs/benchmarks.md index e05fec8406621..d746b6d7c4e24 100644 --- a/docs/en/docs/benchmarks.md +++ b/docs/en/docs/benchmarks.md @@ -2,7 +2,7 @@ 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). (*) -But when checking benchmarks and comparisons you should have the following in mind. +But when checking benchmarks and comparisons you should keep the following in mind. ## Benchmarks and speed diff --git a/docs/en/docs/contributing.md b/docs/en/docs/contributing.md index f968489aed90b..2d308a9dbd801 100644 --- a/docs/en/docs/contributing.md +++ b/docs/en/docs/contributing.md @@ -4,11 +4,11 @@ First, you might want to see the basic ways to [help FastAPI and get help](help- ## Developing -If you already cloned the repository and you know that you need to deep dive in the code, here are some guidelines to set up your environment. +If you already cloned the fastapi repository and you want to deep dive in the code, here are some guidelines to set up your environment. ### Virtual environment with `venv` -You can create a virtual environment in a directory using Python's `venv` module: +You can create an isolated virtual local environment in a directory using Python's `venv` module. Let's do this in the cloned repository (where the `requirements.txt` is):
@@ -18,7 +18,7 @@ $ python -m venv env
-That will create a directory `./env/` with the Python binaries and then you will be able to install packages for that isolated environment. +That will create a directory `./env/` with the Python binaries, and then you will be able to install packages for that local environment. ### Activate the environment @@ -84,7 +84,7 @@ To check it worked, use: If it shows the `pip` binary at `env/bin/pip` then it worked. 🎉 -Make sure you have the latest pip version on your virtual environment to avoid errors on the next steps: +Make sure you have the latest pip version on your local environment to avoid errors on the next steps:
@@ -101,7 +101,7 @@ $ python -m pip install --upgrade pip This makes sure that if you use a terminal program installed by that package, you use the one from your local environment and not any other that could be installed globally. -### pip +### Install requirements using pip After activating the environment as described above: @@ -117,20 +117,20 @@ $ pip install -r requirements.txt It will install all the dependencies and your local FastAPI in your local environment. -#### Using your local FastAPI +### Using your local FastAPI -If you create a Python file that imports and uses FastAPI, and run it with the Python from your local environment, it will use your local FastAPI source code. +If you create a Python file that imports and uses FastAPI, and run it with the Python from your local environment, it will use your cloned local FastAPI source code. And if you update that local FastAPI source code when you run that Python file again, it will use the fresh version of FastAPI you just edited. That way, you don't have to "install" your local version to be able to test every change. !!! note "Technical Details" - This only happens when you install using this included `requiements.txt` instead of installing `pip install fastapi` directly. + This only happens when you install using this included `requirements.txt` instead of running `pip install fastapi` directly. - That is because inside of the `requirements.txt` file, the local version of FastAPI is marked to be installed in "editable" mode, with the `-e` option. + That is because inside the `requirements.txt` file, the local version of FastAPI is marked to be installed in "editable" mode, with the `-e` option. -### Format +### Format the code There is a script that you can run that will format and clean all your code: @@ -150,32 +150,7 @@ For it to sort them correctly, you need to have FastAPI installed locally in you First, make sure you set up your environment as described above, that will install all the requirements. -The documentation uses MkDocs. - -And there are extra tools/scripts in place to handle translations in `./scripts/docs.py`. - -!!! tip - You don't need to see the code in `./scripts/docs.py`, you just use it in the command line. - -All the documentation is in Markdown format in the directory `./docs/en/`. - -Many of the tutorials have blocks of code. - -In most of the cases, these blocks of code are actual complete applications that can be run as is. - -In fact, those blocks of code are not written inside the Markdown, they are Python files in the `./docs_src/` directory. - -And those Python files are included/injected in the documentation when generating the site. - -### Docs for tests - -Most of the tests actually run against the example source files in the documentation. - -This helps making sure that: - -* The documentation is up to date. -* The documentation examples can be run as is. -* Most of the features are covered by the documentation, ensured by test coverage. +### Docs live During local development, there is a script that builds the site and checks for any changes, live-reloading: @@ -229,7 +204,36 @@ Completion will take effect once you restart the terminal.
-### Apps and docs at the same time +### Docs Structure + +The documentation uses MkDocs. + +And there are extra tools/scripts in place to handle translations in `./scripts/docs.py`. + +!!! tip + You don't need to see the code in `./scripts/docs.py`, you just use it in the command line. + +All the documentation is in Markdown format in the directory `./docs/en/`. + +Many of the tutorials have blocks of code. + +In most of the cases, these blocks of code are actual complete applications that can be run as is. + +In fact, those blocks of code are not written inside the Markdown, they are Python files in the `./docs_src/` directory. + +And those Python files are included/injected in the documentation when generating the site. + +### Docs for tests + +Most of the tests actually run against the example source files in the documentation. + +This helps to make sure that: + +* The documentation is up-to-date. +* The documentation examples can be run as is. +* Most of the features are covered by the documentation, ensured by test coverage. + +#### Apps and docs at the same time If you run the examples with, e.g.: @@ -253,7 +257,9 @@ Here are the steps to help with translations. #### Tips and guidelines -* Check the currently existing pull requests for your language and add reviews requesting changes or approving them. +* Check the currently existing pull requests for your language. You can filter the pull requests by the ones with the label for your language. For example, for Spanish, the label is `lang-es`. + +* Review those pull requests, requesting changes or approving them. For the languages I don't speak, I'll wait for several others to review the translation before merging. !!! tip You can add comments with change suggestions to existing pull requests. @@ -262,19 +268,9 @@ Here are the steps to help with translations. * Check if there's a GitHub Discussion to coordinate translations for your language. You can subscribe to it, and when there's a new pull request to review, an automatic comment will be added to the discussion. -* Add a single pull request per page translated. That will make it much easier for others to review it. - -For the languages I don't speak, I'll wait for several others to review the translation before merging. +* If you translate pages, add a single pull request per page translated. That will make it much easier for others to review it. -* You can also check if there are translations for your language and add a review to them, that will help me know that the translation is correct and I can merge it. - * You could check in the GitHub Discussions for your language. - * Or you can filter the existing PRs by the ones with the label for your language, for example, for Spanish, the label is `lang-es`. - -* Use the same Python examples and only translate the text in the docs. You don't have to change anything for this to work. - -* Use the same images, file names, and links. You don't have to change anything for it to work. - -* To check the 2-letter code for the language you want to translate you can use the table List of ISO 639-1 codes. +* To check the 2-letter code for the language you want to translate, you can use the table List of ISO 639-1 codes. #### Existing language @@ -317,7 +313,7 @@ $ python ./scripts/docs.py live es Now you can go to http://127.0.0.1:8008 and see your changes live. -You will see that every language has all the pages. But some pages are not translated and have a notification about the missing translation. +You will see that every language has all the pages. But some pages are not translated and have an info box at the top, about the missing translation. Now let's say that you want to add a translation for the section [Features](features.md){.internal-link target=_blank}. @@ -336,7 +332,7 @@ docs/es/docs/features.md !!! tip Notice that the only change in the path and file name is the language code, from `en` to `es`. -If you go to your browser you will see that now the docs show your new section. 🎉 +If you go to your browser you will see that now the docs show your new section (the info box at the top is gone). 🎉 Now you can translate it all and see how it looks as you save the file. @@ -380,7 +376,7 @@ You can make the first pull request with those two files, `docs/ht/mkdocs.yml` a #### Preview the result -You can use the `./scripts/docs.py` with the `live` command to preview the results (or `mkdocs serve`). +As already mentioned above, you can use the `./scripts/docs.py` with the `live` command to preview the results (or `mkdocs serve`). Once you are done, you can also test it all as it would look online, including all the other languages. @@ -417,6 +413,25 @@ Serving at: http://127.0.0.1:8008
+#### Translation specific tips and guidelines + +* Translate only the Markdown documents (`.md`). Do not translate the code examples at `./docs_src`. + +* In code blocks within the Markdown document, translate comments (`# a comment`), but leave the rest unchanged. + +* Do not change anything enclosed in "``" (inline code). + +* In lines starting with `===` or `!!!`, translate only the ` "... Text ..."` part. Leave the rest unchanged. + +* You can translate info boxes like `!!! warning` with for example `!!! warning "Achtung"`. But do not change the word immediately after the `!!!`, it determines the color of the info box. + +* Do not change the paths in links to images, code files, Markdown documents. + +* However, when a Markdown document is translated, the `#hash-parts` in links to its headings may change. Update these links if possible. + * Search for such links in the translated document using the regex `#[^# ]`. + * Search in all documents already translated into your language for `your-translated-document.md`. For example VS Code has an option "Edit" -> "Find in Files". + * When translating a document, do not "pre-translate" `#hash-parts` that link to headings in untranslated documents. + ## Tests There is a script that you can run locally to test all the code and generate coverage reports in HTML: diff --git a/docs/en/docs/css/custom.css b/docs/en/docs/css/custom.css index 066b51725ecce..386aa9d7e7fd3 100644 --- a/docs/en/docs/css/custom.css +++ b/docs/en/docs/css/custom.css @@ -136,11 +136,43 @@ code { display: inline-block; } -.md-content__inner h1 { - direction: ltr !important; -} - .illustration { margin-top: 2em; margin-bottom: 2em; } + +/* Screenshots */ +/* +Simulate a browser window frame. +Inspired by Termynal's CSS tricks with modifications +*/ + +.screenshot { + display: block; + background-color: #d3e0de; + border-radius: 4px; + padding: 45px 5px 5px; + position: relative; + -webkit-box-sizing: border-box; + box-sizing: border-box; +} + +.screenshot img { + display: block; + border-radius: 2px; +} + +.screenshot:before { + content: ''; + position: absolute; + top: 15px; + left: 15px; + display: inline-block; + width: 15px; + height: 15px; + border-radius: 50%; + /* A little hack to display the window buttons in one pseudo element. */ + background: #d9515d; + -webkit-box-shadow: 25px 0 0 #f4c025, 50px 0 0 #3ec930; + box-shadow: 25px 0 0 #f4c025, 50px 0 0 #3ec930; +} diff --git a/docs/en/docs/deployment/cloud.md b/docs/en/docs/deployment/cloud.md new file mode 100644 index 0000000000000..d34fbe2f719b5 --- /dev/null +++ b/docs/en/docs/deployment/cloud.md @@ -0,0 +1,17 @@ +# Deploy FastAPI on Cloud Providers + +You can use virtually **any cloud provider** to deploy your FastAPI application. + +In most of the cases, the main cloud providers have guides to deploy FastAPI with them. + +## Cloud Providers - Sponsors + +Some cloud providers ✨ [**sponsor FastAPI**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨, this ensures the continued and healthy **development** of FastAPI and its **ecosystem**. + +And it shows their true commitment to FastAPI and its **community** (you), as they not only want to provide you a **good service** but also want to make sure you have a **good and healthy framework**, FastAPI. 🙇 + +You might want to try their services and follow their guides: + +* Platform.sh +* Porter +* Coherence diff --git a/docs/en/docs/deployment/concepts.md b/docs/en/docs/deployment/concepts.md index 77419f8b0dfd9..cc01fb24e1584 100644 --- a/docs/en/docs/deployment/concepts.md +++ b/docs/en/docs/deployment/concepts.md @@ -258,7 +258,7 @@ And you will have to make sure that it's a single process running those previous Of course, there are some cases where there's no problem in running the previous steps multiple times, in that case, it's a lot easier to handle. !!! tip - Also, have in mind that depending on your setup, in some cases you **might not even need any previous steps** before starting your application. + Also, keep in mind that depending on your setup, in some cases you **might not even need any previous steps** before starting your application. In that case, you wouldn't have to worry about any of this. 🤷 @@ -297,7 +297,7 @@ You can use simple tools like `htop` to see the CPU and RAM used in your server ## Recap -You have been reading here some of the main concepts that you would probably need to have in mind when deciding how to deploy your application: +You have been reading here some of the main concepts that you would probably need to keep in mind when deciding how to deploy your application: * Security - HTTPS * Running on startup diff --git a/docs/en/docs/deployment/deta.md b/docs/en/docs/deployment/deta.md deleted file mode 100644 index 229d7fd5d8eb4..0000000000000 --- a/docs/en/docs/deployment/deta.md +++ /dev/null @@ -1,391 +0,0 @@ -# Deploy FastAPI on Deta Space - -In this section you will learn how to easily deploy a **FastAPI** application on Deta Space, for free. 🎁 - -It will take you about **10 minutes** to deploy an API that you can use. After that, you can optionally release it to anyone. - -Let's dive in. - -!!! info - Deta is a **FastAPI** sponsor. 🎉 - -## A simple **FastAPI** app - -* To start, create an empty directory with the name of your app, for example `./fastapi-deta/`, and then navigate into it. - -```console -$ mkdir fastapi-deta -$ cd fastapi-deta -``` - -### FastAPI code - -* Create a `main.py` file with: - -```Python -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): - return {"item_id": item_id} -``` - -### Requirements - -Now, in the same directory create a file `requirements.txt` with: - -```text -fastapi -uvicorn[standard] -``` - -### Directory structure - -You will now have a directory `./fastapi-deta/` with two files: - -``` -. -└── main.py -└── requirements.txt -``` - -## Create a free **Deta Space** account - -Next, create a free account on Deta Space, you just need an email and password. - -You don't even need a credit card, but make sure **Developer Mode** is enabled when you sign up. - - -## Install the CLI - -Once you have your account, install the Deta Space CLI: - -=== "Linux, macOS" - -
- - ```console - $ curl -fsSL https://get.deta.dev/space-cli.sh | sh - ``` - -
- -=== "Windows PowerShell" - -
- - ```console - $ iwr https://get.deta.dev/space-cli.ps1 -useb | iex - ``` - -
- -After installing it, open a new terminal so that the installed CLI is detected. - -In a new terminal, confirm that it was correctly installed with: - -
- -```console -$ space --help - -Deta command line interface for managing deta micros. -Complete documentation available at https://deta.space/docs - -Usage: - space [flags] - space [command] - -Available Commands: - help Help about any command - link link code to project - login login to space - new create new project - push push code for project - release create release for a project - validate validate spacefile in dir - version Space CLI version -... -``` - -
- -!!! tip - If you have problems installing the CLI, check the official Deta Space Documentation. - -## Login with the CLI - -In order to authenticate your CLI with Deta Space, you will need an access token. - -To obtain this token, open your Deta Space Canvas, open the **Teletype** (command bar at the bottom of the Canvas), and then click on **Settings**. From there, select **Generate Token** and copy the resulting token. - - - -Now run `space login` from the Space CLI. Upon pasting the token into the CLI prompt and pressing enter, you should see a confirmation message. - -
- -```console -$ space login - -To authenticate the Space CLI with your Space account, generate a new access token in your Space settings and paste it below: - -# Enter access token (41 chars) >$ ***************************************** - -👍 Login Successful! -``` - -
- -## Create a new project in Space - -Now that you've authenticated with the Space CLI, use it to create a new Space Project: - -```console -$ space new - -# What is your project's name? >$ fastapi-deta -``` - -The Space CLI will ask you to name the project, we will call ours `fastapi-deta`. - -Then, it will try to automatically detect which framework or language you are using, showing you what it finds. In our case it will identify the Python app with the following message, prompting you to confirm: - -```console -⚙️ No Spacefile found, trying to auto-detect configuration ... -👇 Deta detected the following configuration: - -Micros: -name: fastapi-deta - L src: . - L engine: python3.9 - -# Do you want to bootstrap "fastapi-deta" with this configuration? (y/n)$ y -``` - -After you confirm, your project will be created in Deta Space inside a special app called Builder. Builder is a toolbox that helps you to create and manage your apps in Deta Space. - -The CLI will also create a `Spacefile` locally in the `fastapi-deta` directory. The Spacefile is a configuration file which tells Deta Space how to run your app. The `Spacefile` for your app will be as follows: - -```yaml -v: 0 -micros: - - name: fastapi-deta - src: . - engine: python3.9 -``` - -It is a `yaml` file, and you can use it to add features like scheduled tasks or modify how your app functions, which we'll do later. To learn more, read the `Spacefile` documentation. - -!!! tip - The Space CLI will also create a hidden `.space` folder in your local directory to link your local environment with Deta Space. This folder should not be included in your version control and will automatically be added to your `.gitignore` file, if you have initialized a Git repository. - -## Define the run command in the Spacefile - -The `run` command in the Spacefile tells Space what command should be executed to start your app. In this case it would be `uvicorn main:app`. - -```diff -v: 0 -micros: - - name: fastapi-deta - src: . - engine: python3.9 -+ run: uvicorn main:app -``` - -## Deploy to Deta Space - -To get your FastAPI live in the cloud, use one more CLI command: - -
- -```console -$ space push - ----> 100% - -build complete... created revision: satyr-jvjk - -✔ Successfully pushed your code and created a new Revision! -ℹ Updating your development instance with the latest Revision, it will be available on your Canvas shortly. -``` -
- -This command will package your code, upload all the necessary files to Deta Space, and run a remote build of your app, resulting in a **revision**. Whenever you run `space push` successfully, a live instance of your API is automatically updated with the latest revision. - -!!! tip - You can manage your revisions by opening your project in the Builder app. The live copy of your API will be visible under the **Develop** tab in Builder. - -## Check it - -The live instance of your API will also be added automatically to your Canvas (the dashboard) on Deta Space. - - - -Click on the new app called `fastapi-deta`, and it will open your API in a new browser tab on a URL like `https://fastapi-deta-gj7ka8.deta.app/`. - -You will get a JSON response from your FastAPI app: - -```JSON -{ - "Hello": "World" -} -``` - -And now you can head over to the `/docs` of your API. For this example, it would be `https://fastapi-deta-gj7ka8.deta.app/docs`. - - - -## Enable public access - -Deta will handle authentication for your account using cookies. By default, every app or API that you `push` or install to your Space is personal - it's only accessible to you. - -But you can also make your API public using the `Spacefile` from earlier. - -With a `public_routes` parameter, you can specify which paths of your API should be available to the public. - -Set your `public_routes` to `"*"` to open every route of your API to the public: - -```yaml -v: 0 -micros: - - name: fastapi-deta - src: . - engine: python3.9 - public_routes: - - "/*" -``` - -Then run `space push` again to update your live API on Deta Space. - -Once it deploys, you can share your URL with anyone and they will be able to access your API. 🚀 - -## HTTPS - -Congrats! You deployed your FastAPI app to Deta Space! 🎉 🍰 - -Also, notice that Deta Space correctly handles HTTPS for you, so you don't have to take care of that and can be sure that your users will have a secure encrypted connection. ✅ 🔒 - -## Create a release - -Space also allows you to publish your API. When you publish it, anyone else can install their own copy of your API, in their own Deta Space cloud. - -To do so, run `space release` in the Space CLI to create an **unlisted release**: - -
- -```console -$ space release - -# Do you want to use the latest revision (buzzard-hczt)? (y/n)$ y - -~ Creating a Release with the latest Revision - ----> 100% - -creating release... -publishing release in edge locations.. -completed... -released: fastapi-deta-exp-msbu -https://deta.space/discovery/r/5kjhgyxewkdmtotx - - Lift off -- successfully created a new Release! - Your Release is available globally on 5 Deta Edges - Anyone can install their own copy of your app. -``` -
- -This command publishes your revision as a release and gives you a link. Anyone you give this link to can install your API. - - -You can also make your app publicly discoverable by creating a **listed release** with `space release --listed` in the Space CLI: - -
- -```console -$ space release --listed - -# Do you want to use the latest revision (buzzard-hczt)? (y/n)$ y - -~ Creating a listed Release with the latest Revision ... - -creating release... -publishing release in edge locations.. -completed... -released: fastapi-deta-exp-msbu -https://deta.space/discovery/@user/fastapi-deta - - Lift off -- successfully created a new Release! - Your Release is available globally on 5 Deta Edges - Anyone can install their own copy of your app. - Listed on Discovery for others to find! -``` -
- -This will allow anyone to find and install your app via Deta Discovery. Read more about releasing your app in the docs. - -## Check runtime logs - -Deta Space also lets you inspect the logs of every app you build or install. - -Add some logging functionality to your app by adding a `print` statement to your `main.py` file. - -```py -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): - print(item_id) - return {"item_id": item_id} -``` - -The code within the `read_item` function includes a print statement that will output the `item_id` that is included in the URL. Send a request to your _path operation_ `/items/{item_id}` from the docs UI (which will have a URL like `https://fastapi-deta-gj7ka8.deta.app/docs`), using an ID like `5` as an example. - -Now go to your Space's Canvas. Click on the context menu (`...`) of your live app instance, and then click on **View Logs**. Here you can view your app's logs, sorted by time. - - - -## Learn more - -At some point, you will probably want to store some data for your app in a way that persists through time. For that you can use Deta Base and Deta Drive, both of which have a generous **free tier**. - -You can also read more in the Deta Space Documentation. - -!!! tip - If you have any Deta related questions, comments, or feedback, head to the Deta Discord server. - - -## Deployment Concepts - -Coming back to the concepts we discussed in [Deployments Concepts](./concepts.md){.internal-link target=_blank}, here's how each of them would be handled with Deta Space: - -- **HTTPS**: Handled by Deta Space, they will give you a subdomain and handle HTTPS automatically. -- **Running on startup**: Handled by Deta Space, as part of their service. -- **Restarts**: Handled by Deta Space, as part of their service. -- **Replication**: Handled by Deta Space, as part of their service. -- **Authentication**: Handled by Deta Space, as part of their service. -- **Memory**: Limit predefined by Deta Space, you could contact them to increase it. -- **Previous steps before starting**: Can be configured using the `Spacefile`. - -!!! note - Deta Space is designed to make it easy and free to build cloud applications for yourself. Then you can optionally share them with anyone. - - It can simplify several use cases, but at the same time, it doesn't support others, like using external databases (apart from Deta's own NoSQL database system), custom virtual machines, etc. - - You can read more details in the Deta Space Documentation to see if it's the right choice for you. diff --git a/docs/en/docs/deployment/https.md b/docs/en/docs/deployment/https.md index 790976a718f78..5cf76c1111d6e 100644 --- a/docs/en/docs/deployment/https.md +++ b/docs/en/docs/deployment/https.md @@ -9,7 +9,7 @@ But it is way more complex than that. To **learn the basics of HTTPS**, from a consumer perspective, check https://howhttps.works/. -Now, from a **developer's perspective**, here are several things to have in mind while thinking about HTTPS: +Now, from a **developer's perspective**, here are several things to keep in mind while thinking about HTTPS: * For HTTPS, **the server** needs to **have "certificates"** generated by a **third party**. * Those certificates are actually **acquired** from the third party, not "generated". diff --git a/docs/en/docs/deployment/index.md b/docs/en/docs/deployment/index.md index 6c43d8abbe4db..b43bd050a37ab 100644 --- a/docs/en/docs/deployment/index.md +++ b/docs/en/docs/deployment/index.md @@ -16,6 +16,6 @@ There are several ways to do it depending on your specific use case and the tool You could **deploy a server** yourself using a combination of tools, you could use a **cloud service** that does part of the work for you, or other possible options. -I will show you some of the main concepts you should probably have in mind when deploying a **FastAPI** application (although most of it applies to any other type of web application). +I will show you some of the main concepts you should probably keep in mind when deploying a **FastAPI** application (although most of it applies to any other type of web application). -You will see more details to have in mind and some of the techniques to do it in the next sections. ✨ +You will see more details to keep in mind and some of the techniques to do it in the next sections. ✨ diff --git a/docs/en/docs/deployment/manually.md b/docs/en/docs/deployment/manually.md index d6892b2c14ad6..b10a3686d7565 100644 --- a/docs/en/docs/deployment/manually.md +++ b/docs/en/docs/deployment/manually.md @@ -10,11 +10,11 @@ There are 3 main alternatives: ## Server Machine and Server Program -There's a small detail about names to have in mind. 💡 +There's a small detail about names to keep in mind. 💡 The word "**server**" is commonly used to refer to both the remote/cloud computer (the physical or virtual machine) and also the program that is running on that machine (e.g. Uvicorn). -Just have that in mind when you read "server" in general, it could refer to one of those two things. +Just keep in mind that when you read "server" in general, it could refer to one of those two things. When referring to the remote machine, it's common to call it **server**, but also **machine**, **VM** (virtual machine), **node**. Those all refer to some type of remote machine, normally running Linux, where you run programs. diff --git a/docs/en/docs/deployment/server-workers.md b/docs/en/docs/deployment/server-workers.md index 4ccd9d9f69a8b..2df9f3d432536 100644 --- a/docs/en/docs/deployment/server-workers.md +++ b/docs/en/docs/deployment/server-workers.md @@ -90,7 +90,9 @@ Let's see what each of those options mean: ``` * So, the colon in `main:app` would be equivalent to the Python `import` part in `from main import app`. + * `--workers`: The number of worker processes to use, each will run a Uvicorn worker, in this case, 4 workers. + * `--worker-class`: The Gunicorn-compatible worker class to use in the worker processes. * Here we pass the class that Gunicorn can import and use with: diff --git a/docs/en/docs/external-links.md b/docs/en/docs/external-links.md index 0c91470bc0a03..b89021ee2c57d 100644 --- a/docs/en/docs/external-links.md +++ b/docs/en/docs/external-links.md @@ -9,79 +9,21 @@ Here's an incomplete list of some of them. !!! tip If you have an article, project, tool, or anything related to **FastAPI** that is not yet listed here, create a Pull Request adding it. -## Articles +{% for section_name, section_content in external_links.items() %} -### English +## {{ section_name }} -{% if external_links %} -{% for article in external_links.articles.english %} +{% for lang_name, lang_content in section_content.items() %} -* {{ article.title }} by {{ article.author }}. -{% endfor %} -{% endif %} - -### Japanese - -{% if external_links %} -{% for article in external_links.articles.japanese %} - -* {{ article.title }} by {{ article.author }}. -{% endfor %} -{% endif %} - -### Vietnamese +### {{ lang_name }} -{% if external_links %} -{% for article in external_links.articles.vietnamese %} +{% for item in lang_content %} -* {{ article.title }} by {{ article.author }}. -{% endfor %} -{% endif %} - -### Russian - -{% if external_links %} -{% for article in external_links.articles.russian %} +* {{ item.title }} by {{ item.author }}. -* {{ article.title }} by {{ article.author }}. {% endfor %} -{% endif %} - -### German - -{% if external_links %} -{% for article in external_links.articles.german %} - -* {{ article.title }} by {{ article.author }}. {% endfor %} -{% endif %} - -### Taiwanese - -{% if external_links %} -{% for article in external_links.articles.taiwanese %} - -* {{ article.title }} by {{ article.author }}. -{% endfor %} -{% endif %} - -## Podcasts - -{% if external_links %} -{% for article in external_links.podcasts.english %} - -* {{ article.title }} by {{ article.author }}. -{% endfor %} -{% endif %} - -## Talks - -{% if external_links %} -{% for article in external_links.talks.english %} - -* {{ article.title }} by {{ article.author }}. {% endfor %} -{% endif %} ## Projects diff --git a/docs/en/docs/fastapi-people.md b/docs/en/docs/fastapi-people.md index 20caaa1ee8be1..2bd01ba434e16 100644 --- a/docs/en/docs/fastapi-people.md +++ b/docs/en/docs/fastapi-people.md @@ -1,8 +1,13 @@ +--- +hide: + - navigation +--- + # FastAPI People FastAPI has an amazing community that welcomes people from all backgrounds. -## Creator - Maintainer +## Creator Hey! 👋 @@ -18,7 +23,7 @@ This is me:
{% endif %} -I'm the creator and maintainer of **FastAPI**. You can read more about that in [Help FastAPI - Get Help - Connect with the author](help-fastapi.md#connect-with-the-author){.internal-link target=_blank}. +I'm the creator of **FastAPI**. You can read more about that in [Help FastAPI - Get Help - Connect with the author](help-fastapi.md#connect-with-the-author){.internal-link target=_blank}. ...But here I want to show you the community. @@ -34,13 +39,60 @@ These are the people that: A round of applause to them. 👏 🙇 -## Most active users last month +## FastAPI Experts + +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}. 🙇 + +They have proven to be **FastAPI Experts** by helping many others. ✨ + +!!! tip + You could become an official FastAPI Expert too! + + Just [help others with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}. 🤓 + +You can see the **FastAPI Experts** for: + +* [Last Month](#fastapi-experts-last-month) 🤓 +* [3 Months](#fastapi-experts-3-months) 😎 +* [6 Months](#fastapi-experts-6-months) 🧐 +* [1 Year](#fastapi-experts-1-year) 🧑‍🔬 +* [**All Time**](#fastapi-experts-all-time) 🧙 + +### FastAPI Experts - 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 %} +
+{% for user in people.last_month_experts[:10] %} + +
@{{ user.login }}
Questions replied: {{ user.count }}
+{% endfor %} + +
+{% endif %} + +### FastAPI Experts - 3 Months + +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 3 months. 😎 + +{% if people %} +
+{% for user in people.three_months_experts[:10] %} + +
@{{ user.login }}
Questions replied: {{ user.count }}
+{% endfor %} + +
+{% endif %} + +### FastAPI Experts - 6 Months -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. ☕ +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 6 months. 🧐 {% if people %}
-{% for user in people.last_month_active %} +{% for user in people.six_months_experts[:10] %}
@{{ user.login }}
Questions replied: {{ user.count }}
{% endfor %} @@ -48,17 +100,29 @@ These are the users that have been [helping others the most with questions in Gi
{% endif %} -## Experts +### FastAPI Experts - 1 Year -Here are the **FastAPI Experts**. 🤓 +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 year. 🧑‍🔬 -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*. +{% if people %} +
+{% for user in people.one_year_experts[:20] %} -They have proven to be experts by helping many others. ✨ +
@{{ user.login }}
Questions replied: {{ user.count }}
+{% endfor %} + +
+{% endif %} + +### FastAPI Experts - All Time + +Here are the all time **FastAPI Experts**. 🤓🤯 + +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*. 🧙 {% if people %}
-{% for user in people.experts %} +{% for user in people.experts[:50] %}
@{{ user.login }}
Questions replied: {{ user.count }}
{% endfor %} @@ -76,7 +140,7 @@ They have contributed source code, documentation, translations, etc. 📦 {% if people %}
-{% for user in people.top_contributors %} +{% for user in people.top_contributors[:50] %}
@{{ user.login }}
Pull Requests: {{ user.count }}
{% endfor %} @@ -86,21 +150,15 @@ They have contributed source code, documentation, translations, etc. 📦 There are many other contributors (more than a hundred), you can see them all in the FastAPI GitHub Contributors page. 👷 -## Top Reviewers - -These users are the **Top Reviewers**. 🕵️ +## Top Translation Reviewers -### Reviews for Translations +These users are the **Top Translation Reviewers**. 🕵️ I only speak a few languages (and not very well 😅). So, the reviewers are the ones that have the [**power to approve translations**](contributing.md#translations){.internal-link target=_blank} of the documentation. Without them, there wouldn't be documentation in several other languages. ---- - -The **Top Reviewers** 🕵️ have reviewed the most Pull Requests from others, ensuring the quality of the code, documentation, and especially, the **translations**. - {% if people %}
-{% for user in people.top_reviewers %} +{% for user in people.top_translations_reviewers[:50] %}
@{{ user.login }}
Reviews: {{ user.count }}
{% endfor %} diff --git a/docs/en/docs/features.md b/docs/en/docs/features.md index 98f37b5344580..6f0e74b3d1882 100644 --- a/docs/en/docs/features.md +++ b/docs/en/docs/features.md @@ -1,3 +1,8 @@ +--- +hide: + - navigation +--- + # Features ## FastAPI features @@ -174,7 +179,7 @@ With **FastAPI** you get all of **Starlette**'s features (as FastAPI is just Sta ## Pydantic features -**FastAPI** is fully compatible with (and based on) Pydantic. So, any additional Pydantic code you have, will also work. +**FastAPI** is fully compatible with (and based on) Pydantic. So, any additional Pydantic code you have, will also work. Including external libraries also based on Pydantic, as ORMs, ODMs for databases. diff --git a/docs/en/docs/help-fastapi.md b/docs/en/docs/help-fastapi.md index e977dba20019b..095fc8c586d44 100644 --- a/docs/en/docs/help-fastapi.md +++ b/docs/en/docs/help-fastapi.md @@ -51,7 +51,7 @@ You can: * Tell me how you use FastAPI (I love to hear that). * Hear when I make announcements or release new tools. * You can also follow @fastapi on Twitter (a separate account). -* Connect with me on **Linkedin**. +* Follow me on **Linkedin**. * Hear when I make announcements or release new tools (although I use Twitter more often 🤷‍♂). * Read what I write (or follow me) on **Dev.to** or **Medium**. * Read other ideas, articles, and read about tools I have created. @@ -106,7 +106,7 @@ In many cases they will only copy a fragment of the code, but that's not enough * You can ask them to provide a minimal, reproducible, example, that you can **copy-paste** and run locally to see the same error or behavior they are seeing, or to understand their use case better. -* If you are feeling too generous, you can try to **create an example** like that yourself, just based on the description of the problem. Just have in mind that this might take a lot of time and it might be better to ask them to clarify the problem first. +* If you are feeling too generous, you can try to **create an example** like that yourself, just based on the description of the problem. Just keep in mind that this might take a lot of time and it might be better to ask them to clarify the problem first. ### Suggest solutions @@ -148,7 +148,7 @@ Again, please try your best to be kind. 🤗 --- -Here's what to have in mind and how to review a pull request: +Here's what to keep in mind and how to review a pull request: ### Understand the problem @@ -231,11 +231,9 @@ Join the 👥 Gitter chat, but as it doesn't have channels and advanced features, conversations are more difficult, so Discord is now the recommended system. - ### Don't use the chat for questions -Have in mind that as chats allow more "free conversation", it's easy to ask questions that are too general and more difficult to answer, so, you might not receive answers. +Keep in mind that as chats allow more "free conversation", it's easy to ask questions that are too general and more difficult to answer, so, you might not receive answers. In GitHub, the template will guide you to write the right question so that you can more easily get a good answer, or even solve the problem yourself even before asking. And in GitHub I can make sure I always answer everything, even if it takes some time. I can't personally do that with the chat systems. 😅 diff --git a/docs/en/docs/help/index.md b/docs/en/docs/help/index.md new file mode 100644 index 0000000000000..5ee7df2fefc8a --- /dev/null +++ b/docs/en/docs/help/index.md @@ -0,0 +1,3 @@ +# Help + +Help and get help, contribute, get involved. 🤝 diff --git a/docs/en/docs/history-design-future.md b/docs/en/docs/history-design-future.md index 9db1027c26c2a..7824fb080ffe5 100644 --- a/docs/en/docs/history-design-future.md +++ b/docs/en/docs/history-design-future.md @@ -54,7 +54,7 @@ All in a way that provided the best development experience for all the developer ## Requirements -After testing several alternatives, I decided that I was going to use **Pydantic** for its advantages. +After testing several alternatives, I decided that I was going to use **Pydantic** for its advantages. Then I contributed to it, to make it fully compliant with JSON Schema, to support different ways to define constraint declarations, and to improve editor support (type checks, autocompletion) based on the tests in several editors. diff --git a/docs/en/docs/advanced/async-sql-databases.md b/docs/en/docs/how-to/async-sql-encode-databases.md similarity index 86% rename from docs/en/docs/advanced/async-sql-databases.md rename to docs/en/docs/how-to/async-sql-encode-databases.md index 93c288e1b4f56..c7b340d679179 100644 --- a/docs/en/docs/advanced/async-sql-databases.md +++ b/docs/en/docs/how-to/async-sql-encode-databases.md @@ -1,4 +1,14 @@ -# Async SQL (Relational) Databases +# ~~Async SQL (Relational) Databases with Encode/Databases~~ (deprecated) + +!!! info + These docs are about to be updated. 🎉 + + The current version assumes Pydantic v1. + + The new docs will include Pydantic v2 and will use SQLModel once it is updated to use Pydantic v2 as well. + +!!! warning "Deprecated" + This tutorial is deprecated and will be removed in a future version. You can also use `encode/databases` with **FastAPI** to connect to databases using `async` and `await`. @@ -107,6 +117,11 @@ Create the *path operation function* to create notes: {!../../../docs_src/async_sql_databases/tutorial001.py!} ``` +!!! info + In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`. + + The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2. + !!! Note Notice that as we communicate with the database using `await`, the *path operation function* is declared with `async`. diff --git a/docs/en/docs/advanced/conditional-openapi.md b/docs/en/docs/how-to/conditional-openapi.md similarity index 100% rename from docs/en/docs/advanced/conditional-openapi.md rename to docs/en/docs/how-to/conditional-openapi.md diff --git a/docs/en/docs/how-to/configure-swagger-ui.md b/docs/en/docs/how-to/configure-swagger-ui.md new file mode 100644 index 0000000000000..f36ba5ba8c230 --- /dev/null +++ b/docs/en/docs/how-to/configure-swagger-ui.md @@ -0,0 +1,78 @@ +# Configure Swagger UI + +You can configure some extra Swagger UI parameters. + +To configure them, pass the `swagger_ui_parameters` argument when creating the `FastAPI()` app object or to the `get_swagger_ui_html()` function. + +`swagger_ui_parameters` receives a dictionary with the configurations passed to Swagger UI directly. + +FastAPI converts the configurations to **JSON** to make them compatible with JavaScript, as that's what Swagger UI needs. + +## Disable Syntax Highlighting + +For example, you could disable syntax highlighting in Swagger UI. + +Without changing the settings, syntax highlighting is enabled by default: + + + +But you can disable it by setting `syntaxHighlight` to `False`: + +```Python hl_lines="3" +{!../../../docs_src/configure_swagger_ui/tutorial001.py!} +``` + +...and then Swagger UI won't show the syntax highlighting anymore: + + + +## Change the Theme + +The same way you could set the syntax highlighting theme with the key `"syntaxHighlight.theme"` (notice that it has a dot in the middle): + +```Python hl_lines="3" +{!../../../docs_src/configure_swagger_ui/tutorial002.py!} +``` + +That configuration would change the syntax highlighting color theme: + + + +## Change Default Swagger UI Parameters + +FastAPI includes some default configuration parameters appropriate for most of the use cases. + +It includes these default configurations: + +```Python +{!../../../fastapi/openapi/docs.py[ln:7-13]!} +``` + +You can override any of them by setting a different value in the argument `swagger_ui_parameters`. + +For example, to disable `deepLinking` you could pass these settings to `swagger_ui_parameters`: + +```Python hl_lines="3" +{!../../../docs_src/configure_swagger_ui/tutorial003.py!} +``` + +## Other Swagger UI Parameters + +To see all the other possible configurations you can use, read the official docs for Swagger UI parameters. + +## JavaScript-only settings + +Swagger UI also allows other configurations to be **JavaScript-only** objects (for example, JavaScript functions). + +FastAPI also includes these JavaScript-only `presets` settings: + +```JavaScript +presets: [ + SwaggerUIBundle.presets.apis, + SwaggerUIBundle.SwaggerUIStandalonePreset +] +``` + +These are **JavaScript** objects, not strings, so you can't pass them from Python code directly. + +If you need to use JavaScript-only configurations like those, you can use one of the methods above. Override all the Swagger UI *path operation* and manually write any JavaScript you need. diff --git a/docs/en/docs/how-to/custom-docs-ui-assets.md b/docs/en/docs/how-to/custom-docs-ui-assets.md new file mode 100644 index 0000000000000..9726be2c710e2 --- /dev/null +++ b/docs/en/docs/how-to/custom-docs-ui-assets.md @@ -0,0 +1,199 @@ +# Custom Docs UI Static Assets (Self-Hosting) + +The API docs use **Swagger UI** and **ReDoc**, and each of those need some JavaScript and CSS files. + +By default, those files are served from a CDN. + +But it's possible to customize it, you can set a specific CDN, or serve the files yourself. + +## Custom CDN for JavaScript and CSS + +Let's say that you want to use a different CDN, for example you want to use `https://unpkg.com/`. + +This could be useful if for example you live in a country that restricts some URLs. + +### Disable the automatic docs + +The first step is to disable the automatic docs, as by default, those use the default CDN. + +To disable them, set their URLs to `None` when creating your `FastAPI` app: + +```Python hl_lines="8" +{!../../../docs_src/custom_docs_ui/tutorial001.py!} +``` + +### Include the custom docs + +Now you can create the *path operations* for the custom docs. + +You can re-use FastAPI's internal functions to create the HTML pages for the docs, and pass them the needed arguments: + +* `openapi_url`: the URL where the HTML page for the docs can get the OpenAPI schema for your API. You can use here the attribute `app.openapi_url`. +* `title`: the title of your API. +* `oauth2_redirect_url`: you can use `app.swagger_ui_oauth2_redirect_url` here to use the default. +* `swagger_js_url`: the URL where the HTML for your Swagger UI docs can get the **JavaScript** file. This is the custom CDN URL. +* `swagger_css_url`: the URL where the HTML for your Swagger UI docs can get the **CSS** file. This is the custom CDN URL. + +And similarly for ReDoc... + +```Python hl_lines="2-6 11-19 22-24 27-33" +{!../../../docs_src/custom_docs_ui/tutorial001.py!} +``` + +!!! tip + The *path operation* for `swagger_ui_redirect` is a helper for when you use OAuth2. + + If you integrate your API with an OAuth2 provider, you will be able to authenticate and come back to the API docs with the acquired credentials. And interact with it using the real OAuth2 authentication. + + Swagger UI will handle it behind the scenes for you, but it needs this "redirect" helper. + +### Create a *path operation* to test it + +Now, to be able to test that everything works, create a *path operation*: + +```Python hl_lines="36-38" +{!../../../docs_src/custom_docs_ui/tutorial001.py!} +``` + +### Test it + +Now, you should be able to go to your docs at http://127.0.0.1:8000/docs, and reload the page, it will load those assets from the new CDN. + +## Self-hosting JavaScript and CSS for docs + +Self-hosting the JavaScript and CSS could be useful if, for example, you need your app to keep working even while offline, without open Internet access, or in a local network. + +Here you'll see how to serve those files yourself, in the same FastAPI app, and configure the docs to use them. + +### Project file structure + +Let's say your project file structure looks like this: + +``` +. +├── app +│ ├── __init__.py +│ ├── main.py +``` + +Now create a directory to store those static files. + +Your new file structure could look like this: + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +└── static/ +``` + +### Download the files + +Download the static files needed for the docs and put them on that `static/` directory. + +You can probably right-click each link and select an option similar to `Save link as...`. + +**Swagger UI** uses the files: + +* `swagger-ui-bundle.js` +* `swagger-ui.css` + +And **ReDoc** uses the file: + +* `redoc.standalone.js` + +After that, your file structure could look like: + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +└── static + ├── redoc.standalone.js + ├── swagger-ui-bundle.js + └── swagger-ui.css +``` + +### Serve the static files + +* Import `StaticFiles`. +* "Mount" a `StaticFiles()` instance in a specific path. + +```Python hl_lines="7 11" +{!../../../docs_src/custom_docs_ui/tutorial002.py!} +``` + +### Test the static files + +Start your application and go to http://127.0.0.1:8000/static/redoc.standalone.js. + +You should see a very long JavaScript file for **ReDoc**. + +It could start with something like: + +```JavaScript +/*! + * ReDoc - OpenAPI/Swagger-generated API Reference Documentation + * ------------------------------------------------------------- + * Version: "2.0.0-rc.18" + * Repo: https://github.com/Redocly/redoc + */ +!function(e,t){"object"==typeof exports&&"object"==typeof m + +... +``` + +That confirms that you are being able to serve static files from your app, and that you placed the static files for the docs in the correct place. + +Now we can configure the app to use those static files for the docs. + +### Disable the automatic docs for static files + +The same as when using a custom CDN, the first step is to disable the automatic docs, as those use the CDN by default. + +To disable them, set their URLs to `None` when creating your `FastAPI` app: + +```Python hl_lines="9" +{!../../../docs_src/custom_docs_ui/tutorial002.py!} +``` + +### Include the custom docs for static files + +And the same way as with a custom CDN, now you can create the *path operations* for the custom docs. + +Again, you can re-use FastAPI's internal functions to create the HTML pages for the docs, and pass them the needed arguments: + +* `openapi_url`: the URL where the HTML page for the docs can get the OpenAPI schema for your API. You can use here the attribute `app.openapi_url`. +* `title`: the title of your API. +* `oauth2_redirect_url`: you can use `app.swagger_ui_oauth2_redirect_url` here to use the default. +* `swagger_js_url`: the URL where the HTML for your Swagger UI docs can get the **JavaScript** file. **This is the one that your own app is now serving**. +* `swagger_css_url`: the URL where the HTML for your Swagger UI docs can get the **CSS** file. **This is the one that your own app is now serving**. + +And similarly for ReDoc... + +```Python hl_lines="2-6 14-22 25-27 30-36" +{!../../../docs_src/custom_docs_ui/tutorial002.py!} +``` + +!!! tip + The *path operation* for `swagger_ui_redirect` is a helper for when you use OAuth2. + + If you integrate your API with an OAuth2 provider, you will be able to authenticate and come back to the API docs with the acquired credentials. And interact with it using the real OAuth2 authentication. + + Swagger UI will handle it behind the scenes for you, but it needs this "redirect" helper. + +### Create a *path operation* to test static files + +Now, to be able to test that everything works, create a *path operation*: + +```Python hl_lines="39-41" +{!../../../docs_src/custom_docs_ui/tutorial002.py!} +``` + +### Test Static Files UI + +Now, you should be able to disconnect your WiFi, go to your docs at http://127.0.0.1:8000/docs, and reload the page. + +And even without Internet, you would be able to see the docs for your API and interact with it. diff --git a/docs/en/docs/advanced/custom-request-and-route.md b/docs/en/docs/how-to/custom-request-and-route.md similarity index 100% rename from docs/en/docs/advanced/custom-request-and-route.md rename to docs/en/docs/how-to/custom-request-and-route.md diff --git a/docs/en/docs/how-to/extending-openapi.md b/docs/en/docs/how-to/extending-openapi.md new file mode 100644 index 0000000000000..a18fd737e6b4e --- /dev/null +++ b/docs/en/docs/how-to/extending-openapi.md @@ -0,0 +1,87 @@ +# Extending OpenAPI + +There are some cases where you might need to modify the generated OpenAPI schema. + +In this section you will see how. + +## The normal process + +The normal (default) process, is as follows. + +A `FastAPI` application (instance) has an `.openapi()` method that is expected to return the OpenAPI schema. + +As part of the application object creation, a *path operation* for `/openapi.json` (or for whatever you set your `openapi_url`) is registered. + +It just returns a JSON response with the result of the application's `.openapi()` method. + +By default, what the method `.openapi()` does is check the property `.openapi_schema` to see if it has contents and return them. + +If it doesn't, it generates them using the utility function at `fastapi.openapi.utils.get_openapi`. + +And that function `get_openapi()` receives as parameters: + +* `title`: The OpenAPI title, shown in the docs. +* `version`: The version of your API, e.g. `2.5.0`. +* `openapi_version`: The version of the OpenAPI specification used. By default, the latest: `3.1.0`. +* `summary`: A short summary of the API. +* `description`: The description of your API, this can include markdown and will be shown in the docs. +* `routes`: A list of routes, these are each of the registered *path operations*. They are taken from `app.routes`. + +!!! info + The parameter `summary` is available in OpenAPI 3.1.0 and above, supported by FastAPI 0.99.0 and above. + +## Overriding the defaults + +Using the information above, you can use the same utility function to generate the OpenAPI schema and override each part that you need. + +For example, let's add ReDoc's OpenAPI extension to include a custom logo. + +### Normal **FastAPI** + +First, write all your **FastAPI** application as normally: + +```Python hl_lines="1 4 7-9" +{!../../../docs_src/extending_openapi/tutorial001.py!} +``` + +### Generate the OpenAPI schema + +Then, use the same utility function to generate the OpenAPI schema, inside a `custom_openapi()` function: + +```Python hl_lines="2 15-21" +{!../../../docs_src/extending_openapi/tutorial001.py!} +``` + +### Modify the OpenAPI schema + +Now you can add the ReDoc extension, adding a custom `x-logo` to the `info` "object" in the OpenAPI schema: + +```Python hl_lines="22-24" +{!../../../docs_src/extending_openapi/tutorial001.py!} +``` + +### Cache the OpenAPI schema + +You can use the property `.openapi_schema` as a "cache", to store your generated schema. + +That way, your application won't have to generate the schema every time a user opens your API docs. + +It will be generated only once, and then the same cached schema will be used for the next requests. + +```Python hl_lines="13-14 25-26" +{!../../../docs_src/extending_openapi/tutorial001.py!} +``` + +### Override the method + +Now you can replace the `.openapi()` method with your new function. + +```Python hl_lines="29" +{!../../../docs_src/extending_openapi/tutorial001.py!} +``` + +### Check it + +Once you go to http://127.0.0.1:8000/redoc you will see that you are using your custom logo (in this example, **FastAPI**'s logo): + + diff --git a/docs/en/docs/how-to/general.md b/docs/en/docs/how-to/general.md new file mode 100644 index 0000000000000..04367c6b76353 --- /dev/null +++ b/docs/en/docs/how-to/general.md @@ -0,0 +1,39 @@ +# General - How To - Recipes + +Here are several pointers to other places in the docs, for general or frequent questions. + +## Filter Data - Security + +To ensure that you don't return more data than you should, read the docs for [Tutorial - Response Model - Return Type](../tutorial/response-model.md){.internal-link target=_blank}. + +## Documentation Tags - OpenAPI + +To add tags to your *path operations*, and group them in the docs UI, read the docs for [Tutorial - Path Operation Configurations - Tags](../tutorial/path-operation-configuration.md#tags){.internal-link target=_blank}. + +## Documentation Summary and Description - OpenAPI + +To add a summary and description to your *path operations*, and show them in the docs UI, read the docs for [Tutorial - Path Operation Configurations - Summary and Description](../tutorial/path-operation-configuration.md#summary-and-description){.internal-link target=_blank}. + +## Documentation Response description - OpenAPI + +To define the description of the response, shown in the docs UI, read the docs for [Tutorial - Path Operation Configurations - Response description](../tutorial/path-operation-configuration.md#response-description){.internal-link target=_blank}. + +## Documentation Deprecate a *Path Operation* - OpenAPI + +To deprecate a *path operation*, and show it in the docs UI, read the docs for [Tutorial - Path Operation Configurations - Deprecation](../tutorial/path-operation-configuration.md#deprecate-a-path-operation){.internal-link target=_blank}. + +## Convert any Data to JSON-compatible + +To convert any data to JSON-compatible, read the docs for [Tutorial - JSON Compatible Encoder](../tutorial/encoder.md){.internal-link target=_blank}. + +## OpenAPI Metadata - Docs + +To add metadata to your OpenAPI schema, including a license, version, contact, etc, read the docs for [Tutorial - Metadata and Docs URLs](../tutorial/metadata.md){.internal-link target=_blank}. + +## OpenAPI Custom URL + +To customize the OpenAPI URL (or remove it), read the docs for [Tutorial - Metadata and Docs URLs](../tutorial/metadata.md#openapi-url){.internal-link target=_blank}. + +## OpenAPI Docs URLs + +To update the URLs used for the automatically generated docs user interfaces, read the docs for [Tutorial - Metadata and Docs URLs](../tutorial/metadata.md#docs-urls){.internal-link target=_blank}. diff --git a/docs/en/docs/advanced/graphql.md b/docs/en/docs/how-to/graphql.md similarity index 100% rename from docs/en/docs/advanced/graphql.md rename to docs/en/docs/how-to/graphql.md diff --git a/docs/en/docs/how-to/index.md b/docs/en/docs/how-to/index.md new file mode 100644 index 0000000000000..ec7fd38f8f277 --- /dev/null +++ b/docs/en/docs/how-to/index.md @@ -0,0 +1,11 @@ +# How To - Recipes + +Here you will see different recipes or "how to" guides for **several topics**. + +Most of these ideas would be more or less **independent**, and in most cases you should only need to study them if they apply directly to **your project**. + +If something seems interesting and useful to your project, go ahead and check it, but otherwise, you might probably just skip them. + +!!! tip + + If you want to **learn FastAPI** in a structured way (recommended), go and read the [Tutorial - User Guide](../tutorial/index.md){.internal-link target=_blank} chapter by chapter instead. diff --git a/docs/en/docs/advanced/nosql-databases.md b/docs/en/docs/how-to/nosql-databases-couchbase.md similarity index 92% rename from docs/en/docs/advanced/nosql-databases.md rename to docs/en/docs/how-to/nosql-databases-couchbase.md index 6cc5a938575d2..563318984378d 100644 --- a/docs/en/docs/advanced/nosql-databases.md +++ b/docs/en/docs/how-to/nosql-databases-couchbase.md @@ -1,4 +1,14 @@ -# NoSQL (Distributed / Big Data) Databases +# ~~NoSQL (Distributed / Big Data) Databases with Couchbase~~ (deprecated) + +!!! info + These docs are about to be updated. 🎉 + + The current version assumes Pydantic v1. + + The new docs will hopefully use Pydantic v2 and will use ODMantic with MongoDB. + +!!! warning "Deprecated" + This tutorial is deprecated and will be removed in a future version. **FastAPI** can also be integrated with any NoSQL. diff --git a/docs/en/docs/how-to/separate-openapi-schemas.md b/docs/en/docs/how-to/separate-openapi-schemas.md new file mode 100644 index 0000000000000..10be1071a93a0 --- /dev/null +++ b/docs/en/docs/how-to/separate-openapi-schemas.md @@ -0,0 +1,231 @@ +# Separate OpenAPI Schemas for Input and Output or Not + +When using **Pydantic v2**, the generated OpenAPI is a bit more exact and **correct** than before. 😎 + +In fact, in some cases, it will even have **two JSON Schemas** in OpenAPI for the same Pydantic model, for input and output, depending on if they have **default values**. + +Let's see how that works and how to change it if you need to do that. + +## Pydantic Models for Input and Output + +Let's say you have a Pydantic model with default values, like this one: + +=== "Python 3.10+" + + ```Python hl_lines="7" + {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-7]!} + + # Code below omitted 👇 + ``` + +
+ 👀 Full file preview + + ```Python + {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} + ``` + +
+ +=== "Python 3.9+" + + ```Python hl_lines="9" + {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-9]!} + + # Code below omitted 👇 + ``` + +
+ 👀 Full file preview + + ```Python + {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} + ``` + +
+ +=== "Python 3.8+" + + ```Python hl_lines="9" + {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-9]!} + + # Code below omitted 👇 + ``` + +
+ 👀 Full file preview + + ```Python + {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} + ``` + +
+ +### Model for Input + +If you use this model as an input like here: + +=== "Python 3.10+" + + ```Python hl_lines="14" + {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-15]!} + + # Code below omitted 👇 + ``` + +
+ 👀 Full file preview + + ```Python + {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} + ``` + +
+ +=== "Python 3.9+" + + ```Python hl_lines="16" + {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-17]!} + + # Code below omitted 👇 + ``` + +
+ 👀 Full file preview + + ```Python + {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} + ``` + +
+ +=== "Python 3.8+" + + ```Python hl_lines="16" + {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-17]!} + + # Code below omitted 👇 + ``` + +
+ 👀 Full file preview + + ```Python + {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} + ``` + +
+ +...then the `description` field will **not be required**. Because it has a default value of `None`. + +### Input Model in Docs + +You can confirm that in the docs, the `description` field doesn't have a **red asterisk**, it's not marked as required: + +
+ +
+ +### Model for Output + +But if you use the same model as an output, like here: + +=== "Python 3.10+" + + ```Python hl_lines="19" + {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="21" + {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="21" + {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} + ``` + +...then because `description` has a default value, if you **don't return anything** for that field, it will still have that **default value**. + +### Model for Output Response Data + +If you interact with the docs and check the response, even though the code didn't add anything in one of the `description` fields, the JSON response contains the default value (`null`): + +
+ +
+ +This means that it will **always have a value**, it's just that sometimes the value could be `None` (or `null` in JSON). + +That means that, clients using your API don't have to check if the value exists or not, they can **assume the field will always be there**, but just that in some cases it will have the default value of `None`. + +The way to describe this in OpenAPI, is to mark that field as **required**, because it will always be there. + +Because of that, the JSON Schema for a model can be different depending on if it's used for **input or output**: + +* for **input** the `description` will **not be required** +* for **output** it will be **required** (and possibly `None`, or in JSON terms, `null`) + +### Model for Output in Docs + +You can check the output model in the docs too, **both** `name` and `description` are marked as **required** with a **red asterisk**: + +
+ +
+ +### Model for Input and Output in Docs + +And if you check all the available Schemas (JSON Schemas) in OpenAPI, you will see that there are two, one `Item-Input` and one `Item-Output`. + +For `Item-Input`, `description` is **not required**, it doesn't have a red asterisk. + +But for `Item-Output`, `description` is **required**, it has a red asterisk. + +
+ +
+ +With this feature from **Pydantic v2**, your API documentation is more **precise**, and if you have autogenerated clients and SDKs, they will be more precise too, with a better **developer experience** and consistency. 🎉 + +## Do not Separate Schemas + +Now, there are some cases where you might want to have the **same schema for input and output**. + +Probably the main use case for this is if you already have some autogenerated client code/SDKs and you don't want to update all the autogenerated client code/SDKs yet, you probably will want to do it at some point, but maybe not right now. + +In that case, you can disable this feature in **FastAPI**, with the parameter `separate_input_output_schemas=False`. + +!!! info + Support for `separate_input_output_schemas` was added in FastAPI `0.102.0`. 🤓 + +=== "Python 3.10+" + + ```Python hl_lines="10" + {!> ../../../docs_src/separate_openapi_schemas/tutorial002_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="12" + {!> ../../../docs_src/separate_openapi_schemas/tutorial002_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="12" + {!> ../../../docs_src/separate_openapi_schemas/tutorial002.py!} + ``` + +### Same Schema for Input and Output Models in Docs + +And now there will be one single schema for input and output for the model, only `Item`, and it will have `description` as **not required**: + +
+ +
+ +This is the same behavior as in Pydantic v1. 🤓 diff --git a/docs/en/docs/advanced/sql-databases-peewee.md b/docs/en/docs/how-to/sql-databases-peewee.md similarity index 96% rename from docs/en/docs/advanced/sql-databases-peewee.md rename to docs/en/docs/how-to/sql-databases-peewee.md index b4ea61367e820..7211f7ed3b7b7 100644 --- a/docs/en/docs/advanced/sql-databases-peewee.md +++ b/docs/en/docs/how-to/sql-databases-peewee.md @@ -1,10 +1,22 @@ -# SQL (Relational) Databases with Peewee +# ~~SQL (Relational) Databases with Peewee~~ (deprecated) + +!!! warning "Deprecated" + This tutorial is deprecated and will be removed in a future version. !!! warning If you are just starting, the tutorial [SQL (Relational) Databases](../tutorial/sql-databases.md){.internal-link target=_blank} that uses SQLAlchemy should be enough. Feel free to skip this. + Peewee is not recommended with FastAPI as it doesn't play well with anything async Python. There are several better alternatives. + +!!! info + These docs assume Pydantic v1. + + Because Pewee doesn't play well with anything async and there are better alternatives, I won't update these docs for Pydantic v2, they are kept for now only for historical purposes. + + The examples here are no longer tested in CI (as they were before). + If you are starting a project from scratch, you are probably better off with SQLAlchemy ORM ([SQL (Relational) Databases](../tutorial/sql-databases.md){.internal-link target=_blank}), or any other async ORM. If you already have a code base that uses Peewee ORM, you can check here how to use it with **FastAPI**. @@ -66,7 +78,7 @@ Let's first check all the normal Peewee code, create a Peewee database: ``` !!! tip - Have in mind that if you wanted to use a different database, like PostgreSQL, you couldn't just change the string. You would need to use a different Peewee database class. + Keep in mind that if you wanted to use a different database, like PostgreSQL, you couldn't just change the string. You would need to use a different Peewee database class. #### Note @@ -354,7 +366,7 @@ It will have the database connection open at the beginning and will just wait so This will easily let you test that your app with Peewee and FastAPI is behaving correctly with all the stuff about threads. -If you want to check how Peewee would break your app if used without modification, go the the `sql_app/database.py` file and comment the line: +If you want to check how Peewee would break your app if used without modification, go the `sql_app/database.py` file and comment the line: ```Python # db._state = PeeweeConnectionState() @@ -484,7 +496,7 @@ This means that, with Peewee's current implementation, multiple tasks could be u Python 3.7 has `contextvars` that can create a local variable very similar to `threading.local`, but also supporting these async features. -There are several things to have in mind. +There are several things to keep in mind. The `ContextVar` has to be created at the top of the module, like: diff --git a/docs/en/docs/img/favicon.png b/docs/en/docs/img/favicon.png old mode 100755 new mode 100644 index b3dcdd3090e52..e5b7c3ada7d09 Binary files a/docs/en/docs/img/favicon.png and b/docs/en/docs/img/favicon.png differ diff --git a/docs/en/docs/img/github-social-preview.png b/docs/en/docs/img/github-social-preview.png index a12cbcda56040..4c299c1d6a1ac 100644 Binary files a/docs/en/docs/img/github-social-preview.png and b/docs/en/docs/img/github-social-preview.png differ diff --git a/docs/en/docs/img/github-social-preview.svg b/docs/en/docs/img/github-social-preview.svg index 08450929e601c..f03a0eefde8e4 100644 --- a/docs/en/docs/img/github-social-preview.svg +++ b/docs/en/docs/img/github-social-preview.svg @@ -1,42 +1,15 @@ - + xmlns="http://www.w3.org/2000/svg" + xmlns:svg="http://www.w3.org/2000/svg" + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:cc="http://creativecommons.org/ns#" + xmlns:dc="http://purl.org/dc/elements/1.1/"> image/svg+xml - @@ -57,42 +29,47 @@ width="338.66666" height="169.33333" x="-1.0833333e-05" - y="0.71613133" - inkscape:export-xdpi="96" - inkscape:export-ydpi="96" /> + y="0.71613133" /> - + id="g2" + transform="matrix(0.73293148,0,0,0.73293148,42.286898,36.073041)"> + + + + FastAPI + style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Ubuntu;-inkscape-font-specification:Ubuntu;fill:#009688;fill-opacity:1;stroke-width:1.99288" + y="59.410606" + x="82.667519" + id="tspan977-7">FastAPI High performance, easy to learn,High performance, easy to learn,fast to code, ready for production diff --git a/docs/en/docs/img/icon-transparent-bg.png b/docs/en/docs/img/icon-transparent-bg.png deleted file mode 100644 index c3481da4ac551..0000000000000 Binary files a/docs/en/docs/img/icon-transparent-bg.png and /dev/null differ diff --git a/docs/en/docs/img/icon-white-bg.png b/docs/en/docs/img/icon-white-bg.png deleted file mode 100644 index 00888b5226bf0..0000000000000 Binary files a/docs/en/docs/img/icon-white-bg.png and /dev/null differ diff --git a/docs/en/docs/img/icon-white.svg b/docs/en/docs/img/icon-white.svg index cf7c0c7ecb184..19f0825cc245a 100644 --- a/docs/en/docs/img/icon-white.svg +++ b/docs/en/docs/img/icon-white.svg @@ -1,15 +1,15 @@ + width="6.3499999mm" + xmlns="http://www.w3.org/2000/svg" + xmlns:svg="http://www.w3.org/2000/svg" + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:cc="http://creativecommons.org/ns#" + xmlns:dc="http://purl.org/dc/elements/1.1/"> image/svg+xml - - - - - + + diff --git a/docs/en/docs/img/logo-margin/logo-teal-vector.svg b/docs/en/docs/img/logo-margin/logo-teal-vector.svg index 02183293ce2a6..3eb945c7e5ad7 100644 --- a/docs/en/docs/img/logo-margin/logo-teal-vector.svg +++ b/docs/en/docs/img/logo-margin/logo-teal-vector.svg @@ -1,15 +1,15 @@ + id="svg8" + xmlns="http://www.w3.org/2000/svg" + xmlns:svg="http://www.w3.org/2000/svg" + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:cc="http://creativecommons.org/ns#" + xmlns:dc="http://purl.org/dc/elements/1.1/"> image/svg+xml - + + + + + - - - - - - - - - - - + transform="translate(83.131114,-6.0791148)" /> diff --git a/docs/en/docs/img/logo-margin/logo-teal.png b/docs/en/docs/img/logo-margin/logo-teal.png index 57d9eec137c04..f08144cd92e7a 100644 Binary files a/docs/en/docs/img/logo-margin/logo-teal.png and b/docs/en/docs/img/logo-margin/logo-teal.png differ diff --git a/docs/en/docs/img/logo-margin/logo-teal.svg b/docs/en/docs/img/logo-margin/logo-teal.svg index 2fad25ef7ed89..ce9db533b0e76 100644 --- a/docs/en/docs/img/logo-margin/logo-teal.svg +++ b/docs/en/docs/img/logo-margin/logo-teal.svg @@ -1,15 +1,15 @@ + id="svg8" + xmlns="http://www.w3.org/2000/svg" + xmlns:svg="http://www.w3.org/2000/svg" + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:cc="http://creativecommons.org/ns#" + xmlns:dc="http://purl.org/dc/elements/1.1/"> image/svg+xml - + + + + + + + - - FastAPI - + transform="translate(83.131114,-6.0791148)" /> diff --git a/docs/en/docs/img/logo-margin/logo-white-bg.png b/docs/en/docs/img/logo-margin/logo-white-bg.png index 89256db06f02e..b84fd285ee52d 100644 Binary files a/docs/en/docs/img/logo-margin/logo-white-bg.png and b/docs/en/docs/img/logo-margin/logo-white-bg.png differ diff --git a/docs/en/docs/img/logo-teal-vector.svg b/docs/en/docs/img/logo-teal-vector.svg index c1d1b72e44ba3..d3dad4bec8b31 100644 --- a/docs/en/docs/img/logo-teal-vector.svg +++ b/docs/en/docs/img/logo-teal-vector.svg @@ -1,15 +1,15 @@ + viewBox="0 0 346.52395 63.977134" + height="63.977139mm" + width="346.52396mm" + xmlns="http://www.w3.org/2000/svg" + xmlns:svg="http://www.w3.org/2000/svg" + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:cc="http://creativecommons.org/ns#" + xmlns:dc="http://purl.org/dc/elements/1.1/"> image/svg+xml - - + id="g2149"> - - - - - - + id="g2141"> + + + + + style="font-size:79.7151px;line-height:1.25;font-family:Ubuntu;-inkscape-font-specification:Ubuntu;letter-spacing:0px;word-spacing:0px;fill:#009688;stroke-width:1.99288" + d="M 89.523017,59.410606 V 4.1680399 H 122.84393 V 10.784393 H 97.255382 V 27.44485 h 22.718808 v 6.536638 H 97.255382 v 25.429118 z m 52.292963,-5.340912 q 2.6306,0 4.62348,-0.07972 2.07259,-0.15943 3.42774,-0.47829 V 41.155848 q -0.79715,-0.398576 -2.63059,-0.637721 -1.75374,-0.31886 -4.30462,-0.31886 -1.67402,0 -3.58718,0.239145 -1.83345,0.239145 -3.42775,1.036296 -1.51459,0.717436 -2.55088,2.072593 -1.0363,1.275442 -1.0363,3.427749 0,3.985755 2.55089,5.580058 2.55088,1.514586 6.93521,1.514586 z m -0.63772,-37.147238 q 4.46404,0 7.49322,1.195727 3.10889,1.116011 4.94233,3.268319 1.91317,2.072593 2.71032,5.022052 0.79715,2.869743 0.79715,6.377208 V 58.69317 q -0.95658,0.159431 -2.71031,0.478291 -1.67402,0.239145 -3.82633,0.478291 -2.15231,0.239145 -4.70319,0.398575 -2.47117,0.239146 -4.94234,0.239146 -3.50746,0 -6.45692,-0.717436 -2.94946,-0.717436 -5.10177,-2.232023 -2.1523,-1.594302 -3.34803,-4.145186 -1.19573,-2.550883 -1.19573,-6.138063 0,-3.427749 1.35516,-5.898917 1.43487,-2.471168 3.82632,-3.985755 2.39146,-1.514587 5.58006,-2.232023 3.18861,-0.717436 6.69607,-0.717436 1.11601,0 2.31174,0.15943 1.19572,0.07972 2.23202,0.31886 1.11601,0.159431 1.91316,0.318861 0.79715,0.15943 1.11601,0.239145 v -2.072593 q 0,-1.833447 -0.39857,-3.587179 -0.39858,-1.833448 -1.43487,-3.188604 -1.0363,-1.434872 -2.86975,-2.232023 -1.75373,-0.876866 -4.62347,-0.876866 -3.6669,0 -6.45693,0.558005 -2.71031,0.478291 -4.06547,1.036297 l -0.87686,-6.138063 q 1.43487,-0.637721 4.7829,-1.195727 3.34804,-0.637721 7.25408,-0.637721 z m 37.86462,37.147238 q 4.54377,0 6.69607,-1.195726 2.23203,-1.195727 2.23203,-3.826325 0,-2.710314 -2.15231,-4.304616 -2.15231,-1.594302 -7.09465,-3.587179 -2.39145,-0.956581 -4.62347,-1.913163 -2.15231,-1.036296 -3.74661,-2.391453 -1.5943,-1.355157 -2.55088,-3.268319 -0.95659,-1.913163 -0.95659,-4.703191 0,-5.500342 4.06547,-8.688946 4.06547,-3.26832 11.0804,-3.26832 1.75374,0 3.50747,0.239146 1.75373,0.15943 3.26832,0.47829 1.51458,0.239146 2.6306,0.558006 1.19572,0.31886 1.83344,0.558006 l -1.35515,6.377208 q -1.19573,-0.637721 -3.74661,-1.275442 -2.55089,-0.717436 -6.13807,-0.717436 -3.10889,0 -5.42062,1.275442 -2.31174,1.195727 -2.31174,3.826325 0,1.355157 0.47829,2.391453 0.55801,1.036296 1.5943,1.913163 1.11601,0.797151 2.71031,1.514587 1.59431,0.717436 3.82633,1.514587 2.94946,1.116011 5.2612,2.232022 2.31173,1.036297 3.90604,2.471169 1.67401,1.434871 2.55088,3.507464 0.87687,1.992878 0.87687,4.942337 0,5.739487 -4.30462,8.688946 -4.2249,2.949459 -12.1167,2.949459 -5.50034,0 -8.60923,-0.956582 -3.10889,-0.876866 -4.2249,-1.355156 l 1.35516,-6.377209 q 1.27544,0.478291 4.06547,1.434872 2.79003,0.956581 7.4135,0.956581 z m 32.84256,-36.110941 h 15.70387 v 6.217778 h -15.70387 v 19.131625 q 0,3.108889 0.47829,5.181481 0.47829,1.992878 1.43487,3.188604 0.95658,1.116012 2.39145,1.594302 1.43487,0.478291 3.34804,0.478291 3.34803,0 5.34091,-0.717436 2.07259,-0.797151 2.86974,-1.116011 l 1.43487,6.138063 q -1.11601,0.558005 -3.90604,1.355156 -2.79003,0.876867 -6.37721,0.876867 -4.2249,0 -7.01492,-1.036297 -2.71032,-1.116011 -4.38434,-3.268319 -1.67401,-2.152308 -2.39145,-5.261197 -0.63772,-3.188604 -0.63772,-7.333789 V 6.4000628 l 7.41351,-1.2754417 z m 62.49652,41.451853 q -1.35516,-3.587179 -2.55088,-7.014929 -1.19573,-3.507464 -2.47117,-7.094644 h -25.03054 l -5.02205,14.109573 h -8.05123 q 3.18861,-8.768661 5.97863,-16.182166 2.79003,-7.493219 5.42063,-14.189288 2.71031,-6.696069 5.34091,-12.754416 2.6306,-6.138063 5.50034,-12.1166961 h 7.09465 q 2.86974,5.9786331 5.50034,12.1166961 2.6306,6.058347 5.2612,12.754416 2.71031,6.696069 5.50034,14.189288 2.79003,7.413505 5.97863,16.182166 z m -7.25407,-20.486781 q -2.55089,-6.935214 -5.10177,-13.392137 -2.47117,-6.536639 -5.18148,-12.515272 -2.79003,5.978633 -5.34091,12.515272 -2.47117,6.456923 -4.94234,13.392137 z M 304.99242,3.6100342 q 11.6384,0 17.85618,4.4640458 6.29749,4.384331 6.29749,13.152992 0,4.782906 -1.75373,8.210656 -1.67402,3.348034 -4.94234,5.500342 -3.1886,2.072592 -7.81208,3.029174 -4.62347,0.956581 -10.44268,0.956581 h -6.13806 v 20.486781 h -7.73236 V 4.9651909 q 3.26832,-0.797151 7.25407,-1.0362963 4.06547,-0.3188604 7.41351,-0.3188604 z m 0.63772,6.7757838 q -4.94234,0 -7.57294,0.239145 v 21.682508 h 5.8192 q 3.98576,0 7.17436,-0.47829 3.18861,-0.558006 5.34092,-1.753733 2.23202,-1.275441 3.42774,-3.427749 1.19573,-2.152308 1.19573,-5.500342 0,-3.188604 -1.27544,-5.261197 -1.19573,-2.072593 -3.34803,-3.268319 -2.0726,-1.275442 -4.86263,-1.753732 -2.79002,-0.478291 -5.89891,-0.478291 z M 338.7916,4.1680399 h 7.73237 V 59.410606 h -7.73237 z" + id="text979" + aria-label="FastAPI" /> diff --git a/docs/en/docs/img/logo-teal.svg b/docs/en/docs/img/logo-teal.svg index 0d1136eb4dcab..bc699860fc478 100644 --- a/docs/en/docs/img/logo-teal.svg +++ b/docs/en/docs/img/logo-teal.svg @@ -1,15 +1,15 @@ + width="346.52396mm" + xmlns="http://www.w3.org/2000/svg" + xmlns:svg="http://www.w3.org/2000/svg" + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:cc="http://creativecommons.org/ns#" + xmlns:dc="http://purl.org/dc/elements/1.1/"> image/svg+xml - - - FastAPI + id="g2149"> + + + + + + FastAPI + diff --git a/docs/en/docs/img/sponsors/bump-sh-banner.png b/docs/en/docs/img/sponsors/bump-sh-banner.png new file mode 100755 index 0000000000000..e75c0facd30ac Binary files /dev/null and b/docs/en/docs/img/sponsors/bump-sh-banner.png differ diff --git a/docs/en/docs/img/sponsors/bump-sh-banner.svg b/docs/en/docs/img/sponsors/bump-sh-banner.svg new file mode 100644 index 0000000000000..c8ec7675a7df5 --- /dev/null +++ b/docs/en/docs/img/sponsors/bump-sh-banner.svg @@ -0,0 +1,48 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/en/docs/img/sponsors/bump-sh.png b/docs/en/docs/img/sponsors/bump-sh.png new file mode 100755 index 0000000000000..61817e86fa106 Binary files /dev/null and b/docs/en/docs/img/sponsors/bump-sh.png differ diff --git a/docs/en/docs/img/sponsors/bump-sh.svg b/docs/en/docs/img/sponsors/bump-sh.svg new file mode 100644 index 0000000000000..053e54b1da4fb --- /dev/null +++ b/docs/en/docs/img/sponsors/bump-sh.svg @@ -0,0 +1,56 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/en/docs/img/sponsors/codacy.png b/docs/en/docs/img/sponsors/codacy.png new file mode 100644 index 0000000000000..baa615c2a8364 Binary files /dev/null and b/docs/en/docs/img/sponsors/codacy.png differ diff --git a/docs/en/docs/img/sponsors/coherence-banner.png b/docs/en/docs/img/sponsors/coherence-banner.png new file mode 100644 index 0000000000000..1d495965920e7 Binary files /dev/null and b/docs/en/docs/img/sponsors/coherence-banner.png differ diff --git a/docs/en/docs/img/sponsors/coherence.png b/docs/en/docs/img/sponsors/coherence.png new file mode 100644 index 0000000000000..d48c4edc4df96 Binary files /dev/null and b/docs/en/docs/img/sponsors/coherence.png differ diff --git a/docs/en/docs/img/sponsors/fern-banner.png b/docs/en/docs/img/sponsors/fern-banner.png new file mode 100644 index 0000000000000..1b70ab96d9548 Binary files /dev/null and b/docs/en/docs/img/sponsors/fern-banner.png differ diff --git a/docs/en/docs/img/sponsors/fern-banner.svg b/docs/en/docs/img/sponsors/fern-banner.svg new file mode 100644 index 0000000000000..e05ccc3a47aec --- /dev/null +++ b/docs/en/docs/img/sponsors/fern-banner.svg @@ -0,0 +1 @@ + diff --git a/docs/en/docs/img/sponsors/fern.png b/docs/en/docs/img/sponsors/fern.png new file mode 100644 index 0000000000000..4c6e54b0d517f Binary files /dev/null and b/docs/en/docs/img/sponsors/fern.png differ diff --git a/docs/en/docs/img/sponsors/fern.svg b/docs/en/docs/img/sponsors/fern.svg new file mode 100644 index 0000000000000..ad3842fe03eae --- /dev/null +++ b/docs/en/docs/img/sponsors/fern.svg @@ -0,0 +1 @@ + diff --git a/docs/en/docs/img/sponsors/mongodb-banner.png b/docs/en/docs/img/sponsors/mongodb-banner.png new file mode 100755 index 0000000000000..25bc85eaae908 Binary files /dev/null and b/docs/en/docs/img/sponsors/mongodb-banner.png differ diff --git a/docs/en/docs/img/sponsors/mongodb.png b/docs/en/docs/img/sponsors/mongodb.png new file mode 100755 index 0000000000000..113ca478582b2 Binary files /dev/null and b/docs/en/docs/img/sponsors/mongodb.png differ diff --git a/docs/en/docs/img/sponsors/porter-banner.png b/docs/en/docs/img/sponsors/porter-banner.png new file mode 100755 index 0000000000000..fa2e741c0cbb3 Binary files /dev/null and b/docs/en/docs/img/sponsors/porter-banner.png differ diff --git a/docs/en/docs/img/sponsors/porter.png b/docs/en/docs/img/sponsors/porter.png new file mode 100755 index 0000000000000..582a15156470b Binary files /dev/null and b/docs/en/docs/img/sponsors/porter.png differ diff --git a/docs/en/docs/img/sponsors/propelauth-banner.png b/docs/en/docs/img/sponsors/propelauth-banner.png new file mode 100644 index 0000000000000..7a1bb2580395a Binary files /dev/null and b/docs/en/docs/img/sponsors/propelauth-banner.png differ diff --git a/docs/en/docs/img/sponsors/propelauth.png b/docs/en/docs/img/sponsors/propelauth.png new file mode 100644 index 0000000000000..8234d631f6b67 Binary files /dev/null and b/docs/en/docs/img/sponsors/propelauth.png differ diff --git a/docs/en/docs/img/sponsors/reflex-banner.png b/docs/en/docs/img/sponsors/reflex-banner.png new file mode 100644 index 0000000000000..3095c3a7b4090 Binary files /dev/null and b/docs/en/docs/img/sponsors/reflex-banner.png differ diff --git a/docs/en/docs/img/sponsors/reflex.png b/docs/en/docs/img/sponsors/reflex.png new file mode 100644 index 0000000000000..59c46a1104140 Binary files /dev/null and b/docs/en/docs/img/sponsors/reflex.png differ diff --git a/docs/en/docs/img/sponsors/scalar-banner.svg b/docs/en/docs/img/sponsors/scalar-banner.svg new file mode 100644 index 0000000000000..bab74e2d7c0e3 --- /dev/null +++ b/docs/en/docs/img/sponsors/scalar-banner.svg @@ -0,0 +1 @@ + diff --git a/docs/en/docs/img/sponsors/scalar.svg b/docs/en/docs/img/sponsors/scalar.svg new file mode 100644 index 0000000000000..174c57ee23c3e --- /dev/null +++ b/docs/en/docs/img/sponsors/scalar.svg @@ -0,0 +1 @@ + diff --git a/docs/en/docs/img/sponsors/speakeasy.png b/docs/en/docs/img/sponsors/speakeasy.png new file mode 100644 index 0000000000000..001b4b4caffe2 Binary files /dev/null and b/docs/en/docs/img/sponsors/speakeasy.png differ diff --git a/docs/en/docs/img/sponsors/talkpython-v2.jpg b/docs/en/docs/img/sponsors/talkpython-v2.jpg new file mode 100644 index 0000000000000..adb0152489fa8 Binary files /dev/null and b/docs/en/docs/img/sponsors/talkpython-v2.jpg differ diff --git a/docs/en/docs/img/tutorial/metadata/image01.png b/docs/en/docs/img/tutorial/metadata/image01.png index b7708a3fd98ad..4146a8607b5b4 100644 Binary files a/docs/en/docs/img/tutorial/metadata/image01.png and b/docs/en/docs/img/tutorial/metadata/image01.png differ diff --git a/docs/en/docs/img/tutorial/openapi-webhooks/image01.png b/docs/en/docs/img/tutorial/openapi-webhooks/image01.png new file mode 100644 index 0000000000000..25ced48186d83 Binary files /dev/null and b/docs/en/docs/img/tutorial/openapi-webhooks/image01.png differ diff --git a/docs/en/docs/img/tutorial/separate-openapi-schemas/image01.png b/docs/en/docs/img/tutorial/separate-openapi-schemas/image01.png new file mode 100644 index 0000000000000..aa085f88df45e Binary files /dev/null and b/docs/en/docs/img/tutorial/separate-openapi-schemas/image01.png differ diff --git a/docs/en/docs/img/tutorial/separate-openapi-schemas/image02.png b/docs/en/docs/img/tutorial/separate-openapi-schemas/image02.png new file mode 100644 index 0000000000000..672ef1d2b71df Binary files /dev/null and b/docs/en/docs/img/tutorial/separate-openapi-schemas/image02.png differ diff --git a/docs/en/docs/img/tutorial/separate-openapi-schemas/image03.png b/docs/en/docs/img/tutorial/separate-openapi-schemas/image03.png new file mode 100644 index 0000000000000..81340fbece942 Binary files /dev/null and b/docs/en/docs/img/tutorial/separate-openapi-schemas/image03.png differ diff --git a/docs/en/docs/img/tutorial/separate-openapi-schemas/image04.png b/docs/en/docs/img/tutorial/separate-openapi-schemas/image04.png new file mode 100644 index 0000000000000..fc2302aa77ce2 Binary files /dev/null and b/docs/en/docs/img/tutorial/separate-openapi-schemas/image04.png differ diff --git a/docs/en/docs/img/tutorial/separate-openapi-schemas/image05.png b/docs/en/docs/img/tutorial/separate-openapi-schemas/image05.png new file mode 100644 index 0000000000000..674dd0b2e2730 Binary files /dev/null and b/docs/en/docs/img/tutorial/separate-openapi-schemas/image05.png differ diff --git a/docs/en/docs/index.md b/docs/en/docs/index.md index afd6d7138f0a8..86b0c699b7ea6 100644 --- a/docs/en/docs/index.md +++ b/docs/en/docs/index.md @@ -1,3 +1,12 @@ +--- +hide: + - navigation +--- + + +

FastAPI

@@ -27,7 +36,7 @@ --- -FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints. +FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.8+ based on standard Python type hints. The key features are: @@ -115,12 +124,12 @@ If you are building a CLI app to be ## Requirements -Python 3.7+ +Python 3.8+ FastAPI stands on the shoulders of giants: * Starlette for the web parts. -* Pydantic for the data parts. +* Pydantic for the data parts. ## Installation @@ -331,7 +340,7 @@ 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+**. +Just standard **Python 3.8+**. For example, for an `int`: @@ -446,12 +455,14 @@ To understand more about it, see the section email_validator - for email validation. +* pydantic-settings - for settings management. +* pydantic-extra-types - for extra types to be used with Pydantic. 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()`. +* 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`. diff --git a/docs/en/docs/js/chat.js b/docs/en/docs/js/chat.js deleted file mode 100644 index debdef4dad5d0..0000000000000 --- a/docs/en/docs/js/chat.js +++ /dev/null @@ -1,3 +0,0 @@ -((window.gitter = {}).chat = {}).options = { - room: 'tiangolo/fastapi' -}; diff --git a/docs/en/docs/learn/index.md b/docs/en/docs/learn/index.md new file mode 100644 index 0000000000000..d056fb320072c --- /dev/null +++ b/docs/en/docs/learn/index.md @@ -0,0 +1,5 @@ +# Learn + +Here are the introductory sections and the tutorials to learn **FastAPI**. + +You could consider this a **book**, a **course**, the **official** and recommended way to learn FastAPI. 😎 diff --git a/docs/en/docs/project-generation.md b/docs/en/docs/project-generation.md index 8ba34fa11200d..d142862ee8317 100644 --- a/docs/en/docs/project-generation.md +++ b/docs/en/docs/project-generation.md @@ -1,84 +1,27 @@ -# 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 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. - -## Full Stack FastAPI PostgreSQL - -GitHub: https://github.com/tiangolo/full-stack-fastapi-postgresql - -### Full Stack FastAPI PostgreSQL - Features - -* Full **Docker** integration (Docker based). -* Docker Swarm Mode deployment. -* **Docker Compose** integration and optimization for local development. -* **Production ready** Python web server using Uvicorn and Gunicorn. -* Python **FastAPI** backend: - * **Fast**: Very high performance, on par with **NodeJS** and **Go** (thanks to Starlette and Pydantic). - * **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. - * **Robust**: Get production-ready code. With automatic interactive documentation. - * **Standards-based**: Based on (and fully compatible with) the open standards for APIs: OpenAPI and JSON Schema. - * **Many other features** including automatic validation, serialization, interactive documentation, authentication with OAuth2 JWT tokens, etc. -* **Secure password** hashing by default. -* **JWT token** authentication. -* **SQLAlchemy** models (independent of Flask extensions, so they can be used with Celery workers directly). -* Basic starting models for users (modify and remove as you need). -* **Alembic** migrations. -* **CORS** (Cross Origin Resource Sharing). -* **Celery** worker that can import and use models and code from the rest of the backend selectively. -* REST backend tests based on **Pytest**, integrated with Docker, so you can test the full API interaction, independent on the database. As it runs in Docker, it can build a new data store from scratch each time (so you can use ElasticSearch, MongoDB, CouchDB, or whatever you want, and just test that the API works). -* Easy Python integration with **Jupyter Kernels** for remote or in-Docker development with extensions like Atom Hydrogen or Visual Studio Code Jupyter. -* **Vue** frontend: - * Generated with Vue CLI. - * **JWT Authentication** handling. - * Login view. - * After login, main dashboard view. - * Main dashboard with user creation and edition. - * Self user edition. - * **Vuex**. - * **Vue-router**. - * **Vuetify** for beautiful material design components. - * **TypeScript**. - * Docker server based on **Nginx** (configured to play nicely with Vue-router). - * Docker multi-stage building, so you don't need to save or commit compiled code. - * Frontend tests ran at build time (can be disabled too). - * Made as modular as possible, so it works out of the box, but you can re-generate with Vue CLI or create it as you need, and re-use what you want. -* **PGAdmin** for PostgreSQL database, you can modify it to use PHPMyAdmin and MySQL easily. -* **Flower** for Celery jobs monitoring. -* Load balancing between frontend and backend with **Traefik**, so you can have both under the same domain, separated by path, but served by different containers. -* Traefik integration, including Let's Encrypt **HTTPS** certificates automatic generation. -* GitLab **CI** (continuous integration), including frontend and backend testing. - -## Full Stack FastAPI Couchbase - -GitHub: https://github.com/tiangolo/full-stack-fastapi-couchbase - -⚠️ **WARNING** ⚠️ - -If you are starting a new project from scratch, check the alternatives here. - -For example, the project generator Full Stack FastAPI PostgreSQL might be a better alternative, as it is actively maintained and used. And it includes all the new features and improvements. - -You are still free to use the Couchbase-based generator if you want to, it should probably still work fine, and if you already have a project generated with it that's fine as well (and you probably already updated it to suit your needs). - -You can read more about it in the docs for the repo. - -## Full Stack FastAPI MongoDB - -...might come later, depending on my time availability and other factors. 😅 🎉 - -## Machine Learning models with spaCy and FastAPI - -GitHub: https://github.com/microsoft/cookiecutter-spacy-fastapi - -### Machine Learning models with spaCy and FastAPI - Features - -* **spaCy** NER model integration. -* **Azure Cognitive Search** request format built in. -* **Production ready** Python web server using Uvicorn and Gunicorn. -* **Azure DevOps** Kubernetes (AKS) CI/CD deployment built in. -* **Multilingual** Easily choose one of spaCy's built in languages during project setup. -* **Easily extensible** to other model frameworks (Pytorch, Tensorflow), not just spaCy. +# Full Stack FastAPI Template + +Templates, while typically come with a specific setup, are designed to be flexible and customizable. This allows you to modify and adapt them to your project's requirements, making them an excellent starting point. 🏁 + +You can use this template to get started, as it includes a lot of the initial set up, security, database and some API endpoints already done for you. + +GitHub Repository: Full Stack FastAPI Template + +## Full Stack FastAPI Template - Technology Stack and Features + +- ⚡ [**FastAPI**](https://fastapi.tiangolo.com) for the Python backend API. + - 🧰 [SQLModel](https://sqlmodel.tiangolo.com) for the Python SQL database interactions (ORM). + - 🔍 [Pydantic](https://docs.pydantic.dev), used by FastAPI, for the data validation and settings management. + - 💾 [PostgreSQL](https://www.postgresql.org) as the SQL database. +- 🚀 [React](https://react.dev) for the frontend. + - 💃 Using TypeScript, hooks, Vite, and other parts of a modern frontend stack. + - 🎨 [Chakra UI](https://chakra-ui.com) for the frontend components. + - 🤖 An automatically generated frontend client. + - 🦇 Dark mode support. +- 🐋 [Docker Compose](https://www.docker.com) for development and production. +- 🔒 Secure password hashing by default. +- 🔑 JWT token authentication. +- 📫 Email based password recovery. +- ✅ Tests with [Pytest](https://pytest.org). +- 📞 [Traefik](https://traefik.io) as a reverse proxy / load balancer. +- 🚢 Deployment instructions using Docker Compose, including how to set up a frontend Traefik proxy to handle automatic HTTPS certificates. +- 🏭 CI (continuous integration) and CD (continuous deployment) based on GitHub Actions. diff --git a/docs/en/docs/python-types.md b/docs/en/docs/python-types.md index 693613a36fa8d..51db744ff5a9b 100644 --- a/docs/en/docs/python-types.md +++ b/docs/en/docs/python-types.md @@ -182,7 +182,7 @@ For example, let's define a variable to be a `list` of `str`. {!> ../../../docs_src/python_types/tutorial006_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" From `typing`, import `List` (with a capital `L`): @@ -230,7 +230,7 @@ You would do the same to declare `tuple`s and `set`s: {!> ../../../docs_src/python_types/tutorial007_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="1 4" {!> ../../../docs_src/python_types/tutorial007.py!} @@ -255,7 +255,7 @@ The second type parameter is for the values of the `dict`: {!> ../../../docs_src/python_types/tutorial008_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="1 4" {!> ../../../docs_src/python_types/tutorial008.py!} @@ -281,7 +281,7 @@ In Python 3.10 there's also a **new syntax** where you can put the possible type {!> ../../../docs_src/python_types/tutorial008b_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="1 4" {!> ../../../docs_src/python_types/tutorial008b.py!} @@ -311,13 +311,13 @@ This also means that in Python 3.10, you can use `Something | None`: {!> ../../../docs_src/python_types/tutorial009_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="1 4" {!> ../../../docs_src/python_types/tutorial009.py!} ``` -=== "Python 3.6+ alternative" +=== "Python 3.8+ alternative" ```Python hl_lines="1 4" {!> ../../../docs_src/python_types/tutorial009b.py!} @@ -375,10 +375,10 @@ These types that take type parameters in square brackets are called **Generic ty * `set` * `dict` - And the same as with Python 3.6, from the `typing` module: + And the same as with Python 3.8, from the `typing` module: * `Union` - * `Optional` (the same as with Python 3.6) + * `Optional` (the same as with Python 3.8) * ...and others. In Python 3.10, as an alternative to using the generics `Union` and `Optional`, you can use the vertical bar (`|`) to declare unions of types, that's a lot better and simpler. @@ -392,13 +392,13 @@ These types that take type parameters in square brackets are called **Generic ty * `set` * `dict` - And the same as with Python 3.6, from the `typing` module: + And the same as with Python 3.8, from the `typing` module: * `Union` * `Optional` * ...and others. -=== "Python 3.6+" +=== "Python 3.8+" * `List` * `Tuple` @@ -434,7 +434,7 @@ It doesn't mean "`one_person` is the **class** called `Person`". ## Pydantic models -Pydantic is a Python library to perform data validation. +Pydantic is a Python library to perform data validation. You declare the "shape" of the data as classes with attributes. @@ -458,21 +458,21 @@ An example from the official Pydantic docs: {!> ../../../docs_src/python_types/tutorial011_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python {!> ../../../docs_src/python_types/tutorial011.py!} ``` !!! info - To learn more about Pydantic, check its docs. + To learn more about Pydantic, check its docs. **FastAPI** is all based on Pydantic. You will see a lot more of all this in practice in the [Tutorial - User Guide](tutorial/index.md){.internal-link target=_blank}. !!! tip - Pydantic has a special behavior when you use `Optional` or `Union[Something, None]` without a default value, you can read more about it in the Pydantic docs about Required Optional fields. + 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 @@ -486,7 +486,7 @@ Python also has a feature that allows putting **additional metadata** in these t {!> ../../../docs_src/python_types/tutorial013_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" In versions below Python 3.9, you import `Annotated` from `typing_extensions`. diff --git a/docs/en/docs/reference/apirouter.md b/docs/en/docs/reference/apirouter.md new file mode 100644 index 0000000000000..b779ad2914370 --- /dev/null +++ b/docs/en/docs/reference/apirouter.md @@ -0,0 +1,25 @@ +# `APIRouter` class + +Here's the reference information for the `APIRouter` class, with all its parameters, +attributes and methods. + +You can import the `APIRouter` class directly from `fastapi`: + +```python +from fastapi import APIRouter +``` + +::: fastapi.APIRouter + options: + members: + - websocket + - include_router + - get + - put + - post + - delete + - options + - head + - patch + - trace + - on_event diff --git a/docs/en/docs/reference/background.md b/docs/en/docs/reference/background.md new file mode 100644 index 0000000000000..e0c0be899f994 --- /dev/null +++ b/docs/en/docs/reference/background.md @@ -0,0 +1,13 @@ +# Background Tasks - `BackgroundTasks` + +You can declare a parameter in a *path operation function* or dependency function +with the type `BackgroundTasks`, and then you can use it to schedule the execution +of background tasks after the response is sent. + +You can import it directly from `fastapi`: + +```python +from fastapi import BackgroundTasks +``` + +::: fastapi.BackgroundTasks diff --git a/docs/en/docs/reference/dependencies.md b/docs/en/docs/reference/dependencies.md new file mode 100644 index 0000000000000..0999682679a7e --- /dev/null +++ b/docs/en/docs/reference/dependencies.md @@ -0,0 +1,32 @@ +# Dependencies - `Depends()` and `Security()` + +## `Depends()` + +Dependencies are handled mainly with the special function `Depends()` that takes a +callable. + +Here is the reference for it and its parameters. + +You can import it directly from `fastapi`: + +```python +from fastapi import Depends +``` + +::: fastapi.Depends + +## `Security()` + +For many scenarios, you can handle security (authorization, authentication, etc.) with +dependencies, using `Depends()`. + +But when you want to also declare OAuth2 scopes, you can use `Security()` instead of +`Depends()`. + +You can import `Security()` directly from `fastapi`: + +```python +from fastapi import Security +``` + +::: fastapi.Security diff --git a/docs/en/docs/reference/encoders.md b/docs/en/docs/reference/encoders.md new file mode 100644 index 0000000000000..28df2e43a2786 --- /dev/null +++ b/docs/en/docs/reference/encoders.md @@ -0,0 +1,3 @@ +# Encoders - `jsonable_encoder` + +::: fastapi.encoders.jsonable_encoder diff --git a/docs/en/docs/reference/exceptions.md b/docs/en/docs/reference/exceptions.md new file mode 100644 index 0000000000000..7c480834928f9 --- /dev/null +++ b/docs/en/docs/reference/exceptions.md @@ -0,0 +1,22 @@ +# Exceptions - `HTTPException` and `WebSocketException` + +These are the exceptions that you can raise to show errors to the client. + +When you raise an exception, as would happen with normal Python, the rest of the +execution is aborted. This way you can raise these exceptions from anywhere in the +code to abort a request and show the error to the client. + +You can use: + +* `HTTPException` +* `WebSocketException` + +These exceptions can be imported directly from `fastapi`: + +```python +from fastapi import HTTPException, WebSocketException +``` + +::: fastapi.HTTPException + +::: fastapi.WebSocketException diff --git a/docs/en/docs/reference/fastapi.md b/docs/en/docs/reference/fastapi.md new file mode 100644 index 0000000000000..8b87664cb31ee --- /dev/null +++ b/docs/en/docs/reference/fastapi.md @@ -0,0 +1,32 @@ +# `FastAPI` class + +Here's the reference information for the `FastAPI` class, with all its parameters, +attributes and methods. + +You can import the `FastAPI` class directly from `fastapi`: + +```python +from fastapi import FastAPI +``` + +::: fastapi.FastAPI + options: + members: + - openapi_version + - webhooks + - state + - dependency_overrides + - openapi + - websocket + - include_router + - get + - put + - post + - delete + - options + - head + - patch + - trace + - on_event + - middleware + - exception_handler diff --git a/docs/en/docs/reference/httpconnection.md b/docs/en/docs/reference/httpconnection.md new file mode 100644 index 0000000000000..43dfc46f94376 --- /dev/null +++ b/docs/en/docs/reference/httpconnection.md @@ -0,0 +1,13 @@ +# `HTTPConnection` class + +When you want to define dependencies that should be compatible with both HTTP and +WebSockets, you can define a parameter that takes an `HTTPConnection` instead of a +`Request` or a `WebSocket`. + +You can import it from `fastapi.requests`: + +```python +from fastapi.requests import HTTPConnection +``` + +::: fastapi.requests.HTTPConnection diff --git a/docs/en/docs/reference/index.md b/docs/en/docs/reference/index.md new file mode 100644 index 0000000000000..512d5c25c5af7 --- /dev/null +++ b/docs/en/docs/reference/index.md @@ -0,0 +1,7 @@ +# Reference - Code API + +Here's the reference or code API, the classes, functions, parameters, attributes, and +all the FastAPI parts you can use in your applications. + +If you want to **learn FastAPI** you are much better off reading the +[FastAPI Tutorial](https://fastapi.tiangolo.com/tutorial/). diff --git a/docs/en/docs/reference/middleware.md b/docs/en/docs/reference/middleware.md new file mode 100644 index 0000000000000..89704d3c8baac --- /dev/null +++ b/docs/en/docs/reference/middleware.md @@ -0,0 +1,46 @@ +# Middleware + +There are several middlewares available provided by Starlette directly. + +Read more about them in the +[FastAPI docs for Middleware](https://fastapi.tiangolo.com/advanced/middleware/). + +::: fastapi.middleware.cors.CORSMiddleware + +It can be imported from `fastapi`: + +```python +from fastapi.middleware.cors import CORSMiddleware +``` + +::: fastapi.middleware.gzip.GZipMiddleware + +It can be imported from `fastapi`: + +```python +from fastapi.middleware.gzip import GZipMiddleware +``` + +::: fastapi.middleware.httpsredirect.HTTPSRedirectMiddleware + +It can be imported from `fastapi`: + +```python +from fastapi.middleware.httpsredirect import HTTPSRedirectMiddleware +``` + +::: fastapi.middleware.trustedhost.TrustedHostMiddleware + +It can be imported from `fastapi`: + +```python +from fastapi.middleware.trustedhost import TrustedHostMiddleware +``` + +::: fastapi.middleware.wsgi.WSGIMiddleware + +It can be imported from `fastapi`: + +```python +from fastapi.middleware.wsgi import WSGIMiddleware +``` diff --git a/docs/en/docs/reference/openapi/docs.md b/docs/en/docs/reference/openapi/docs.md new file mode 100644 index 0000000000000..ab620833ec99a --- /dev/null +++ b/docs/en/docs/reference/openapi/docs.md @@ -0,0 +1,11 @@ +# OpenAPI `docs` + +Utilities to handle OpenAPI automatic UI documentation, including Swagger UI (by default at `/docs`) and ReDoc (by default at `/redoc`). + +::: fastapi.openapi.docs.get_swagger_ui_html + +::: fastapi.openapi.docs.get_redoc_html + +::: fastapi.openapi.docs.get_swagger_ui_oauth2_redirect_html + +::: fastapi.openapi.docs.swagger_ui_default_parameters diff --git a/docs/en/docs/reference/openapi/index.md b/docs/en/docs/reference/openapi/index.md new file mode 100644 index 0000000000000..e2b313f1509a1 --- /dev/null +++ b/docs/en/docs/reference/openapi/index.md @@ -0,0 +1,5 @@ +# OpenAPI + +There are several utilities to handle OpenAPI. + +You normally don't need to use them unless you have a specific advanced use case that requires it. diff --git a/docs/en/docs/reference/openapi/models.md b/docs/en/docs/reference/openapi/models.md new file mode 100644 index 0000000000000..4a6b0770edca0 --- /dev/null +++ b/docs/en/docs/reference/openapi/models.md @@ -0,0 +1,5 @@ +# OpenAPI `models` + +OpenAPI Pydantic models used to generate and validate the generated OpenAPI. + +::: fastapi.openapi.models diff --git a/docs/en/docs/reference/parameters.md b/docs/en/docs/reference/parameters.md new file mode 100644 index 0000000000000..8f77f0161b07d --- /dev/null +++ b/docs/en/docs/reference/parameters.md @@ -0,0 +1,36 @@ +# Request Parameters + +Here's the reference information for the request parameters. + +These are the special functions that you can put in *path operation function* +parameters or dependency functions with `Annotated` to get data from the request. + +It includes: + +* `Query()` +* `Path()` +* `Body()` +* `Cookie()` +* `Header()` +* `Form()` +* `File()` + +You can import them all directly from `fastapi`: + +```python +from fastapi import Body, Cookie, File, Form, Header, Path, Query +``` + +::: fastapi.Query + +::: fastapi.Path + +::: fastapi.Body + +::: fastapi.Cookie + +::: fastapi.Header + +::: fastapi.Form + +::: fastapi.File diff --git a/docs/en/docs/reference/request.md b/docs/en/docs/reference/request.md new file mode 100644 index 0000000000000..91ec7d37b65b6 --- /dev/null +++ b/docs/en/docs/reference/request.md @@ -0,0 +1,18 @@ +# `Request` class + +You can declare a parameter in a *path operation function* or dependency to be of type +`Request` and then you can access the raw request object directly, without any +validation, etc. + +You can import it directly from `fastapi`: + +```python +from fastapi import Request +``` + +!!! tip + When you want to define dependencies that should be compatible with both HTTP and + WebSockets, you can define a parameter that takes an `HTTPConnection` instead of a + `Request` or a `WebSocket`. + +::: fastapi.Request diff --git a/docs/en/docs/reference/response.md b/docs/en/docs/reference/response.md new file mode 100644 index 0000000000000..91625458317f1 --- /dev/null +++ b/docs/en/docs/reference/response.md @@ -0,0 +1,15 @@ +# `Response` class + +You can declare a parameter in a *path operation function* or dependency to be of type +`Response` and then you can set data for the response like headers or cookies. + +You can also use it directly to create an instance of it and return it from your *path +operations*. + +You can import it directly from `fastapi`: + +```python +from fastapi import Response +``` + +::: fastapi.Response diff --git a/docs/en/docs/reference/responses.md b/docs/en/docs/reference/responses.md new file mode 100644 index 0000000000000..2cbbd89632fe8 --- /dev/null +++ b/docs/en/docs/reference/responses.md @@ -0,0 +1,166 @@ +# Custom Response Classes - File, HTML, Redirect, Streaming, etc. + +There are several custom response classes you can use to create an instance and return +them directly from your *path operations*. + +Read more about it in the +[FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/). + +You can import them directly from `fastapi.responses`: + +```python +from fastapi.responses import ( + FileResponse, + HTMLResponse, + JSONResponse, + ORJSONResponse, + PlainTextResponse, + RedirectResponse, + Response, + StreamingResponse, + UJSONResponse, +) +``` + +## FastAPI Responses + +There are a couple of custom FastAPI response classes, you can use them to optimize JSON performance. + +::: fastapi.responses.UJSONResponse + options: + members: + - charset + - status_code + - media_type + - body + - background + - raw_headers + - render + - init_headers + - headers + - set_cookie + - delete_cookie + +::: fastapi.responses.ORJSONResponse + options: + members: + - charset + - status_code + - media_type + - body + - background + - raw_headers + - render + - init_headers + - headers + - set_cookie + - delete_cookie + +## Starlette Responses + +::: fastapi.responses.FileResponse + options: + members: + - chunk_size + - charset + - status_code + - media_type + - body + - background + - raw_headers + - render + - init_headers + - headers + - set_cookie + - delete_cookie + +::: fastapi.responses.HTMLResponse + options: + members: + - charset + - status_code + - media_type + - body + - background + - raw_headers + - render + - init_headers + - headers + - set_cookie + - delete_cookie + +::: fastapi.responses.JSONResponse + options: + members: + - charset + - status_code + - media_type + - body + - background + - raw_headers + - render + - init_headers + - headers + - set_cookie + - delete_cookie + +::: fastapi.responses.PlainTextResponse + options: + members: + - charset + - status_code + - media_type + - body + - background + - raw_headers + - render + - init_headers + - headers + - set_cookie + - delete_cookie + +::: fastapi.responses.RedirectResponse + options: + members: + - charset + - status_code + - media_type + - body + - background + - raw_headers + - render + - init_headers + - headers + - set_cookie + - delete_cookie + +::: fastapi.responses.Response + options: + members: + - charset + - status_code + - media_type + - body + - background + - raw_headers + - render + - init_headers + - headers + - set_cookie + - delete_cookie + +::: fastapi.responses.StreamingResponse + options: + members: + - body_iterator + - charset + - status_code + - media_type + - body + - background + - raw_headers + - render + - init_headers + - headers + - set_cookie + - delete_cookie diff --git a/docs/en/docs/reference/security/index.md b/docs/en/docs/reference/security/index.md new file mode 100644 index 0000000000000..ff86e9e30ca70 --- /dev/null +++ b/docs/en/docs/reference/security/index.md @@ -0,0 +1,76 @@ +# Security Tools + +When you need to declare dependencies with OAuth2 scopes you use `Security()`. + +But you still need to define what is the dependable, the callable that you pass as +a parameter to `Depends()` or `Security()`. + +There are multiple tools that you can use to create those dependables, and they get +integrated into OpenAPI so they are shown in the automatic docs UI, they can be used +by automatically generated clients and SDKs, etc. + +You can import them from `fastapi.security`: + +```python +from fastapi.security import ( + APIKeyCookie, + APIKeyHeader, + APIKeyQuery, + HTTPAuthorizationCredentials, + HTTPBasic, + HTTPBasicCredentials, + HTTPBearer, + HTTPDigest, + OAuth2, + OAuth2AuthorizationCodeBearer, + OAuth2PasswordBearer, + OAuth2PasswordRequestForm, + OAuth2PasswordRequestFormStrict, + OpenIdConnect, + SecurityScopes, +) +``` + +## API Key Security Schemes + +::: fastapi.security.APIKeyCookie + +::: fastapi.security.APIKeyHeader + +::: fastapi.security.APIKeyQuery + +## HTTP Authentication Schemes + +::: fastapi.security.HTTPBasic + +::: fastapi.security.HTTPBearer + +::: fastapi.security.HTTPDigest + +## HTTP Credentials + +::: fastapi.security.HTTPAuthorizationCredentials + +::: fastapi.security.HTTPBasicCredentials + +## OAuth2 Authentication + +::: fastapi.security.OAuth2 + +::: fastapi.security.OAuth2AuthorizationCodeBearer + +::: fastapi.security.OAuth2PasswordBearer + +## OAuth2 Password Form + +::: fastapi.security.OAuth2PasswordRequestForm + +::: fastapi.security.OAuth2PasswordRequestFormStrict + +## OAuth2 Security Scopes in Dependencies + +::: fastapi.security.SecurityScopes + +## OpenID Connect + +::: fastapi.security.OpenIdConnect diff --git a/docs/en/docs/reference/staticfiles.md b/docs/en/docs/reference/staticfiles.md new file mode 100644 index 0000000000000..ce66f17b3d08e --- /dev/null +++ b/docs/en/docs/reference/staticfiles.md @@ -0,0 +1,14 @@ +# Static Files - `StaticFiles` + +You can use the `StaticFiles` class to serve static files, like JavaScript, CSS, images, etc. + +Read more about it in the +[FastAPI docs for Static Files](https://fastapi.tiangolo.com/tutorial/static-files/). + +You can import it directly from `fastapi.staticfiles`: + +```python +from fastapi.staticfiles import StaticFiles +``` + +::: fastapi.staticfiles.StaticFiles diff --git a/docs/en/docs/reference/status.md b/docs/en/docs/reference/status.md new file mode 100644 index 0000000000000..a238007923be8 --- /dev/null +++ b/docs/en/docs/reference/status.md @@ -0,0 +1,39 @@ +# Status Codes + +You can import the `status` module from `fastapi`: + +```python +from fastapi import status +``` + +`status` is provided directly by Starlette. + +It contains a group of named constants (variables) with integer status codes. + +For example: + +* 200: `status.HTTP_200_OK` +* 403: `status.HTTP_403_FORBIDDEN` +* etc. + +It can be convenient to quickly access HTTP (and WebSocket) status codes in your app, +using autocompletion for the name without having to remember the integer status codes +by memory. + +Read more about it in the +[FastAPI docs about Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). + +## Example + +```python +from fastapi import FastAPI, status + +app = FastAPI() + + +@app.get("/items/", status_code=status.HTTP_418_IM_A_TEAPOT) +def read_items(): + return [{"name": "Plumbus"}, {"name": "Portal Gun"}] +``` + +::: fastapi.status diff --git a/docs/en/docs/reference/templating.md b/docs/en/docs/reference/templating.md new file mode 100644 index 0000000000000..c865badfcb3f5 --- /dev/null +++ b/docs/en/docs/reference/templating.md @@ -0,0 +1,14 @@ +# Templating - `Jinja2Templates` + +You can use the `Jinja2Templates` class to render Jinja templates. + +Read more about it in the +[FastAPI docs for Templates](https://fastapi.tiangolo.com/advanced/templates/). + +You can import it directly from `fastapi.templating`: + +```python +from fastapi.templating import Jinja2Templates +``` + +::: fastapi.templating.Jinja2Templates diff --git a/docs/en/docs/reference/testclient.md b/docs/en/docs/reference/testclient.md new file mode 100644 index 0000000000000..e391d964a28b7 --- /dev/null +++ b/docs/en/docs/reference/testclient.md @@ -0,0 +1,14 @@ +# Test Client - `TestClient` + +You can use the `TestClient` class to test FastAPI applications without creating an actual HTTP and socket connection, just communicating directly with the FastAPI code. + +Read more about it in the +[FastAPI docs for Testing](https://fastapi.tiangolo.com/tutorial/testing/). + +You can import it directly from `fastapi.testclient`: + +```python +from fastapi.testclient import TestClient +``` + +::: fastapi.testclient.TestClient diff --git a/docs/en/docs/reference/uploadfile.md b/docs/en/docs/reference/uploadfile.md new file mode 100644 index 0000000000000..45c644b18de9b --- /dev/null +++ b/docs/en/docs/reference/uploadfile.md @@ -0,0 +1,23 @@ +# `UploadFile` class + +You can define *path operation function* parameters to be of the type `UploadFile` +to receive files from the request. + +You can import it directly from `fastapi`: + +```python +from fastapi import UploadFile +``` + +::: fastapi.UploadFile + options: + members: + - file + - filename + - size + - headers + - content_type + - read + - write + - seek + - close diff --git a/docs/en/docs/reference/websockets.md b/docs/en/docs/reference/websockets.md new file mode 100644 index 0000000000000..2a046946781b4 --- /dev/null +++ b/docs/en/docs/reference/websockets.md @@ -0,0 +1,70 @@ +# WebSockets + +When defining WebSockets, you normally declare a parameter of type `WebSocket` and +with it you can read data from the client and send data to it. + +It is provided directly by Starlette, but you can import it from `fastapi`: + +```python +from fastapi import WebSocket +``` + +!!! tip + When you want to define dependencies that should be compatible with both HTTP and + WebSockets, you can define a parameter that takes an `HTTPConnection` instead of a + `Request` or a `WebSocket`. + +::: fastapi.WebSocket + options: + members: + - scope + - app + - url + - base_url + - headers + - query_params + - path_params + - cookies + - client + - state + - url_for + - client_state + - application_state + - receive + - send + - accept + - receive_text + - receive_bytes + - receive_json + - iter_text + - iter_bytes + - iter_json + - send_text + - send_bytes + - send_json + - close + +When a client disconnects, a `WebSocketDisconnect` exception is raised, you can catch +it. + +You can import it directly form `fastapi`: + +```python +from fastapi import WebSocketDisconnect +``` + +::: fastapi.WebSocketDisconnect + +## WebSockets - additional classes + +Additional classes for handling WebSockets. + +Provided directly by Starlette, but you can import it from `fastapi`: + +```python +from fastapi.websockets import WebSocketDisconnect, WebSocketState +``` + +::: fastapi.websockets.WebSocketDisconnect + +::: fastapi.websockets.WebSocketState diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index e55bf48c76da7..6d842165c7008 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -1,8 +1,989 @@ +--- +hide: + - navigation +--- + # Release Notes ## Latest Changes +### Docs + +* ✏️ Fix typo in `fastapi/security/oauth2.py`. PR [#11368](https://github.com/tiangolo/fastapi/pull/11368) by [@shandongbinzhou](https://github.com/shandongbinzhou). +* 📝 Update links to Pydantic docs to point to new website. PR [#11328](https://github.com/tiangolo/fastapi/pull/11328) by [@alejsdev](https://github.com/alejsdev). +* ✏️ Fix typo in `docs/en/docs/tutorial/extra-models.md`. PR [#11329](https://github.com/tiangolo/fastapi/pull/11329) by [@alejsdev](https://github.com/alejsdev). +* 📝 Update `project-generation.md`. PR [#11326](https://github.com/tiangolo/fastapi/pull/11326) by [@alejsdev](https://github.com/alejsdev). +* 📝 Update External Links. PR [#11327](https://github.com/tiangolo/fastapi/pull/11327) by [@alejsdev](https://github.com/alejsdev). +* 🔥 Remove link to Pydantic's benchmark, on other i18n pages.. PR [#11224](https://github.com/tiangolo/fastapi/pull/11224) by [@hirotoKirimaru](https://github.com/hirotoKirimaru). +* ✏️ Fix typos in docstrings. PR [#11295](https://github.com/tiangolo/fastapi/pull/11295) by [@davidhuser](https://github.com/davidhuser). +* 🛠️ Improve Node.js script in docs to generate TypeScript clients. PR [#11293](https://github.com/tiangolo/fastapi/pull/11293) by [@alejsdev](https://github.com/alejsdev). +* 📝 Update examples for tests to replace "inexistent" for "nonexistent". PR [#11220](https://github.com/tiangolo/fastapi/pull/11220) by [@Homesteady](https://github.com/Homesteady). +* 📝 Update `python-multipart` GitHub link in all docs from `https://andrew-d.github.io/python-multipart/` to `https://github.com/Kludex/python-multipart`. PR [#11239](https://github.com/tiangolo/fastapi/pull/11239) by [@joshjhans](https://github.com/joshjhans). + +### Translations + +* 🌐 Add German translation for `docs/de/docs/tutorial/security/first-steps.md`. PR [#10432](https://github.com/tiangolo/fastapi/pull/10432) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/advanced/events.md`. PR [#10693](https://github.com/tiangolo/fastapi/pull/10693) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/deployment/cloud.md`. PR [#10746](https://github.com/tiangolo/fastapi/pull/10746) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/advanced/behind-a-proxy.md`. PR [#10675](https://github.com/tiangolo/fastapi/pull/10675) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/help-fastapi.md`. PR [#10455](https://github.com/tiangolo/fastapi/pull/10455) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Update German translation for `docs/de/docs/python-types.md`. PR [#10287](https://github.com/tiangolo/fastapi/pull/10287) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/tutorial/path-params.md`. PR [#10290](https://github.com/tiangolo/fastapi/pull/10290) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/tutorial/handling-errors.md`. PR [#10379](https://github.com/tiangolo/fastapi/pull/10379) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Update German translation for `docs/de/docs/index.md`. PR [#10283](https://github.com/tiangolo/fastapi/pull/10283) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/advanced/security/http-basic-auth.md`. PR [#10651](https://github.com/tiangolo/fastapi/pull/10651) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/tutorial/bigger-applications.md`. PR [#10554](https://github.com/tiangolo/fastapi/pull/10554) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/advanced/path-operation-advanced-configuration.md`. PR [#10612](https://github.com/tiangolo/fastapi/pull/10612) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/tutorial/static-files.md`. PR [#10584](https://github.com/tiangolo/fastapi/pull/10584) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/tutorial/security/oauth2-jwt.md`. PR [#10522](https://github.com/tiangolo/fastapi/pull/10522) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/tutorial/response-model.md`. PR [#10345](https://github.com/tiangolo/fastapi/pull/10345) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/tutorial/extra-models.md`. PR [#10351](https://github.com/tiangolo/fastapi/pull/10351) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/tutorial/body-updates.md`. PR [#10396](https://github.com/tiangolo/fastapi/pull/10396) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/alternatives.md`. PR [#10855](https://github.com/tiangolo/fastapi/pull/10855) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/advanced/templates.md`. PR [#10678](https://github.com/tiangolo/fastapi/pull/10678) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/advanced/security/oauth2-scopes.md`. PR [#10643](https://github.com/tiangolo/fastapi/pull/10643) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/advanced/async-tests.md`. PR [#10708](https://github.com/tiangolo/fastapi/pull/10708) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/tutorial/metadata.md`. PR [#10581](https://github.com/tiangolo/fastapi/pull/10581) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/tutorial/testing.md`. PR [#10586](https://github.com/tiangolo/fastapi/pull/10586) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/tutorial/schema-extra-example.md`. PR [#10597](https://github.com/tiangolo/fastapi/pull/10597) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/advanced/index.md`. PR [#10611](https://github.com/tiangolo/fastapi/pull/10611) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/advanced/response-directly.md`. PR [#10618](https://github.com/tiangolo/fastapi/pull/10618) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/advanced/additional-responses.md`. PR [#10626](https://github.com/tiangolo/fastapi/pull/10626) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/advanced/response-cookies.md`. PR [#10627](https://github.com/tiangolo/fastapi/pull/10627) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/advanced/response-headers.md`. PR [#10628](https://github.com/tiangolo/fastapi/pull/10628) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/advanced/response-change-status-code.md`. PR [#10632](https://github.com/tiangolo/fastapi/pull/10632) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/advanced/advanced-dependencies.md`. PR [#10633](https://github.com/tiangolo/fastapi/pull/10633) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/advanced/security/index.md`. PR [#10635](https://github.com/tiangolo/fastapi/pull/10635) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/advanced/using-request-directly.md`. PR [#10653](https://github.com/tiangolo/fastapi/pull/10653) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/advanced/dataclasses.md`. PR [#10667](https://github.com/tiangolo/fastapi/pull/10667) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/advanced/middleware.md`. PR [#10668](https://github.com/tiangolo/fastapi/pull/10668) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/advanced/sub-applications.md`. PR [#10671](https://github.com/tiangolo/fastapi/pull/10671) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/advanced/websockets.md`. PR [#10687](https://github.com/tiangolo/fastapi/pull/10687) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/advanced/testing-websockets.md`. PR [#10703](https://github.com/tiangolo/fastapi/pull/10703) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/advanced/testing-events.md`. PR [#10704](https://github.com/tiangolo/fastapi/pull/10704) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/advanced/testing-dependencies.md`. PR [#10706](https://github.com/tiangolo/fastapi/pull/10706) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/advanced/openapi-callbacks.md`. PR [#10710](https://github.com/tiangolo/fastapi/pull/10710) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/advanced/settings.md`. PR [#10709](https://github.com/tiangolo/fastapi/pull/10709) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/advanced/wsgi.md`. PR [#10713](https://github.com/tiangolo/fastapi/pull/10713) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/deployment/index.md`. PR [#10733](https://github.com/tiangolo/fastapi/pull/10733) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/deployment/https.md`. PR [#10737](https://github.com/tiangolo/fastapi/pull/10737) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/deployment/manually.md`. PR [#10738](https://github.com/tiangolo/fastapi/pull/10738) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/deployment/concepts.md`. PR [#10744](https://github.com/tiangolo/fastapi/pull/10744) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Update German translation for `docs/de/docs/features.md`. PR [#10284](https://github.com/tiangolo/fastapi/pull/10284) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/deployment/server-workers.md`. PR [#10747](https://github.com/tiangolo/fastapi/pull/10747) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/deployment/docker.md`. PR [#10759](https://github.com/tiangolo/fastapi/pull/10759) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/how-to/index.md`. PR [#10769](https://github.com/tiangolo/fastapi/pull/10769) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/how-to/general.md`. PR [#10770](https://github.com/tiangolo/fastapi/pull/10770) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/how-to/graphql.md`. PR [#10788](https://github.com/tiangolo/fastapi/pull/10788) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/how-to/custom-request-and-route.md`. PR [#10789](https://github.com/tiangolo/fastapi/pull/10789) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/how-to/conditional-openapi.md`. PR [#10790](https://github.com/tiangolo/fastapi/pull/10790) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/how-to/separate-openapi-schemas.md`. PR [#10796](https://github.com/tiangolo/fastapi/pull/10796) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/how-to/configure-swagger-ui.md`. PR [#10804](https://github.com/tiangolo/fastapi/pull/10804) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/how-to/custom-docs-ui-assets.md`. PR [#10803](https://github.com/tiangolo/fastapi/pull/10803) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/reference/parameters.md`. PR [#10814](https://github.com/tiangolo/fastapi/pull/10814) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/reference/status.md`. PR [#10815](https://github.com/tiangolo/fastapi/pull/10815) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/reference/uploadfile.md`. PR [#10816](https://github.com/tiangolo/fastapi/pull/10816) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/reference/exceptions.md`. PR [#10817](https://github.com/tiangolo/fastapi/pull/10817) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/reference/dependencies.md`. PR [#10818](https://github.com/tiangolo/fastapi/pull/10818) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/reference/apirouter.md`. PR [#10819](https://github.com/tiangolo/fastapi/pull/10819) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/reference/websockets.md`. PR [#10822](https://github.com/tiangolo/fastapi/pull/10822) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/reference/httpconnection.md`. PR [#10823](https://github.com/tiangolo/fastapi/pull/10823) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/reference/response.md`. PR [#10824](https://github.com/tiangolo/fastapi/pull/10824) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/reference/middleware.md`. PR [#10837](https://github.com/tiangolo/fastapi/pull/10837) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/reference/openapi/*.md`. PR [#10838](https://github.com/tiangolo/fastapi/pull/10838) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/reference/security/index.md`. PR [#10839](https://github.com/tiangolo/fastapi/pull/10839) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/reference/staticfiles.md`. PR [#10841](https://github.com/tiangolo/fastapi/pull/10841) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/reference/testclient.md`. PR [#10843](https://github.com/tiangolo/fastapi/pull/10843) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/project-generation.md`. PR [#10851](https://github.com/tiangolo/fastapi/pull/10851) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/history-design-future.md`. PR [#10865](https://github.com/tiangolo/fastapi/pull/10865) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/tutorial/dependencies/dependencies-with-yield.md`. PR [#10422](https://github.com/tiangolo/fastapi/pull/10422) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/tutorial/dependencies/global-dependencies.md`. PR [#10420](https://github.com/tiangolo/fastapi/pull/10420) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Update German translation for `docs/de/docs/fastapi-people.md`. PR [#10285](https://github.com/tiangolo/fastapi/pull/10285) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/tutorial/dependencies/sub-dependencies.md`. PR [#10409](https://github.com/tiangolo/fastapi/pull/10409) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/tutorial/security/index.md`. PR [#10429](https://github.com/tiangolo/fastapi/pull/10429) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md`. PR [#10411](https://github.com/tiangolo/fastapi/pull/10411) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/tutorial/extra-data-types.md`. PR [#10534](https://github.com/tiangolo/fastapi/pull/10534) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/tutorial/security/simple-oauth2.md`. PR [#10504](https://github.com/tiangolo/fastapi/pull/10504) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/tutorial/security/get-current-user.md`. PR [#10439](https://github.com/tiangolo/fastapi/pull/10439) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/tutorial/request-forms-and-files.md`. PR [#10368](https://github.com/tiangolo/fastapi/pull/10368) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/tutorial/encoder.md`. PR [#10385](https://github.com/tiangolo/fastapi/pull/10385) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/tutorial/request-forms.md`. PR [#10361](https://github.com/tiangolo/fastapi/pull/10361) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/deployment/versions.md`. PR [#10491](https://github.com/tiangolo/fastapi/pull/10491) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/async.md`. PR [#10449](https://github.com/tiangolo/fastapi/pull/10449) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/tutorial/cookie-params.md`. PR [#10323](https://github.com/tiangolo/fastapi/pull/10323) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/tutorial/dependencies/classes-as-dependencies.md`. PR [#10407](https://github.com/tiangolo/fastapi/pull/10407) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/tutorial/dependencies/index.md`. PR [#10399](https://github.com/tiangolo/fastapi/pull/10399) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/tutorial/header-params.md`. PR [#10326](https://github.com/tiangolo/fastapi/pull/10326) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/tutorial/path-params-numeric-validations.md`. PR [#10307](https://github.com/tiangolo/fastapi/pull/10307) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/tutorial/query-params-str-validations.md`. PR [#10304](https://github.com/tiangolo/fastapi/pull/10304) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/tutorial/request-files.md`. PR [#10364](https://github.com/tiangolo/fastapi/pull/10364) by [@nilslindemann](https://github.com/nilslindemann). +* :globe_with_meridians: Add Portuguese translation for `docs/pt/docs/advanced/templates.md`. PR [#11338](https://github.com/tiangolo/fastapi/pull/11338) by [@SamuelBFavarin](https://github.com/SamuelBFavarin). +* 🌐 Add Bengali translations for `docs/bn/docs/learn/index.md`. PR [#11337](https://github.com/tiangolo/fastapi/pull/11337) by [@imtiaz101325](https://github.com/imtiaz101325). +* 🌐 Fix Korean translation for `docs/ko/docs/index.md`. PR [#11296](https://github.com/tiangolo/fastapi/pull/11296) by [@choi-haram](https://github.com/choi-haram). +* 🌐 Add Korean translation for `docs/ko/docs/about/index.md`. PR [#11299](https://github.com/tiangolo/fastapi/pull/11299) by [@choi-haram](https://github.com/choi-haram). +* 🌐 Add Korean translation for `docs/ko/docs/advanced/index.md`. PR [#9613](https://github.com/tiangolo/fastapi/pull/9613) by [@ElliottLarsen](https://github.com/ElliottLarsen). +* 🌐 Add German translation for `docs/de/docs/how-to/extending-openapi.md`. PR [#10794](https://github.com/tiangolo/fastapi/pull/10794) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Update Chinese translation for `docs/zh/docs/tutorial/metadata.md`. PR [#11286](https://github.com/tiangolo/fastapi/pull/11286) by [@jackleeio](https://github.com/jackleeio). +* 🌐 Update Chinese translation for `docs/zh/docs/contributing.md`. PR [#10887](https://github.com/tiangolo/fastapi/pull/10887) by [@Aruelius](https://github.com/Aruelius). +* 🌐 Add Azerbaijani translation for `docs/az/docs/fastapi-people.md`. PR [#11195](https://github.com/tiangolo/fastapi/pull/11195) by [@vusallyv](https://github.com/vusallyv). +* 🌐 Add Russian translation for `docs/ru/docs/tutorial/dependencies/index.md`. PR [#11223](https://github.com/tiangolo/fastapi/pull/11223) by [@kohiry](https://github.com/kohiry). +* 🌐 Update Chinese translation for `docs/zh/docs/tutorial/query-params.md`. PR [#11242](https://github.com/tiangolo/fastapi/pull/11242) by [@jackleeio](https://github.com/jackleeio). +* 🌐 Add Azerbaijani translation for `docs/az/learn/index.md`. PR [#11192](https://github.com/tiangolo/fastapi/pull/11192) by [@vusallyv](https://github.com/vusallyv). + +### Internal + +* 👷 Disable MkDocs insiders social plugin while an issue in MkDocs Material is handled. PR [#11373](https://github.com/tiangolo/fastapi/pull/11373) by [@tiangolo](https://github.com/tiangolo). +* 👷 Fix logic for when to install and use MkDocs Insiders. PR [#11372](https://github.com/tiangolo/fastapi/pull/11372) by [@tiangolo](https://github.com/tiangolo). +* 👷 Do not use Python packages cache for publish. PR [#11366](https://github.com/tiangolo/fastapi/pull/11366) by [@tiangolo](https://github.com/tiangolo). +* 👷 Add CI to test sdists for redistribution (e.g. Linux distros). PR [#11365](https://github.com/tiangolo/fastapi/pull/11365) by [@tiangolo](https://github.com/tiangolo). +* 👷 Update build-docs GitHub Action path filter. PR [#11354](https://github.com/tiangolo/fastapi/pull/11354) by [@tiangolo](https://github.com/tiangolo). +* 🔧 Update Ruff config, add extra ignore rule from SQLModel. PR [#11353](https://github.com/tiangolo/fastapi/pull/11353) by [@tiangolo](https://github.com/tiangolo). +* ⬆️ Upgrade configuration for Ruff v0.2.0. PR [#11075](https://github.com/tiangolo/fastapi/pull/11075) by [@charliermarsh](https://github.com/charliermarsh). +* 🔧 Update sponsors, add MongoDB. PR [#11346](https://github.com/tiangolo/fastapi/pull/11346) by [@tiangolo](https://github.com/tiangolo). +* ⬆ Bump dorny/paths-filter from 2 to 3. PR [#11028](https://github.com/tiangolo/fastapi/pull/11028) by [@dependabot[bot]](https://github.com/apps/dependabot). +* ⬆ Bump dawidd6/action-download-artifact from 3.0.0 to 3.1.4. PR [#11310](https://github.com/tiangolo/fastapi/pull/11310) by [@dependabot[bot]](https://github.com/apps/dependabot). +* ♻️ Refactor computing FastAPI People, include 3 months, 6 months, 1 year, based on comment date, not discussion date. PR [#11304](https://github.com/tiangolo/fastapi/pull/11304) by [@tiangolo](https://github.com/tiangolo). +* 👥 Update FastAPI People. PR [#11228](https://github.com/tiangolo/fastapi/pull/11228) by [@tiangolo](https://github.com/tiangolo). +* 🔥 Remove Jina AI QA Bot from the docs. PR [#11268](https://github.com/tiangolo/fastapi/pull/11268) by [@nan-wang](https://github.com/nan-wang). +* 🔧 Update sponsors, remove Jina, remove Powens, move TestDriven.io. PR [#11213](https://github.com/tiangolo/fastapi/pull/11213) by [@tiangolo](https://github.com/tiangolo). + +## 0.110.0 + +### Breaking Changes + +* 🐛 Fix unhandled growing memory for internal server errors, refactor dependencies with `yield` and `except` to require raising again as in regular Python. PR [#11191](https://github.com/tiangolo/fastapi/pull/11191) by [@tiangolo](https://github.com/tiangolo). + * This is a breaking change (and only slightly) if you used dependencies with `yield`, used `except` in those dependencies, and didn't raise again. + * This was reported internally by [@rushilsrivastava](https://github.com/rushilsrivastava) as a memory leak when the server had unhandled exceptions that would produce internal server errors, the memory allocated before that point would not be released. + * Read the new docs: [Dependencies with `yield` and `except`](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/#dependencies-with-yield-and-except). + +In short, if you had dependencies that looked like: + +```Python +def my_dep(): + try: + yield + except SomeException: + pass +``` + +Now you need to make sure you raise again after `except`, just as you would in regular Python: + +```Python +def my_dep(): + try: + yield + except SomeException: + raise +``` + +### Docs + +* ✏️ Fix minor typos in `docs/ko/docs/`. PR [#11126](https://github.com/tiangolo/fastapi/pull/11126) by [@KaniKim](https://github.com/KaniKim). +* ✏️ Fix minor typo in `fastapi/applications.py`. PR [#11099](https://github.com/tiangolo/fastapi/pull/11099) by [@JacobHayes](https://github.com/JacobHayes). + +### Translations + +* 🌐 Add German translation for `docs/de/docs/reference/background.md`. PR [#10820](https://github.com/tiangolo/fastapi/pull/10820) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/reference/templating.md`. PR [#10842](https://github.com/tiangolo/fastapi/pull/10842) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/external-links.md`. PR [#10852](https://github.com/tiangolo/fastapi/pull/10852) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Update Turkish translation for `docs/tr/docs/tutorial/query-params.md`. PR [#11162](https://github.com/tiangolo/fastapi/pull/11162) by [@hasansezertasan](https://github.com/hasansezertasan). +* 🌐 Add German translation for `docs/de/docs/reference/encoders.md`. PR [#10840](https://github.com/tiangolo/fastapi/pull/10840) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/reference/responses.md`. PR [#10825](https://github.com/tiangolo/fastapi/pull/10825) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/reference/request.md`. PR [#10821](https://github.com/tiangolo/fastapi/pull/10821) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add Turkish translation for `docs/tr/docs/tutorial/query-params.md`. PR [#11078](https://github.com/tiangolo/fastapi/pull/11078) by [@emrhnsyts](https://github.com/emrhnsyts). +* 🌐 Add German translation for `docs/de/docs/reference/fastapi.md`. PR [#10813](https://github.com/tiangolo/fastapi/pull/10813) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/newsletter.md`. PR [#10853](https://github.com/tiangolo/fastapi/pull/10853) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/learn/index.md`. PR [#11142](https://github.com/tiangolo/fastapi/pull/11142) by [@hsuanchi](https://github.com/hsuanchi). +* 🌐 Add Korean translation for `/docs/ko/docs/tutorial/dependencies/global-dependencies.md`. PR [#11123](https://github.com/tiangolo/fastapi/pull/11123) by [@riroan](https://github.com/riroan). +* 🌐 Add Korean translation for `/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md`. PR [#11124](https://github.com/tiangolo/fastapi/pull/11124) by [@riroan](https://github.com/riroan). +* 🌐 Add Korean translation for `/docs/ko/docs/tutorial/schema-extra-example.md`. PR [#11121](https://github.com/tiangolo/fastapi/pull/11121) by [@KaniKim](https://github.com/KaniKim). +* 🌐 Add Korean translation for `/docs/ko/docs/tutorial/body-fields.md`. PR [#11112](https://github.com/tiangolo/fastapi/pull/11112) by [@KaniKim](https://github.com/KaniKim). +* 🌐 Add Korean translation for `/docs/ko/docs/tutorial/cookie-params.md`. PR [#11118](https://github.com/tiangolo/fastapi/pull/11118) by [@riroan](https://github.com/riroan). +* 🌐 Update Korean translation for `/docs/ko/docs/dependencies/index.md`. PR [#11114](https://github.com/tiangolo/fastapi/pull/11114) by [@KaniKim](https://github.com/KaniKim). +* 🌐 Update Korean translation for `/docs/ko/docs/deployment/docker.md`. PR [#11113](https://github.com/tiangolo/fastapi/pull/11113) by [@KaniKim](https://github.com/KaniKim). +* 🌐 Update Turkish translation for `docs/tr/docs/tutorial/first-steps.md`. PR [#11094](https://github.com/tiangolo/fastapi/pull/11094) by [@hasansezertasan](https://github.com/hasansezertasan). +* 🌐 Add Spanish translation for `docs/es/docs/advanced/security/index.md`. PR [#2278](https://github.com/tiangolo/fastapi/pull/2278) by [@Xaraxx](https://github.com/Xaraxx). +* 🌐 Add Spanish translation for `docs/es/docs/advanced/response-headers.md`. PR [#2276](https://github.com/tiangolo/fastapi/pull/2276) by [@Xaraxx](https://github.com/Xaraxx). +* 🌐 Add Spanish translation for `docs/es/docs/deployment/index.md` and `~/deployment/versions.md`. PR [#9669](https://github.com/tiangolo/fastapi/pull/9669) by [@pabloperezmoya](https://github.com/pabloperezmoya). +* 🌐 Add Spanish translation for `docs/es/docs/benchmarks.md`. PR [#10928](https://github.com/tiangolo/fastapi/pull/10928) by [@pablocm83](https://github.com/pablocm83). +* 🌐 Add Spanish translation for `docs/es/docs/advanced/response-change-status-code.md`. PR [#11100](https://github.com/tiangolo/fastapi/pull/11100) by [@alejsdev](https://github.com/alejsdev). + +## 0.109.2 + +### Upgrades + +* ⬆️ Upgrade version of Starlette to `>= 0.36.3`. PR [#11086](https://github.com/tiangolo/fastapi/pull/11086) by [@tiangolo](https://github.com/tiangolo). + +### Translations + +* 🌐 Update Turkish translation for `docs/tr/docs/fastapi-people.md`. PR [#10547](https://github.com/tiangolo/fastapi/pull/10547) by [@alperiox](https://github.com/alperiox). + +### Internal + +* 🍱 Add new FastAPI logo. PR [#11090](https://github.com/tiangolo/fastapi/pull/11090) by [@tiangolo](https://github.com/tiangolo). + +## 0.109.1 + +### Security fixes + +* ⬆️ Upgrade minimum version of `python-multipart` to `>=0.0.7` to fix a vulnerability when using form data with a ReDos attack. You can also simply upgrade `python-multipart`. + +Read more in the [advisory: Content-Type Header ReDoS](https://github.com/tiangolo/fastapi/security/advisories/GHSA-qf9m-vfgh-m389). + +### Features + +* ✨ Include HTTP 205 in status codes with no body. PR [#10969](https://github.com/tiangolo/fastapi/pull/10969) by [@tiangolo](https://github.com/tiangolo). + +### Refactors + +* ✅ Refactor tests for duplicate operation ID generation for compatibility with other tools running the FastAPI test suite. PR [#10876](https://github.com/tiangolo/fastapi/pull/10876) by [@emmettbutler](https://github.com/emmettbutler). +* ♻️ Simplify string format with f-strings in `fastapi/utils.py`. PR [#10576](https://github.com/tiangolo/fastapi/pull/10576) by [@eukub](https://github.com/eukub). +* 🔧 Fix Ruff configuration unintentionally enabling and re-disabling mccabe complexity check. PR [#10893](https://github.com/tiangolo/fastapi/pull/10893) by [@jiridanek](https://github.com/jiridanek). +* ✅ Re-enable test in `tests/test_tutorial/test_header_params/test_tutorial003.py` after fix in Starlette. PR [#10904](https://github.com/tiangolo/fastapi/pull/10904) by [@ooknimm](https://github.com/ooknimm). + +### Docs + +* 📝 Tweak wording in `help-fastapi.md`. PR [#11040](https://github.com/tiangolo/fastapi/pull/11040) by [@tiangolo](https://github.com/tiangolo). +* 📝 Tweak docs for Behind a Proxy. PR [#11038](https://github.com/tiangolo/fastapi/pull/11038) by [@tiangolo](https://github.com/tiangolo). +* 📝 Add External Link: 10 Tips for adding SQLAlchemy to FastAPI. PR [#11036](https://github.com/tiangolo/fastapi/pull/11036) by [@Donnype](https://github.com/Donnype). +* 📝 Add External Link: Tips on migrating from Flask to FastAPI and vice-versa. PR [#11029](https://github.com/tiangolo/fastapi/pull/11029) by [@jtemporal](https://github.com/jtemporal). +* 📝 Deprecate old tutorials: Peewee, Couchbase, encode/databases. PR [#10979](https://github.com/tiangolo/fastapi/pull/10979) by [@tiangolo](https://github.com/tiangolo). +* ✏️ Fix typo in `fastapi/security/oauth2.py`. PR [#10972](https://github.com/tiangolo/fastapi/pull/10972) by [@RafalSkolasinski](https://github.com/RafalSkolasinski). +* 📝 Update `HTTPException` details in `docs/en/docs/tutorial/handling-errors.md`. PR [#5418](https://github.com/tiangolo/fastapi/pull/5418) by [@papb](https://github.com/papb). +* ✏️ A few tweaks in `docs/de/docs/tutorial/first-steps.md`. PR [#10959](https://github.com/tiangolo/fastapi/pull/10959) by [@nilslindemann](https://github.com/nilslindemann). +* ✏️ Fix link in `docs/en/docs/advanced/async-tests.md`. PR [#10960](https://github.com/tiangolo/fastapi/pull/10960) by [@nilslindemann](https://github.com/nilslindemann). +* ✏️ Fix typos for Spanish documentation. PR [#10957](https://github.com/tiangolo/fastapi/pull/10957) by [@jlopezlira](https://github.com/jlopezlira). +* 📝 Add warning about lifespan functions and backwards compatibility with events. PR [#10734](https://github.com/tiangolo/fastapi/pull/10734) by [@jacob-indigo](https://github.com/jacob-indigo). +* ✏️ Fix broken link in `docs/tutorial/sql-databases.md` in several languages. PR [#10716](https://github.com/tiangolo/fastapi/pull/10716) by [@theoohoho](https://github.com/theoohoho). +* ✏️ Remove broken links from `external_links.yml`. PR [#10943](https://github.com/tiangolo/fastapi/pull/10943) by [@Torabek](https://github.com/Torabek). +* 📝 Update template docs with more info about `url_for`. PR [#5937](https://github.com/tiangolo/fastapi/pull/5937) by [@EzzEddin](https://github.com/EzzEddin). +* 📝 Update usage of Token model in security docs. PR [#9313](https://github.com/tiangolo/fastapi/pull/9313) by [@piotrszacilowski](https://github.com/piotrszacilowski). +* ✏️ Update highlighted line in `docs/en/docs/tutorial/bigger-applications.md`. PR [#5490](https://github.com/tiangolo/fastapi/pull/5490) by [@papb](https://github.com/papb). +* 📝 Add External Link: Explore How to Effectively Use JWT With FastAPI. PR [#10212](https://github.com/tiangolo/fastapi/pull/10212) by [@aanchlia](https://github.com/aanchlia). +* 📝 Add hyperlink to `docs/en/docs/tutorial/static-files.md`. PR [#10243](https://github.com/tiangolo/fastapi/pull/10243) by [@hungtsetse](https://github.com/hungtsetse). +* 📝 Add External Link: Instrument a FastAPI service adding tracing with OpenTelemetry and send/show traces in Grafana Tempo. PR [#9440](https://github.com/tiangolo/fastapi/pull/9440) by [@softwarebloat](https://github.com/softwarebloat). +* 📝 Review and rewording of `en/docs/contributing.md`. PR [#10480](https://github.com/tiangolo/fastapi/pull/10480) by [@nilslindemann](https://github.com/nilslindemann). +* 📝 Add External Link: ML serving and monitoring with FastAPI and Evidently. PR [#9701](https://github.com/tiangolo/fastapi/pull/9701) by [@mnrozhkov](https://github.com/mnrozhkov). +* 📝 Reword in docs, from "have in mind" to "keep in mind". PR [#10376](https://github.com/tiangolo/fastapi/pull/10376) by [@malicious](https://github.com/malicious). +* 📝 Add External Link: Talk by Jeny Sadadia. PR [#10265](https://github.com/tiangolo/fastapi/pull/10265) by [@JenySadadia](https://github.com/JenySadadia). +* 📝 Add location info to `tutorial/bigger-applications.md`. PR [#10552](https://github.com/tiangolo/fastapi/pull/10552) by [@nilslindemann](https://github.com/nilslindemann). +* ✏️ Fix Pydantic method name in `docs/en/docs/advanced/path-operation-advanced-configuration.md`. PR [#10826](https://github.com/tiangolo/fastapi/pull/10826) by [@ahmedabdou14](https://github.com/ahmedabdou14). + +### Translations + +* 🌐 Add Spanish translation for `docs/es/docs/external-links.md`. PR [#10933](https://github.com/tiangolo/fastapi/pull/10933) by [@pablocm83](https://github.com/pablocm83). +* 🌐 Update Korean translation for `docs/ko/docs/tutorial/first-steps.md`, `docs/ko/docs/tutorial/index.md`, `docs/ko/docs/tutorial/path-params.md`, and `docs/ko/docs/tutorial/query-params.md`. PR [#4218](https://github.com/tiangolo/fastapi/pull/4218) by [@SnowSuno](https://github.com/SnowSuno). +* 🌐 Add Chinese translation for `docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md`. PR [#10870](https://github.com/tiangolo/fastapi/pull/10870) by [@zhiquanchi](https://github.com/zhiquanchi). +* 🌐 Add Chinese translation for `docs/zh/docs/deployment/concepts.md`. PR [#10282](https://github.com/tiangolo/fastapi/pull/10282) by [@xzmeng](https://github.com/xzmeng). +* 🌐 Add Azerbaijani translation for `docs/az/docs/index.md`. PR [#11047](https://github.com/tiangolo/fastapi/pull/11047) by [@aykhans](https://github.com/aykhans). +* 🌐 Add Korean translation for `docs/ko/docs/tutorial/middleware.md`. PR [#2829](https://github.com/tiangolo/fastapi/pull/2829) by [@JeongHyeongKim](https://github.com/JeongHyeongKim). +* 🌐 Add German translation for `docs/de/docs/tutorial/body-nested-models.md`. PR [#10313](https://github.com/tiangolo/fastapi/pull/10313) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add Persian translation for `docs/fa/docs/tutorial/middleware.md`. PR [#9695](https://github.com/tiangolo/fastapi/pull/9695) by [@mojtabapaso](https://github.com/mojtabapaso). +* 🌐 Update Farsi translation for `docs/fa/docs/index.md`. PR [#10216](https://github.com/tiangolo/fastapi/pull/10216) by [@theonlykingpin](https://github.com/theonlykingpin). +* 🌐 Add German translation for `docs/de/docs/tutorial/body-fields.md`. PR [#10310](https://github.com/tiangolo/fastapi/pull/10310) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/tutorial/body.md`. PR [#10295](https://github.com/tiangolo/fastapi/pull/10295) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/tutorial/body-multiple-params.md`. PR [#10308](https://github.com/tiangolo/fastapi/pull/10308) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/security/get-current-user.md`. PR [#2681](https://github.com/tiangolo/fastapi/pull/2681) by [@sh0nk](https://github.com/sh0nk). +* 🌐 Add Chinese translation for `docs/zh/docs/advanced/advanced-dependencies.md`. PR [#3798](https://github.com/tiangolo/fastapi/pull/3798) by [@jaystone776](https://github.com/jaystone776). +* 🌐 Add Chinese translation for `docs/zh/docs/advanced/events.md`. PR [#3815](https://github.com/tiangolo/fastapi/pull/3815) by [@jaystone776](https://github.com/jaystone776). +* 🌐 Add Chinese translation for `docs/zh/docs/advanced/behind-a-proxy.md`. PR [#3820](https://github.com/tiangolo/fastapi/pull/3820) by [@jaystone776](https://github.com/jaystone776). +* 🌐 Add Chinese translation for `docs/zh/docs/advanced/testing-events.md`. PR [#3818](https://github.com/tiangolo/fastapi/pull/3818) by [@jaystone776](https://github.com/jaystone776). +* 🌐 Add Chinese translation for `docs/zh/docs/advanced/testing-websockets.md`. PR [#3817](https://github.com/tiangolo/fastapi/pull/3817) by [@jaystone776](https://github.com/jaystone776). +* 🌐 Add Chinese translation for `docs/zh/docs/advanced/testing-database.md`. PR [#3821](https://github.com/tiangolo/fastapi/pull/3821) by [@jaystone776](https://github.com/jaystone776). +* 🌐 Add Chinese translation for `docs/zh/docs/deployment/deta.md`. PR [#3837](https://github.com/tiangolo/fastapi/pull/3837) by [@jaystone776](https://github.com/jaystone776). +* 🌐 Add Chinese translation for `docs/zh/docs/history-design-future.md`. PR [#3832](https://github.com/tiangolo/fastapi/pull/3832) by [@jaystone776](https://github.com/jaystone776). +* 🌐 Add Chinese translation for `docs/zh/docs/project-generation.md`. PR [#3831](https://github.com/tiangolo/fastapi/pull/3831) by [@jaystone776](https://github.com/jaystone776). +* 🌐 Add Chinese translation for `docs/zh/docs/deployment/docker.md`. PR [#10296](https://github.com/tiangolo/fastapi/pull/10296) by [@xzmeng](https://github.com/xzmeng). +* 🌐 Update Spanish translation for `docs/es/docs/features.md`. PR [#10884](https://github.com/tiangolo/fastapi/pull/10884) by [@pablocm83](https://github.com/pablocm83). +* 🌐 Add Spanish translation for `docs/es/docs/newsletter.md`. PR [#10922](https://github.com/tiangolo/fastapi/pull/10922) by [@pablocm83](https://github.com/pablocm83). +* 🌐 Add Korean translation for `docs/ko/docs/tutorial/background-tasks.md`. PR [#5910](https://github.com/tiangolo/fastapi/pull/5910) by [@junah201](https://github.com/junah201). +* :globe_with_meridians: Add Turkish translation for `docs/tr/docs/alternatives.md`. PR [#10502](https://github.com/tiangolo/fastapi/pull/10502) by [@alperiox](https://github.com/alperiox). +* 🌐 Add Korean translation for `docs/ko/docs/tutorial/dependencies/index.md`. PR [#10989](https://github.com/tiangolo/fastapi/pull/10989) by [@KaniKim](https://github.com/KaniKim). +* 🌐 Add Korean translation for `/docs/ko/docs/tutorial/body.md`. PR [#11000](https://github.com/tiangolo/fastapi/pull/11000) by [@KaniKim](https://github.com/KaniKim). +* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/schema-extra-example.md`. PR [#4065](https://github.com/tiangolo/fastapi/pull/4065) by [@luccasmmg](https://github.com/luccasmmg). +* 🌐 Add Turkish translation for `docs/tr/docs/history-design-future.md`. PR [#11012](https://github.com/tiangolo/fastapi/pull/11012) by [@hasansezertasan](https://github.com/hasansezertasan). +* 🌐 Add Turkish translation for `docs/tr/docs/resources/index.md`. PR [#11020](https://github.com/tiangolo/fastapi/pull/11020) by [@hasansezertasan](https://github.com/hasansezertasan). +* 🌐 Add Turkish translation for `docs/tr/docs/how-to/index.md`. PR [#11021](https://github.com/tiangolo/fastapi/pull/11021) by [@hasansezertasan](https://github.com/hasansezertasan). +* 🌐 Add German translation for `docs/de/docs/tutorial/query-params.md`. PR [#10293](https://github.com/tiangolo/fastapi/pull/10293) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/benchmarks.md`. PR [#10866](https://github.com/tiangolo/fastapi/pull/10866) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add Turkish translation for `docs/tr/docs/learn/index.md`. PR [#11014](https://github.com/tiangolo/fastapi/pull/11014) by [@hasansezertasan](https://github.com/hasansezertasan). +* 🌐 Add Persian translation for `docs/fa/docs/tutorial/security/index.md`. PR [#9945](https://github.com/tiangolo/fastapi/pull/9945) by [@mojtabapaso](https://github.com/mojtabapaso). +* 🌐 Add Turkish translation for `docs/tr/docs/help/index.md`. PR [#11013](https://github.com/tiangolo/fastapi/pull/11013) by [@hasansezertasan](https://github.com/hasansezertasan). +* 🌐 Add Turkish translation for `docs/tr/docs/about/index.md`. PR [#11006](https://github.com/tiangolo/fastapi/pull/11006) by [@hasansezertasan](https://github.com/hasansezertasan). +* 🌐 Update Turkish translation for `docs/tr/docs/benchmarks.md`. PR [#11005](https://github.com/tiangolo/fastapi/pull/11005) by [@hasansezertasan](https://github.com/hasansezertasan). +* 🌐 Add Italian translation for `docs/it/docs/index.md`. PR [#5233](https://github.com/tiangolo/fastapi/pull/5233) by [@matteospanio](https://github.com/matteospanio). +* 🌐 Add Korean translation for `docs/ko/docs/help/index.md`. PR [#10983](https://github.com/tiangolo/fastapi/pull/10983) by [@KaniKim](https://github.com/KaniKim). +* 🌐 Add Korean translation for `docs/ko/docs/features.md`. PR [#10976](https://github.com/tiangolo/fastapi/pull/10976) by [@KaniKim](https://github.com/KaniKim). +* 🌐 Add Korean translation for `docs/ko/docs/tutorial/security/get-current-user.md`. PR [#5737](https://github.com/tiangolo/fastapi/pull/5737) by [@KdHyeon0661](https://github.com/KdHyeon0661). +* 🌐 Add Russian translation for `docs/ru/docs/tutorial/security/first-steps.md`. PR [#10541](https://github.com/tiangolo/fastapi/pull/10541) by [@AlertRED](https://github.com/AlertRED). +* 🌐 Add Russian translation for `docs/ru/docs/tutorial/handling-errors.md`. PR [#10375](https://github.com/tiangolo/fastapi/pull/10375) by [@AlertRED](https://github.com/AlertRED). +* 🌐 Add Russian translation for `docs/ru/docs/tutorial/encoder.md`. PR [#10374](https://github.com/tiangolo/fastapi/pull/10374) by [@AlertRED](https://github.com/AlertRED). +* 🌐 Add Russian translation for `docs/ru/docs/tutorial/body-updates.md`. PR [#10373](https://github.com/tiangolo/fastapi/pull/10373) by [@AlertRED](https://github.com/AlertRED). +* 🌐 Russian translation: updated `fastapi-people.md`.. PR [#10255](https://github.com/tiangolo/fastapi/pull/10255) by [@NiKuma0](https://github.com/NiKuma0). +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/security/index.md`. PR [#5798](https://github.com/tiangolo/fastapi/pull/5798) by [@3w36zj6](https://github.com/3w36zj6). +* 🌐 Add German translation for `docs/de/docs/advanced/generate-clients.md`. PR [#10725](https://github.com/tiangolo/fastapi/pull/10725) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/advanced/openapi-webhooks.md`. PR [#10712](https://github.com/tiangolo/fastapi/pull/10712) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/advanced/custom-response.md`. PR [#10624](https://github.com/tiangolo/fastapi/pull/10624) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/advanced/additional-status-codes.md`. PR [#10617](https://github.com/tiangolo/fastapi/pull/10617) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add German translation for `docs/de/docs/tutorial/middleware.md`. PR [#10391](https://github.com/tiangolo/fastapi/pull/10391) by [@JohannesJungbluth](https://github.com/JohannesJungbluth). +* 🌐 Add German translation for introduction documents. PR [#10497](https://github.com/tiangolo/fastapi/pull/10497) by [@nilslindemann](https://github.com/nilslindemann). +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/encoder.md`. PR [#1955](https://github.com/tiangolo/fastapi/pull/1955) by [@SwftAlpc](https://github.com/SwftAlpc). +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/extra-data-types.md`. PR [#1932](https://github.com/tiangolo/fastapi/pull/1932) by [@SwftAlpc](https://github.com/SwftAlpc). +* 🌐 Add Turkish translation for `docs/tr/docs/async.md`. PR [#5191](https://github.com/tiangolo/fastapi/pull/5191) by [@BilalAlpaslan](https://github.com/BilalAlpaslan). +* 🌐 Add Turkish translation for `docs/tr/docs/project-generation.md`. PR [#5192](https://github.com/tiangolo/fastapi/pull/5192) by [@BilalAlpaslan](https://github.com/BilalAlpaslan). +* 🌐 Add Korean translation for `docs/ko/docs/deployment/docker.md`. PR [#5657](https://github.com/tiangolo/fastapi/pull/5657) by [@nearnear](https://github.com/nearnear). +* 🌐 Add Korean translation for `docs/ko/docs/deployment/server-workers.md`. PR [#4935](https://github.com/tiangolo/fastapi/pull/4935) by [@jujumilk3](https://github.com/jujumilk3). +* 🌐 Add Korean translation for `docs/ko/docs/deployment/index.md`. PR [#4561](https://github.com/tiangolo/fastapi/pull/4561) by [@jujumilk3](https://github.com/jujumilk3). +* 🌐 Add Korean translation for `docs/ko/docs/tutorial/path-operation-configuration.md`. PR [#3639](https://github.com/tiangolo/fastapi/pull/3639) by [@jungsu-kwon](https://github.com/jungsu-kwon). +* 🌐 Modify the description of `zh` - Traditional Chinese. PR [#10889](https://github.com/tiangolo/fastapi/pull/10889) by [@cherinyy](https://github.com/cherinyy). +* 🌐 Add Korean translation for `docs/ko/docs/tutorial/static-files.md`. PR [#2957](https://github.com/tiangolo/fastapi/pull/2957) by [@jeesang7](https://github.com/jeesang7). +* 🌐 Add Korean translation for `docs/ko/docs/tutorial/response-model.md`. PR [#2766](https://github.com/tiangolo/fastapi/pull/2766) by [@hard-coders](https://github.com/hard-coders). +* 🌐 Add Korean translation for `docs/ko/docs/tutorial/body-multiple-params.md`. PR [#2461](https://github.com/tiangolo/fastapi/pull/2461) by [@PandaHun](https://github.com/PandaHun). +* 🌐 Add Korean translation for `docs/ko/docs/tutorial/query-params-str-validations.md`. PR [#2415](https://github.com/tiangolo/fastapi/pull/2415) by [@hard-coders](https://github.com/hard-coders). +* 🌐 Add Korean translation for `docs/ko/docs/python-types.md`. PR [#2267](https://github.com/tiangolo/fastapi/pull/2267) by [@jrim](https://github.com/jrim). +* 🌐 Add Korean translation for `docs/ko/docs/tutorial/body-nested-models.md`. PR [#2506](https://github.com/tiangolo/fastapi/pull/2506) by [@hard-coders](https://github.com/hard-coders). +* 🌐 Add Korean translation for `docs/ko/docs/learn/index.md`. PR [#10977](https://github.com/tiangolo/fastapi/pull/10977) by [@KaniKim](https://github.com/KaniKim). +* 🌐 Initialize translations for Traditional Chinese. PR [#10505](https://github.com/tiangolo/fastapi/pull/10505) by [@hsuanchi](https://github.com/hsuanchi). +* ✏️ Tweak the german translation of `docs/de/docs/tutorial/index.md`. PR [#10962](https://github.com/tiangolo/fastapi/pull/10962) by [@nilslindemann](https://github.com/nilslindemann). +* ✏️ Fix typo error in `docs/ko/docs/tutorial/path-params.md`. PR [#10758](https://github.com/tiangolo/fastapi/pull/10758) by [@2chanhaeng](https://github.com/2chanhaeng). +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md`. PR [#1961](https://github.com/tiangolo/fastapi/pull/1961) by [@SwftAlpc](https://github.com/SwftAlpc). +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md`. PR [#1960](https://github.com/tiangolo/fastapi/pull/1960) by [@SwftAlpc](https://github.com/SwftAlpc). +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/dependencies/sub-dependencies.md`. PR [#1959](https://github.com/tiangolo/fastapi/pull/1959) by [@SwftAlpc](https://github.com/SwftAlpc). +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/background-tasks.md`. PR [#2668](https://github.com/tiangolo/fastapi/pull/2668) by [@tokusumi](https://github.com/tokusumi). +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/dependencies/index.md` and `docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md`. PR [#1958](https://github.com/tiangolo/fastapi/pull/1958) by [@SwftAlpc](https://github.com/SwftAlpc). +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/response-model.md`. PR [#1938](https://github.com/tiangolo/fastapi/pull/1938) by [@SwftAlpc](https://github.com/SwftAlpc). +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/body-multiple-params.md`. PR [#1903](https://github.com/tiangolo/fastapi/pull/1903) by [@SwftAlpc](https://github.com/SwftAlpc). +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/path-params-numeric-validations.md`. PR [#1902](https://github.com/tiangolo/fastapi/pull/1902) by [@SwftAlpc](https://github.com/SwftAlpc). +* 🌐 Add Japanese translation for `docs/ja/docs/python-types.md`. PR [#1899](https://github.com/tiangolo/fastapi/pull/1899) by [@SwftAlpc](https://github.com/SwftAlpc). +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/handling-errors.md`. PR [#1953](https://github.com/tiangolo/fastapi/pull/1953) by [@SwftAlpc](https://github.com/SwftAlpc). +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/response-status-code.md`. PR [#1942](https://github.com/tiangolo/fastapi/pull/1942) by [@SwftAlpc](https://github.com/SwftAlpc). +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/extra-models.md`. PR [#1941](https://github.com/tiangolo/fastapi/pull/1941) by [@SwftAlpc](https://github.com/SwftAlpc). +* 🌐 Add Japanese tranlsation for `docs/ja/docs/tutorial/schema-extra-example.md`. PR [#1931](https://github.com/tiangolo/fastapi/pull/1931) by [@SwftAlpc](https://github.com/SwftAlpc). +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/body-nested-models.md`. PR [#1930](https://github.com/tiangolo/fastapi/pull/1930) by [@SwftAlpc](https://github.com/SwftAlpc). +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/body-fields.md`. PR [#1923](https://github.com/tiangolo/fastapi/pull/1923) by [@SwftAlpc](https://github.com/SwftAlpc). +* 🌐 Add German translation for `docs/de/docs/tutorial/index.md`. PR [#9502](https://github.com/tiangolo/fastapi/pull/9502) by [@fhabers21](https://github.com/fhabers21). +* 🌐 Add German translation for `docs/de/docs/tutorial/background-tasks.md`. PR [#10566](https://github.com/tiangolo/fastapi/pull/10566) by [@nilslindemann](https://github.com/nilslindemann). +* ✏️ Fix typo in `docs/ru/docs/index.md`. PR [#10672](https://github.com/tiangolo/fastapi/pull/10672) by [@Delitel-WEB](https://github.com/Delitel-WEB). +* ✏️ Fix typos in `docs/zh/docs/tutorial/extra-data-types.md`. PR [#10727](https://github.com/tiangolo/fastapi/pull/10727) by [@HiemalBeryl](https://github.com/HiemalBeryl). +* 🌐 Add Russian translation for `docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md`. PR [#10410](https://github.com/tiangolo/fastapi/pull/10410) by [@AlertRED](https://github.com/AlertRED). + +### Internal + +* 👥 Update FastAPI People. PR [#11074](https://github.com/tiangolo/fastapi/pull/11074) by [@tiangolo](https://github.com/tiangolo). +* 🔧 Update sponsors: add Coherence. PR [#11066](https://github.com/tiangolo/fastapi/pull/11066) by [@tiangolo](https://github.com/tiangolo). +* 👷 Upgrade GitHub Action issue-manager. PR [#11056](https://github.com/tiangolo/fastapi/pull/11056) by [@tiangolo](https://github.com/tiangolo). +* 🍱 Update sponsors: TalkPython badge. PR [#11052](https://github.com/tiangolo/fastapi/pull/11052) by [@tiangolo](https://github.com/tiangolo). +* 🔧 Update sponsors: TalkPython badge image. PR [#11048](https://github.com/tiangolo/fastapi/pull/11048) by [@tiangolo](https://github.com/tiangolo). +* 🔧 Update sponsors, remove Deta. PR [#11041](https://github.com/tiangolo/fastapi/pull/11041) by [@tiangolo](https://github.com/tiangolo). +* 💄 Fix CSS breaking RTL languages (erroneously introduced by a previous RTL PR). PR [#11039](https://github.com/tiangolo/fastapi/pull/11039) by [@tiangolo](https://github.com/tiangolo). +* 🔧 Add Italian to `mkdocs.yml`. PR [#11016](https://github.com/tiangolo/fastapi/pull/11016) by [@alejsdev](https://github.com/alejsdev). +* 🔨 Verify `mkdocs.yml` languages in CI, update `docs.py`. PR [#11009](https://github.com/tiangolo/fastapi/pull/11009) by [@tiangolo](https://github.com/tiangolo). +* 🔧 Update config in `label-approved.yml` to accept translations with 1 reviewer. PR [#11007](https://github.com/tiangolo/fastapi/pull/11007) by [@alejsdev](https://github.com/alejsdev). +* 👷 Add changes-requested handling in GitHub Action issue manager. PR [#10971](https://github.com/tiangolo/fastapi/pull/10971) by [@tiangolo](https://github.com/tiangolo). +* 🔧 Group dependencies on dependabot updates. PR [#10952](https://github.com/tiangolo/fastapi/pull/10952) by [@Kludex](https://github.com/Kludex). +* ⬆ Bump actions/setup-python from 4 to 5. PR [#10764](https://github.com/tiangolo/fastapi/pull/10764) by [@dependabot[bot]](https://github.com/apps/dependabot). +* ⬆ Bump pypa/gh-action-pypi-publish from 1.8.10 to 1.8.11. PR [#10731](https://github.com/tiangolo/fastapi/pull/10731) by [@dependabot[bot]](https://github.com/apps/dependabot). +* ⬆ Bump dawidd6/action-download-artifact from 2.28.0 to 3.0.0. PR [#10777](https://github.com/tiangolo/fastapi/pull/10777) by [@dependabot[bot]](https://github.com/apps/dependabot). +* 🔧 Add support for translations to languages with a longer code name, like `zh-hant`. PR [#10950](https://github.com/tiangolo/fastapi/pull/10950) by [@tiangolo](https://github.com/tiangolo). + +## 0.109.0 + +### Features + +* ✨ Add support for Python 3.12. PR [#10666](https://github.com/tiangolo/fastapi/pull/10666) by [@Jamim](https://github.com/Jamim). + +### Upgrades + +* ⬆️ Upgrade Starlette to >=0.35.0,<0.36.0. PR [#10938](https://github.com/tiangolo/fastapi/pull/10938) by [@tiangolo](https://github.com/tiangolo). + +### Docs + +* ✏️ Fix typo in `docs/en/docs/alternatives.md`. PR [#10931](https://github.com/tiangolo/fastapi/pull/10931) by [@s111d](https://github.com/s111d). +* 📝 Replace `email` with `username` in `docs_src/security/tutorial007` code examples. PR [#10649](https://github.com/tiangolo/fastapi/pull/10649) by [@nilslindemann](https://github.com/nilslindemann). +* 📝 Add VS Code tutorial link. PR [#10592](https://github.com/tiangolo/fastapi/pull/10592) by [@nilslindemann](https://github.com/nilslindemann). +* 📝 Add notes about Pydantic v2's new `.model_dump()`. PR [#10929](https://github.com/tiangolo/fastapi/pull/10929) by [@tiangolo](https://github.com/tiangolo). +* 📝 Fix broken link in `docs/en/docs/tutorial/sql-databases.md`. PR [#10765](https://github.com/tiangolo/fastapi/pull/10765) by [@HurSungYun](https://github.com/HurSungYun). +* 📝 Add External Link: FastAPI application monitoring made easy. PR [#10917](https://github.com/tiangolo/fastapi/pull/10917) by [@tiangolo](https://github.com/tiangolo). +* ✨ Generate automatic language names for docs translations. PR [#5354](https://github.com/tiangolo/fastapi/pull/5354) by [@jakul](https://github.com/jakul). +* ✏️ Fix typos in `docs/en/docs/alternatives.md` and `docs/en/docs/tutorial/dependencies/index.md`. PR [#10906](https://github.com/tiangolo/fastapi/pull/10906) by [@s111d](https://github.com/s111d). +* ✏️ Fix typos in `docs/en/docs/tutorial/dependencies/dependencies-with-yield.md`. PR [#10834](https://github.com/tiangolo/fastapi/pull/10834) by [@Molkree](https://github.com/Molkree). +* 📝 Add article: "Building a RESTful API with FastAPI: Secure Signup and Login Functionality Included". PR [#9733](https://github.com/tiangolo/fastapi/pull/9733) by [@dxphilo](https://github.com/dxphilo). +* 📝 Add warning about lifecycle events with `AsyncClient`. PR [#4167](https://github.com/tiangolo/fastapi/pull/4167) by [@andrew-chang-dewitt](https://github.com/andrew-chang-dewitt). +* ✏️ Fix typos in `/docs/reference/exceptions.md` and `/en/docs/reference/status.md`. PR [#10809](https://github.com/tiangolo/fastapi/pull/10809) by [@clarencepenz](https://github.com/clarencepenz). +* ✏️ Fix typo in `openapi-callbacks.md`. PR [#10673](https://github.com/tiangolo/fastapi/pull/10673) by [@kayjan](https://github.com/kayjan). +* ✏️ Fix typo in `fastapi/routing.py` . PR [#10520](https://github.com/tiangolo/fastapi/pull/10520) by [@sepsh](https://github.com/sepsh). +* 📝 Replace HTTP code returned in case of existing user error in docs for testing. PR [#4482](https://github.com/tiangolo/fastapi/pull/4482) by [@TristanMarion](https://github.com/TristanMarion). +* 📝 Add blog for FastAPI & Supabase. PR [#6018](https://github.com/tiangolo/fastapi/pull/6018) by [@theinfosecguy](https://github.com/theinfosecguy). +* 📝 Update example source files for SQL databases with SQLAlchemy. PR [#9508](https://github.com/tiangolo/fastapi/pull/9508) by [@s-mustafa](https://github.com/s-mustafa). +* 📝 Update code examples in docs for body, replace name `create_item` with `update_item` when appropriate. PR [#5913](https://github.com/tiangolo/fastapi/pull/5913) by [@OttoAndrey](https://github.com/OttoAndrey). +* ✏️ Fix typo in dependencies with yield source examples. PR [#10847](https://github.com/tiangolo/fastapi/pull/10847) by [@tiangolo](https://github.com/tiangolo). + +### Translations + +* 🌐 Add Bengali translation for `docs/bn/docs/index.md`. PR [#9177](https://github.com/tiangolo/fastapi/pull/9177) by [@Fahad-Md-Kamal](https://github.com/Fahad-Md-Kamal). +* ✏️ Update Python version in `index.md` in several languages. PR [#10711](https://github.com/tiangolo/fastapi/pull/10711) by [@tamago3keran](https://github.com/tamago3keran). +* 🌐 Add Russian translation for `docs/ru/docs/tutorial/request-forms-and-files.md`. PR [#10347](https://github.com/tiangolo/fastapi/pull/10347) by [@AlertRED](https://github.com/AlertRED). +* 🌐 Add Ukrainian translation for `docs/uk/docs/index.md`. PR [#10362](https://github.com/tiangolo/fastapi/pull/10362) by [@rostik1410](https://github.com/rostik1410). +* ✏️ Update Python version in `docs/ko/docs/index.md`. PR [#10680](https://github.com/tiangolo/fastapi/pull/10680) by [@Eeap](https://github.com/Eeap). +* 🌐 Add Persian translation for `docs/fa/docs/features.md`. PR [#5887](https://github.com/tiangolo/fastapi/pull/5887) by [@amirilf](https://github.com/amirilf). +* 🌐 Add Chinese translation for `docs/zh/docs/advanced/additional-responses.md`. PR [#10325](https://github.com/tiangolo/fastapi/pull/10325) by [@ShuibeiC](https://github.com/ShuibeiC). +* 🌐 Fix typos in Russian translations for `docs/ru/docs/tutorial/background-tasks.md`, `docs/ru/docs/tutorial/body-nested-models.md`, `docs/ru/docs/tutorial/debugging.md`, `docs/ru/docs/tutorial/testing.md`. PR [#10311](https://github.com/tiangolo/fastapi/pull/10311) by [@AlertRED](https://github.com/AlertRED). +* 🌐 Add Russian translation for `docs/ru/docs/tutorial/request-files.md`. PR [#10332](https://github.com/tiangolo/fastapi/pull/10332) by [@AlertRED](https://github.com/AlertRED). +* 🌐 Add Chinese translation for `docs/zh/docs/deployment/server-workers.md`. PR [#10292](https://github.com/tiangolo/fastapi/pull/10292) by [@xzmeng](https://github.com/xzmeng). +* 🌐 Add Chinese translation for `docs/zh/docs/deployment/cloud.md`. PR [#10291](https://github.com/tiangolo/fastapi/pull/10291) by [@xzmeng](https://github.com/xzmeng). +* 🌐 Add Chinese translation for `docs/zh/docs/deployment/manually.md`. PR [#10279](https://github.com/tiangolo/fastapi/pull/10279) by [@xzmeng](https://github.com/xzmeng). +* 🌐 Add Chinese translation for `docs/zh/docs/deployment/https.md`. PR [#10277](https://github.com/tiangolo/fastapi/pull/10277) by [@xzmeng](https://github.com/xzmeng). +* 🌐 Add Chinese translation for `docs/zh/docs/deployment/index.md`. PR [#10275](https://github.com/tiangolo/fastapi/pull/10275) by [@xzmeng](https://github.com/xzmeng). +* 🌐 Add German translation for `docs/de/docs/tutorial/first-steps.md`. PR [#9530](https://github.com/tiangolo/fastapi/pull/9530) by [@fhabers21](https://github.com/fhabers21). +* 🌐 Update Turkish translation for `docs/tr/docs/index.md`. PR [#10444](https://github.com/tiangolo/fastapi/pull/10444) by [@hasansezertasan](https://github.com/hasansezertasan). +* 🌐 Add Chinese translation for `docs/zh/docs/learn/index.md`. PR [#10479](https://github.com/tiangolo/fastapi/pull/10479) by [@KAZAMA-DREAM](https://github.com/KAZAMA-DREAM). +* 🌐 Add Russian translation for `docs/ru/docs/learn/index.md`. PR [#10539](https://github.com/tiangolo/fastapi/pull/10539) by [@AlertRED](https://github.com/AlertRED). +* 🌐 Update SQLAlchemy instruction in Chinese translation `docs/zh/docs/tutorial/sql-databases.md`. PR [#9712](https://github.com/tiangolo/fastapi/pull/9712) by [@Royc30ne](https://github.com/Royc30ne). +* 🌐 Add Turkish translation for `docs/tr/docs/external-links.md`. PR [#10549](https://github.com/tiangolo/fastapi/pull/10549) by [@hasansezertasan](https://github.com/hasansezertasan). +* 🌐 Add Spanish translation for `docs/es/docs/learn/index.md`. PR [#10885](https://github.com/tiangolo/fastapi/pull/10885) by [@pablocm83](https://github.com/pablocm83). +* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/body-fields.md`. PR [#10670](https://github.com/tiangolo/fastapi/pull/10670) by [@ArtemKhymenko](https://github.com/ArtemKhymenko). +* 🌐 Add Hungarian translation for `/docs/hu/docs/index.md`. PR [#10812](https://github.com/tiangolo/fastapi/pull/10812) by [@takacs](https://github.com/takacs). +* 🌐 Add Turkish translation for `docs/tr/docs/newsletter.md`. PR [#10550](https://github.com/tiangolo/fastapi/pull/10550) by [@hasansezertasan](https://github.com/hasansezertasan). +* 🌐 Add Spanish translation for `docs/es/docs/help/index.md`. PR [#10907](https://github.com/tiangolo/fastapi/pull/10907) by [@pablocm83](https://github.com/pablocm83). +* 🌐 Add Spanish translation for `docs/es/docs/about/index.md`. PR [#10908](https://github.com/tiangolo/fastapi/pull/10908) by [@pablocm83](https://github.com/pablocm83). +* 🌐 Add Spanish translation for `docs/es/docs/resources/index.md`. PR [#10909](https://github.com/tiangolo/fastapi/pull/10909) by [@pablocm83](https://github.com/pablocm83). + +### Internal + +* 👥 Update FastAPI People. PR [#10871](https://github.com/tiangolo/fastapi/pull/10871) by [@tiangolo](https://github.com/tiangolo). +* 👷 Upgrade custom GitHub Action comment-docs-preview-in-pr. PR [#10916](https://github.com/tiangolo/fastapi/pull/10916) by [@tiangolo](https://github.com/tiangolo). +* ⬆️ Upgrade GitHub Action latest-changes. PR [#10915](https://github.com/tiangolo/fastapi/pull/10915) by [@tiangolo](https://github.com/tiangolo). +* 👷 Upgrade GitHub Action label-approved. PR [#10913](https://github.com/tiangolo/fastapi/pull/10913) by [@tiangolo](https://github.com/tiangolo). +* ⬆️ Upgrade GitHub Action label-approved. PR [#10905](https://github.com/tiangolo/fastapi/pull/10905) by [@tiangolo](https://github.com/tiangolo). + +## 0.108.0 + +### Upgrades + +* ⬆️ Upgrade Starlette to `>=0.29.0,<0.33.0`, update docs and usage of templates with new Starlette arguments. Remove pin of AnyIO `>=3.7.1,<4.0.0`, add support for AnyIO 4.x.x. PR [#10846](https://github.com/tiangolo/fastapi/pull/10846) by [@tiangolo](https://github.com/tiangolo). + +## 0.107.0 + +### Upgrades + +* ⬆️ Upgrade Starlette to 0.28.0. PR [#9636](https://github.com/tiangolo/fastapi/pull/9636) by [@adriangb](https://github.com/adriangb). + +### Docs + +* 📝 Add docs: Node.js script alternative to update OpenAPI for generated clients. PR [#10845](https://github.com/tiangolo/fastapi/pull/10845) by [@alejsdev](https://github.com/alejsdev). +* 📝 Restructure Docs section in Contributing page. PR [#10844](https://github.com/tiangolo/fastapi/pull/10844) by [@alejsdev](https://github.com/alejsdev). + +## 0.106.0 + +### Breaking Changes + +Using resources from dependencies with `yield` in background tasks is no longer supported. + +This change is what supports the new features, read below. 🤓 + +### Dependencies with `yield`, `HTTPException` and Background Tasks + +Dependencies with `yield` now can raise `HTTPException` and other exceptions after `yield`. 🎉 + +Read the new docs here: [Dependencies with `yield` and `HTTPException`](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/#dependencies-with-yield-and-httpexception). + +```Python +from fastapi import Depends, FastAPI, HTTPException +from typing_extensions import Annotated + +app = FastAPI() + + +data = { + "plumbus": {"description": "Freshly pickled plumbus", "owner": "Morty"}, + "portal-gun": {"description": "Gun to create portals", "owner": "Rick"}, +} + + +class OwnerError(Exception): + pass + + +def get_username(): + try: + yield "Rick" + except OwnerError as e: + raise HTTPException(status_code=400, detail=f"Owner error: {e}") + + +@app.get("/items/{item_id}") +def get_item(item_id: str, username: Annotated[str, Depends(get_username)]): + if item_id not in data: + raise HTTPException(status_code=404, detail="Item not found") + item = data[item_id] + if item["owner"] != username: + raise OwnerError(username) + return item +``` + +--- + +Before FastAPI 0.106.0, raising exceptions after `yield` was not possible, the exit code in dependencies with `yield` was executed *after* the response was sent, so [Exception Handlers](https://fastapi.tiangolo.com/tutorial/handling-errors/#install-custom-exception-handlers) would have already run. + +This was designed this way mainly to allow using the same objects "yielded" by dependencies inside of background tasks, because the exit code would be executed after the background tasks were finished. + +Nevertheless, as this would mean waiting for the response to travel through the network while unnecessarily holding a resource in a dependency with yield (for example a database connection), this was changed in FastAPI 0.106.0. + +Additionally, a background task is normally an independent set of logic that should be handled separately, with its own resources (e.g. its own database connection). + +If you used to rely on this behavior, now you should create the resources for background tasks inside the background task itself, and use internally only data that doesn't depend on the resources of dependencies with `yield`. + +For example, instead of using the same database session, you would create a new database session inside of the background task, and you would obtain the objects from the database using this new session. And then instead of passing the object from the database as a parameter to the background task function, you would pass the ID of that object and then obtain the object again inside the background task function. + +The sequence of execution before FastAPI 0.106.0 was like this diagram: + +Time flows from top to bottom. And each column is one of the parts interacting or executing code. + +```mermaid +sequenceDiagram + +participant client as Client +participant handler as Exception handler +participant dep as Dep with yield +participant operation as Path Operation +participant tasks as Background tasks + + Note over client,tasks: Can raise exception for dependency, handled after response is sent + Note over client,operation: Can raise HTTPException and can change the response + client ->> dep: Start request + Note over dep: Run code up to yield + opt raise + dep -->> handler: Raise HTTPException + handler -->> client: HTTP error response + dep -->> dep: Raise other exception + end + dep ->> operation: Run dependency, e.g. DB session + opt raise + operation -->> dep: Raise HTTPException + dep -->> handler: Auto forward exception + handler -->> client: HTTP error response + operation -->> dep: Raise other exception + dep -->> handler: Auto forward exception + end + operation ->> client: Return response to client + Note over client,operation: Response is already sent, can't change it anymore + opt Tasks + operation -->> tasks: Send background tasks + end + opt Raise other exception + tasks -->> dep: Raise other exception + end + Note over dep: After yield + opt Handle other exception + dep -->> dep: Handle exception, can't change response. E.g. close DB session. + end +``` + +The new execution flow can be found in the docs: [Execution of dependencies with `yield`](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/#execution-of-dependencies-with-yield). + +### Features + +* ✨ Add support for raising exceptions (including `HTTPException`) in dependencies with `yield` in the exit code, do not support them in background tasks. PR [#10831](https://github.com/tiangolo/fastapi/pull/10831) by [@tiangolo](https://github.com/tiangolo). + +### Internal + +* 👥 Update FastAPI People. PR [#10567](https://github.com/tiangolo/fastapi/pull/10567) by [@tiangolo](https://github.com/tiangolo). + +## 0.105.0 + +### Features + +* ✨ Add support for multiple Annotated annotations, e.g. `Annotated[str, Field(), Query()]`. PR [#10773](https://github.com/tiangolo/fastapi/pull/10773) by [@tiangolo](https://github.com/tiangolo). + +### Refactors + +* 🔥 Remove unused NoneType. PR [#10774](https://github.com/tiangolo/fastapi/pull/10774) by [@tiangolo](https://github.com/tiangolo). + +### Docs + +* 📝 Tweak default suggested configs for generating clients. PR [#10736](https://github.com/tiangolo/fastapi/pull/10736) by [@tiangolo](https://github.com/tiangolo). + +### Internal + +* 🔧 Update sponsors, add Scalar. PR [#10728](https://github.com/tiangolo/fastapi/pull/10728) by [@tiangolo](https://github.com/tiangolo). +* 🔧 Update sponsors, add PropelAuth. PR [#10760](https://github.com/tiangolo/fastapi/pull/10760) by [@tiangolo](https://github.com/tiangolo). +* 👷 Update build docs, verify README on CI. PR [#10750](https://github.com/tiangolo/fastapi/pull/10750) by [@tiangolo](https://github.com/tiangolo). +* 🔧 Update sponsors, remove Fern. PR [#10729](https://github.com/tiangolo/fastapi/pull/10729) by [@tiangolo](https://github.com/tiangolo). +* 🔧 Update sponsors, add Codacy. PR [#10677](https://github.com/tiangolo/fastapi/pull/10677) by [@tiangolo](https://github.com/tiangolo). +* 🔧 Update sponsors, add Reflex. PR [#10676](https://github.com/tiangolo/fastapi/pull/10676) by [@tiangolo](https://github.com/tiangolo). +* 📝 Update release notes, move and check latest-changes. PR [#10588](https://github.com/tiangolo/fastapi/pull/10588) by [@tiangolo](https://github.com/tiangolo). +* 👷 Upgrade latest-changes GitHub Action. PR [#10587](https://github.com/tiangolo/fastapi/pull/10587) by [@tiangolo](https://github.com/tiangolo). + +## 0.104.1 + +### Fixes + +* 📌 Pin Swagger UI version to 5.9.0 temporarily to handle a bug crashing it in 5.9.1. PR [#10529](https://github.com/tiangolo/fastapi/pull/10529) by [@alejandraklachquin](https://github.com/alejandraklachquin). + * This is not really a bug in FastAPI but in Swagger UI, nevertheless pinning the version will work while a solution is found on the [Swagger UI side](https://github.com/swagger-api/swagger-ui/issues/9337). + +### Docs + +* 📝 Update data structure and render for external-links. PR [#10495](https://github.com/tiangolo/fastapi/pull/10495) by [@tiangolo](https://github.com/tiangolo). +* ✏️ Fix link to SPDX license identifier in `docs/en/docs/tutorial/metadata.md`. PR [#10433](https://github.com/tiangolo/fastapi/pull/10433) by [@worldworm](https://github.com/worldworm). +* 📝 Update example validation error from Pydantic v1 to match Pydantic v2 in `docs/en/docs/tutorial/path-params.md`. PR [#10043](https://github.com/tiangolo/fastapi/pull/10043) by [@giuliowaitforitdavide](https://github.com/giuliowaitforitdavide). +* ✏️ Fix typos in emoji docs and in some source examples. PR [#10438](https://github.com/tiangolo/fastapi/pull/10438) by [@afuetterer](https://github.com/afuetterer). +* ✏️ Fix typo in `docs/en/docs/reference/dependencies.md`. PR [#10465](https://github.com/tiangolo/fastapi/pull/10465) by [@suravshresth](https://github.com/suravshresth). +* ✏️ Fix typos and rewordings in `docs/en/docs/tutorial/body-nested-models.md`. PR [#10468](https://github.com/tiangolo/fastapi/pull/10468) by [@yogabonito](https://github.com/yogabonito). +* 📝 Update docs, remove references to removed `pydantic.Required` in `docs/en/docs/tutorial/query-params-str-validations.md`. PR [#10469](https://github.com/tiangolo/fastapi/pull/10469) by [@yogabonito](https://github.com/yogabonito). +* ✏️ Fix typo in `docs/en/docs/reference/index.md`. PR [#10467](https://github.com/tiangolo/fastapi/pull/10467) by [@tarsil](https://github.com/tarsil). +* 🔥 Remove unnecessary duplicated docstrings. PR [#10484](https://github.com/tiangolo/fastapi/pull/10484) by [@tiangolo](https://github.com/tiangolo). + +### Internal + +* ✏️ Update Pydantic links to dotenv support. PR [#10511](https://github.com/tiangolo/fastapi/pull/10511) by [@White-Mask](https://github.com/White-Mask). +* ✏️ Update links in `docs/en/docs/async.md` and `docs/zh/docs/async.md` to make them relative. PR [#10498](https://github.com/tiangolo/fastapi/pull/10498) by [@hasnatsajid](https://github.com/hasnatsajid). +* ✏️ Fix links in `docs/em/docs/async.md`. PR [#10507](https://github.com/tiangolo/fastapi/pull/10507) by [@hasnatsajid](https://github.com/hasnatsajid). +* ✏️ Fix typo in `docs/em/docs/index.md`, Python 3.8. PR [#10521](https://github.com/tiangolo/fastapi/pull/10521) by [@kerriop](https://github.com/kerriop). +* ⬆ Bump pillow from 9.5.0 to 10.1.0. PR [#10446](https://github.com/tiangolo/fastapi/pull/10446) by [@dependabot[bot]](https://github.com/apps/dependabot). +* ⬆ Update mkdocs-material requirement from <9.0.0,>=8.1.4 to >=8.1.4,<10.0.0. PR [#5862](https://github.com/tiangolo/fastapi/pull/5862) by [@dependabot[bot]](https://github.com/apps/dependabot). +* ⬆ Bump mkdocs-material from 9.1.21 to 9.4.7. PR [#10545](https://github.com/tiangolo/fastapi/pull/10545) by [@dependabot[bot]](https://github.com/apps/dependabot). +* 👷 Install MkDocs Material Insiders only when secrets are available, for Dependabot. PR [#10544](https://github.com/tiangolo/fastapi/pull/10544) by [@tiangolo](https://github.com/tiangolo). +* 🔧 Update sponsors badges, Databento. PR [#10519](https://github.com/tiangolo/fastapi/pull/10519) by [@tiangolo](https://github.com/tiangolo). +* 👷 Adopt Ruff format. PR [#10517](https://github.com/tiangolo/fastapi/pull/10517) by [@tiangolo](https://github.com/tiangolo). +* 🔧 Add `CITATION.cff` file for academic citations. PR [#10496](https://github.com/tiangolo/fastapi/pull/10496) by [@tiangolo](https://github.com/tiangolo). +* 🐛 Fix overriding MKDocs theme lang in hook. PR [#10490](https://github.com/tiangolo/fastapi/pull/10490) by [@tiangolo](https://github.com/tiangolo). +* 🔥 Drop/close Gitter chat. Questions should go to GitHub Discussions, free conversations to Discord.. PR [#10485](https://github.com/tiangolo/fastapi/pull/10485) by [@tiangolo](https://github.com/tiangolo). + +## 0.104.0 + +## Features + +* ✨ Add reference (code API) docs with PEP 727, add subclass with custom docstrings for `BackgroundTasks`, refactor docs structure. PR [#10392](https://github.com/tiangolo/fastapi/pull/10392) by [@tiangolo](https://github.com/tiangolo). New docs at [FastAPI Reference - Code API](https://fastapi.tiangolo.com/reference/). + +## Upgrades + +* ⬆️ Drop support for Python 3.7, require Python 3.8 or above. PR [#10442](https://github.com/tiangolo/fastapi/pull/10442) by [@tiangolo](https://github.com/tiangolo). + +### Internal + +* ⬆ Bump dawidd6/action-download-artifact from 2.27.0 to 2.28.0. PR [#10268](https://github.com/tiangolo/fastapi/pull/10268) by [@dependabot[bot]](https://github.com/apps/dependabot). +* ⬆ Bump actions/checkout from 3 to 4. PR [#10208](https://github.com/tiangolo/fastapi/pull/10208) by [@dependabot[bot]](https://github.com/apps/dependabot). +* ⬆ Bump pypa/gh-action-pypi-publish from 1.8.6 to 1.8.10. PR [#10061](https://github.com/tiangolo/fastapi/pull/10061) by [@dependabot[bot]](https://github.com/apps/dependabot). +* 🔧 Update sponsors, Bump.sh images. PR [#10381](https://github.com/tiangolo/fastapi/pull/10381) by [@tiangolo](https://github.com/tiangolo). +* 👥 Update FastAPI People. PR [#10363](https://github.com/tiangolo/fastapi/pull/10363) by [@tiangolo](https://github.com/tiangolo). + +## 0.103.2 + +### Refactors + +* ⬆️ Upgrade compatibility with Pydantic v2.4, new renamed functions and JSON Schema input/output models with default values. PR [#10344](https://github.com/tiangolo/fastapi/pull/10344) by [@tiangolo](https://github.com/tiangolo). + +### Translations + +* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/extra-data-types.md`. PR [#10132](https://github.com/tiangolo/fastapi/pull/10132) by [@ArtemKhymenko](https://github.com/ArtemKhymenko). +* 🌐 Fix typos in French translations for `docs/fr/docs/advanced/path-operation-advanced-configuration.md`, `docs/fr/docs/alternatives.md`, `docs/fr/docs/async.md`, `docs/fr/docs/features.md`, `docs/fr/docs/help-fastapi.md`, `docs/fr/docs/index.md`, `docs/fr/docs/python-types.md`, `docs/fr/docs/tutorial/body.md`, `docs/fr/docs/tutorial/first-steps.md`, `docs/fr/docs/tutorial/query-params.md`. PR [#10154](https://github.com/tiangolo/fastapi/pull/10154) by [@s-rigaud](https://github.com/s-rigaud). +* 🌐 Add Chinese translation for `docs/zh/docs/async.md`. PR [#5591](https://github.com/tiangolo/fastapi/pull/5591) by [@mkdir700](https://github.com/mkdir700). +* 🌐 Update Chinese translation for `docs/tutorial/security/simple-oauth2.md`. PR [#3844](https://github.com/tiangolo/fastapi/pull/3844) by [@jaystone776](https://github.com/jaystone776). +* 🌐 Add Korean translation for `docs/ko/docs/deployment/cloud.md`. PR [#10191](https://github.com/tiangolo/fastapi/pull/10191) by [@Sion99](https://github.com/Sion99). +* 🌐 Add Japanese translation for `docs/ja/docs/deployment/https.md`. PR [#10298](https://github.com/tiangolo/fastapi/pull/10298) by [@tamtam-fitness](https://github.com/tamtam-fitness). +* 🌐 Fix typo in Russian translation for `docs/ru/docs/tutorial/body-fields.md`. PR [#10224](https://github.com/tiangolo/fastapi/pull/10224) by [@AlertRED](https://github.com/AlertRED). +* 🌐 Add Polish translation for `docs/pl/docs/help-fastapi.md`. PR [#10121](https://github.com/tiangolo/fastapi/pull/10121) by [@romabozhanovgithub](https://github.com/romabozhanovgithub). +* 🌐 Add Russian translation for `docs/ru/docs/tutorial/header-params.md`. PR [#10226](https://github.com/tiangolo/fastapi/pull/10226) by [@AlertRED](https://github.com/AlertRED). +* 🌐 Add Chinese translation for `docs/zh/docs/deployment/versions.md`. PR [#10276](https://github.com/tiangolo/fastapi/pull/10276) by [@xzmeng](https://github.com/xzmeng). + +### Internal + +* 🔧 Update sponsors, remove Flint. PR [#10349](https://github.com/tiangolo/fastapi/pull/10349) by [@tiangolo](https://github.com/tiangolo). +* 🔧 Rename label "awaiting review" to "awaiting-review" to simplify search queries. PR [#10343](https://github.com/tiangolo/fastapi/pull/10343) by [@tiangolo](https://github.com/tiangolo). +* 🔧 Update sponsors, enable Svix (revert #10228). PR [#10253](https://github.com/tiangolo/fastapi/pull/10253) by [@tiangolo](https://github.com/tiangolo). +* 🔧 Update sponsors, remove Svix. PR [#10228](https://github.com/tiangolo/fastapi/pull/10228) by [@tiangolo](https://github.com/tiangolo). +* 🔧 Update sponsors, add Bump.sh. PR [#10227](https://github.com/tiangolo/fastapi/pull/10227) by [@tiangolo](https://github.com/tiangolo). + +## 0.103.1 + +### Fixes + +* 📌 Pin AnyIO to < 4.0.0 to handle an incompatibility while upgrading to Starlette 0.31.1. PR [#10194](https://github.com/tiangolo/fastapi/pull/10194) by [@tiangolo](https://github.com/tiangolo). + +### Docs + +* ✏️ Fix validation parameter name in docs, from `regex` to `pattern`. PR [#10085](https://github.com/tiangolo/fastapi/pull/10085) by [@pablodorrio](https://github.com/pablodorrio). +* ✏️ Fix indent format in `docs/en/docs/deployment/server-workers.md`. PR [#10066](https://github.com/tiangolo/fastapi/pull/10066) by [@tamtam-fitness](https://github.com/tamtam-fitness). +* ✏️ Fix Pydantic examples in tutorial for Python types. PR [#9961](https://github.com/tiangolo/fastapi/pull/9961) by [@rahulsalgare](https://github.com/rahulsalgare). +* ✏️ Fix link to Pydantic docs in `docs/en/docs/tutorial/extra-data-types.md`. PR [#10155](https://github.com/tiangolo/fastapi/pull/10155) by [@hasnatsajid](https://github.com/hasnatsajid). +* ✏️ Fix typo in `docs/en/docs/tutorial/handling-errors.md`. PR [#10170](https://github.com/tiangolo/fastapi/pull/10170) by [@poupapaa](https://github.com/poupapaa). +* ✏️ Fix typo in `docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md`. PR [#10172](https://github.com/tiangolo/fastapi/pull/10172) by [@ragul-kachiappan](https://github.com/ragul-kachiappan). + +### Translations + +* 🌐 Remove duplicate line in translation for `docs/pt/docs/tutorial/path-params.md`. PR [#10126](https://github.com/tiangolo/fastapi/pull/10126) by [@LecoOliveira](https://github.com/LecoOliveira). +* 🌐 Add Yoruba translation for `docs/yo/docs/index.md`. PR [#10033](https://github.com/tiangolo/fastapi/pull/10033) by [@AfolabiOlaoluwa](https://github.com/AfolabiOlaoluwa). +* 🌐 Add Ukrainian translation for `docs/uk/docs/python-types.md`. PR [#10080](https://github.com/tiangolo/fastapi/pull/10080) by [@rostik1410](https://github.com/rostik1410). +* 🌐 Add Vietnamese translations for `docs/vi/docs/tutorial/first-steps.md` and `docs/vi/docs/tutorial/index.md`. PR [#10088](https://github.com/tiangolo/fastapi/pull/10088) by [@magiskboy](https://github.com/magiskboy). +* 🌐 Add Ukrainian translation for `docs/uk/docs/alternatives.md`. PR [#10060](https://github.com/tiangolo/fastapi/pull/10060) by [@whysage](https://github.com/whysage). +* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/index.md`. PR [#10079](https://github.com/tiangolo/fastapi/pull/10079) by [@rostik1410](https://github.com/rostik1410). +* ✏️ Fix typos in `docs/en/docs/how-to/separate-openapi-schemas.md` and `docs/en/docs/tutorial/schema-extra-example.md`. PR [#10189](https://github.com/tiangolo/fastapi/pull/10189) by [@xzmeng](https://github.com/xzmeng). +* 🌐 Add Chinese translation for `docs/zh/docs/advanced/generate-clients.md`. PR [#9883](https://github.com/tiangolo/fastapi/pull/9883) by [@funny-cat-happy](https://github.com/funny-cat-happy). + +### Refactors + +* ✏️ Fix typos in comment in `fastapi/applications.py`. PR [#10045](https://github.com/tiangolo/fastapi/pull/10045) by [@AhsanSheraz](https://github.com/AhsanSheraz). +* ✅ Add missing test for OpenAPI examples, it was missing in coverage. PR [#10188](https://github.com/tiangolo/fastapi/pull/10188) by [@tiangolo](https://github.com/tiangolo). + +### Internal + +* 👥 Update FastAPI People. PR [#10186](https://github.com/tiangolo/fastapi/pull/10186) by [@tiangolo](https://github.com/tiangolo). + +## 0.103.0 + +### Features + +* ✨ Add support for `openapi_examples` in all FastAPI parameters. PR [#10152](https://github.com/tiangolo/fastapi/pull/10152) by [@tiangolo](https://github.com/tiangolo). + * New docs: [OpenAPI-specific examples](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#openapi-specific-examples). + +### Docs + +* 📝 Add note to docs about Separate Input and Output Schemas with FastAPI version. PR [#10150](https://github.com/tiangolo/fastapi/pull/10150) by [@tiangolo](https://github.com/tiangolo). + +## 0.102.0 + +### Features + +* ✨ Add support for disabling the separation of input and output JSON Schemas in OpenAPI with Pydantic v2 with `separate_input_output_schemas=False`. PR [#10145](https://github.com/tiangolo/fastapi/pull/10145) by [@tiangolo](https://github.com/tiangolo). + * New docs [Separate OpenAPI Schemas for Input and Output or Not](https://fastapi.tiangolo.com/how-to/separate-openapi-schemas/). + * This PR also includes a new setup (internal tools) for generating screenshots for the docs. + +### Refactors + +* ♻️ Refactor tests for new Pydantic 2.2.1. PR [#10115](https://github.com/tiangolo/fastapi/pull/10115) by [@tiangolo](https://github.com/tiangolo). + +### Docs + +* 📝 Add new docs section, How To - Recipes, move docs that don't have to be read by everyone to How To. PR [#10114](https://github.com/tiangolo/fastapi/pull/10114) by [@tiangolo](https://github.com/tiangolo). +* 📝 Update Advanced docs, add links to sponsor courses. PR [#10113](https://github.com/tiangolo/fastapi/pull/10113) by [@tiangolo](https://github.com/tiangolo). +* 📝 Update docs for generating clients. PR [#10112](https://github.com/tiangolo/fastapi/pull/10112) by [@tiangolo](https://github.com/tiangolo). +* 📝 Tweak MkDocs and add redirects. PR [#10111](https://github.com/tiangolo/fastapi/pull/10111) by [@tiangolo](https://github.com/tiangolo). +* 📝 Restructure docs for cloud providers, include links to sponsors. PR [#10110](https://github.com/tiangolo/fastapi/pull/10110) by [@tiangolo](https://github.com/tiangolo). + +### Internal + +* 🔧 Update sponsors, add Speakeasy. PR [#10098](https://github.com/tiangolo/fastapi/pull/10098) by [@tiangolo](https://github.com/tiangolo). + +## 0.101.1 + +### Fixes + +* ✨ Add `ResponseValidationError` printable details, to show up in server error logs. PR [#10078](https://github.com/tiangolo/fastapi/pull/10078) by [@tiangolo](https://github.com/tiangolo). + +### Refactors + +* ✏️ Fix typo in deprecation warnings in `fastapi/params.py`. PR [#9854](https://github.com/tiangolo/fastapi/pull/9854) by [@russbiggs](https://github.com/russbiggs). +* ✏️ Fix typos in comments on internal code in `fastapi/concurrency.py` and `fastapi/routing.py`. PR [#9590](https://github.com/tiangolo/fastapi/pull/9590) by [@ElliottLarsen](https://github.com/ElliottLarsen). + +### Docs + +* ✏️ Fix typo in release notes. PR [#9835](https://github.com/tiangolo/fastapi/pull/9835) by [@francisbergin](https://github.com/francisbergin). +* 📝 Add external article: Build an SMS Spam Classifier Serverless Database with FaunaDB and FastAPI. PR [#9847](https://github.com/tiangolo/fastapi/pull/9847) by [@adejumoridwan](https://github.com/adejumoridwan). +* 📝 Fix typo in `docs/en/docs/contributing.md`. PR [#9878](https://github.com/tiangolo/fastapi/pull/9878) by [@VicenteMerino](https://github.com/VicenteMerino). +* 📝 Fix code highlighting in `docs/en/docs/tutorial/bigger-applications.md`. PR [#9806](https://github.com/tiangolo/fastapi/pull/9806) by [@theonlykingpin](https://github.com/theonlykingpin). + +### Translations + +* 🌐 Add Japanese translation for `docs/ja/docs/deployment/concepts.md`. PR [#10062](https://github.com/tiangolo/fastapi/pull/10062) by [@tamtam-fitness](https://github.com/tamtam-fitness). +* 🌐 Add Japanese translation for `docs/ja/docs/deployment/server-workers.md`. PR [#10064](https://github.com/tiangolo/fastapi/pull/10064) by [@tamtam-fitness](https://github.com/tamtam-fitness). +* 🌐 Update Japanese translation for `docs/ja/docs/deployment/docker.md`. PR [#10073](https://github.com/tiangolo/fastapi/pull/10073) by [@tamtam-fitness](https://github.com/tamtam-fitness). +* 🌐 Add Ukrainian translation for `docs/uk/docs/fastapi-people.md`. PR [#10059](https://github.com/tiangolo/fastapi/pull/10059) by [@rostik1410](https://github.com/rostik1410). +* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/cookie-params.md`. PR [#10032](https://github.com/tiangolo/fastapi/pull/10032) by [@rostik1410](https://github.com/rostik1410). +* 🌐 Add Russian translation for `docs/ru/docs/deployment/docker.md`. PR [#9971](https://github.com/tiangolo/fastapi/pull/9971) by [@Xewus](https://github.com/Xewus). +* 🌐 Add Vietnamese translation for `docs/vi/docs/python-types.md`. PR [#10047](https://github.com/tiangolo/fastapi/pull/10047) by [@magiskboy](https://github.com/magiskboy). +* 🌐 Add Russian translation for `docs/ru/docs/tutorial/dependencies/global-dependencies.md`. PR [#9970](https://github.com/tiangolo/fastapi/pull/9970) by [@dudyaosuplayer](https://github.com/dudyaosuplayer). +* 🌐 Add Urdu translation for `docs/ur/docs/benchmarks.md`. PR [#9974](https://github.com/tiangolo/fastapi/pull/9974) by [@AhsanSheraz](https://github.com/AhsanSheraz). + +### Internal + +* 🔧 Add sponsor Porter. PR [#10051](https://github.com/tiangolo/fastapi/pull/10051) by [@tiangolo](https://github.com/tiangolo). +* 🔧 Update sponsors, add Jina back as bronze sponsor. PR [#10050](https://github.com/tiangolo/fastapi/pull/10050) by [@tiangolo](https://github.com/tiangolo). +* ⬆ Bump mypy from 1.4.0 to 1.4.1. PR [#9756](https://github.com/tiangolo/fastapi/pull/9756) by [@dependabot[bot]](https://github.com/apps/dependabot). +* ⬆ Bump mkdocs-material from 9.1.17 to 9.1.21. PR [#9960](https://github.com/tiangolo/fastapi/pull/9960) by [@dependabot[bot]](https://github.com/apps/dependabot). + +## 0.101.0 + +### Features + +* ✨ Enable Pydantic's serialization mode for responses, add support for Pydantic's `computed_field`, better OpenAPI for response models, proper required attributes, better generated clients. PR [#10011](https://github.com/tiangolo/fastapi/pull/10011) by [@tiangolo](https://github.com/tiangolo). + +### Refactors + +* ✅ Fix tests for compatibility with pydantic 2.1.1. PR [#9943](https://github.com/tiangolo/fastapi/pull/9943) by [@dmontagu](https://github.com/dmontagu). +* ✅ Fix test error in Windows for `jsonable_encoder`. PR [#9840](https://github.com/tiangolo/fastapi/pull/9840) by [@iudeen](https://github.com/iudeen). + +### Upgrades + +* 📌 Do not allow Pydantic 2.1.0 that breaks (require 2.1.1). PR [#10012](https://github.com/tiangolo/fastapi/pull/10012) by [@tiangolo](https://github.com/tiangolo). + +### Translations + +* 🌐 Add Russian translation for `docs/ru/docs/tutorial/security/index.md`. PR [#9963](https://github.com/tiangolo/fastapi/pull/9963) by [@eVery1337](https://github.com/eVery1337). +* 🌐 Remove Vietnamese note about missing translation. PR [#9957](https://github.com/tiangolo/fastapi/pull/9957) by [@tiangolo](https://github.com/tiangolo). + +### Internal + +* 👷 Add GitHub Actions step dump context to debug external failures. PR [#10008](https://github.com/tiangolo/fastapi/pull/10008) by [@tiangolo](https://github.com/tiangolo). +* 🔧 Restore MkDocs Material pin after the fix. PR [#10001](https://github.com/tiangolo/fastapi/pull/10001) by [@tiangolo](https://github.com/tiangolo). +* 🔧 Update the Question template to ask for the Pydantic version. PR [#10000](https://github.com/tiangolo/fastapi/pull/10000) by [@tiangolo](https://github.com/tiangolo). +* 📍 Update MkDocs Material dependencies. PR [#9986](https://github.com/tiangolo/fastapi/pull/9986) by [@tiangolo](https://github.com/tiangolo). +* 👥 Update FastAPI People. PR [#9999](https://github.com/tiangolo/fastapi/pull/9999) by [@tiangolo](https://github.com/tiangolo). +* 🐳 Update Dockerfile with compatibility versions, to upgrade later. PR [#9998](https://github.com/tiangolo/fastapi/pull/9998) by [@tiangolo](https://github.com/tiangolo). +* ➕ Add pydantic-settings to FastAPI People dependencies. PR [#9988](https://github.com/tiangolo/fastapi/pull/9988) by [@tiangolo](https://github.com/tiangolo). +* ♻️ Update FastAPI People logic with new Pydantic. PR [#9985](https://github.com/tiangolo/fastapi/pull/9985) by [@tiangolo](https://github.com/tiangolo). +* 🍱 Update sponsors, Fern badge. PR [#9982](https://github.com/tiangolo/fastapi/pull/9982) by [@tiangolo](https://github.com/tiangolo). +* 👷 Deploy docs to Cloudflare Pages. PR [#9978](https://github.com/tiangolo/fastapi/pull/9978) by [@tiangolo](https://github.com/tiangolo). +* 🔧 Update sponsor Fern. PR [#9979](https://github.com/tiangolo/fastapi/pull/9979) by [@tiangolo](https://github.com/tiangolo). +* 👷 Update CI debug mode with Tmate. PR [#9977](https://github.com/tiangolo/fastapi/pull/9977) by [@tiangolo](https://github.com/tiangolo). + +## 0.100.1 + +### Fixes + +* 🐛 Replace `MultHostUrl` to `AnyUrl` for compatibility with older versions of Pydantic v1. PR [#9852](https://github.com/tiangolo/fastapi/pull/9852) by [@Kludex](https://github.com/Kludex). + +### Docs + +* 📝 Update links for self-hosted Swagger UI, point to v5, for OpenAPI 31.0. PR [#9834](https://github.com/tiangolo/fastapi/pull/9834) by [@tiangolo](https://github.com/tiangolo). + +### Translations + +* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/body.md`. PR [#4574](https://github.com/tiangolo/fastapi/pull/4574) by [@ss-o-furda](https://github.com/ss-o-furda). +* 🌐 Add Vietnamese translation for `docs/vi/docs/features.md` and `docs/vi/docs/index.md`. PR [#3006](https://github.com/tiangolo/fastapi/pull/3006) by [@magiskboy](https://github.com/magiskboy). +* 🌐 Add Korean translation for `docs/ko/docs/async.md`. PR [#4179](https://github.com/tiangolo/fastapi/pull/4179) by [@NinaHwang](https://github.com/NinaHwang). +* 🌐 Add Chinese translation for `docs/zh/docs/tutorial/background-tasks.md`. PR [#9812](https://github.com/tiangolo/fastapi/pull/9812) by [@wdh99](https://github.com/wdh99). +* 🌐 Add French translation for `docs/fr/docs/tutorial/query-params-str-validations.md`. PR [#4075](https://github.com/tiangolo/fastapi/pull/4075) by [@Smlep](https://github.com/Smlep). +* 🌐 Add French translation for `docs/fr/docs/tutorial/index.md`. PR [#2234](https://github.com/tiangolo/fastapi/pull/2234) by [@JulianMaurin](https://github.com/JulianMaurin). +* 🌐 Add French translation for `docs/fr/docs/contributing.md`. PR [#2132](https://github.com/tiangolo/fastapi/pull/2132) by [@JulianMaurin](https://github.com/JulianMaurin). +* 🌐 Add French translation for `docs/fr/docs/benchmarks.md`. PR [#2155](https://github.com/tiangolo/fastapi/pull/2155) by [@clemsau](https://github.com/clemsau). +* 🌐 Update Chinese translations with new source files. PR [#9738](https://github.com/tiangolo/fastapi/pull/9738) by [@mahone3297](https://github.com/mahone3297). +* 🌐 Add Russian translation for `docs/ru/docs/tutorial/request-forms.md`. PR [#9841](https://github.com/tiangolo/fastapi/pull/9841) by [@dedkot01](https://github.com/dedkot01). +* 🌐 Update Chinese translation for `docs/zh/docs/tutorial/handling-errors.md`. PR [#9485](https://github.com/tiangolo/fastapi/pull/9485) by [@Creat55](https://github.com/Creat55). + +### Internal + +* 🔧 Update sponsors, add Fern. PR [#9956](https://github.com/tiangolo/fastapi/pull/9956) by [@tiangolo](https://github.com/tiangolo). +* 👷 Update FastAPI People token. PR [#9844](https://github.com/tiangolo/fastapi/pull/9844) by [@tiangolo](https://github.com/tiangolo). +* 👥 Update FastAPI People. PR [#9775](https://github.com/tiangolo/fastapi/pull/9775) by [@tiangolo](https://github.com/tiangolo). +* 👷 Update MkDocs Material token. PR [#9843](https://github.com/tiangolo/fastapi/pull/9843) by [@tiangolo](https://github.com/tiangolo). +* 👷 Update token for latest changes. PR [#9842](https://github.com/tiangolo/fastapi/pull/9842) by [@tiangolo](https://github.com/tiangolo). + +## 0.100.0 + +✨ Support for **Pydantic v2** ✨ + +Pydantic version 2 has the **core** re-written in **Rust** and includes a lot of improvements and features, for example: + +* Improved **correctness** in corner cases. +* **Safer** types. +* Better **performance** and **less energy** consumption. +* Better **extensibility**. +* etc. + +...all this while keeping the **same Python API**. In most of the cases, for simple models, you can simply upgrade the Pydantic version and get all the benefits. 🚀 + +In some cases, for pure data validation and processing, you can get performance improvements of **20x** or more. This means 2,000% or more. 🤯 + +When you use **FastAPI**, there's a lot more going on, processing the request and response, handling dependencies, executing **your own code**, and particularly, **waiting for the network**. But you will probably still get some nice performance improvements just from the upgrade. + +The focus of this release is **compatibility** with Pydantic v1 and v2, to make sure your current apps keep working. Later there will be more focus on refactors, correctness, code improvements, and then **performance** improvements. Some third-party early beta testers that ran benchmarks on the beta releases of FastAPI reported improvements of **2x - 3x**. Which is not bad for just doing `pip install --upgrade fastapi pydantic`. This was not an official benchmark and I didn't check it myself, but it's a good sign. + +### Migration + +Check out the [Pydantic migration guide](https://docs.pydantic.dev/2.0/migration/). + +For the things that need changes in your Pydantic models, the Pydantic team built [`bump-pydantic`](https://github.com/pydantic/bump-pydantic). + +A command line tool that will **process your code** and update most of the things **automatically** for you. Make sure you have your code in git first, and review each of the changes to make sure everything is correct before committing the changes. + +### Pydantic v1 + +**This version of FastAPI still supports Pydantic v1**. And although Pydantic v1 will be deprecated at some point, it will still be supported for a while. + +This means that you can install the new Pydantic v2, and if something fails, you can install Pydantic v1 while you fix any problems you might have, but having the latest FastAPI. + +There are **tests for both Pydantic v1 and v2**, and test **coverage** is kept at **100%**. + +### Changes + +* There are **new parameter** fields supported by Pydantic `Field()` for: + + * `Path()` + * `Query()` + * `Header()` + * `Cookie()` + * `Body()` + * `Form()` + * `File()` + +* The new parameter fields are: + + * `default_factory` + * `alias_priority` + * `validation_alias` + * `serialization_alias` + * `discriminator` + * `strict` + * `multiple_of` + * `allow_inf_nan` + * `max_digits` + * `decimal_places` + * `json_schema_extra` + +...you can read about them in the Pydantic docs. + +* The parameter `regex` has been deprecated and replaced by `pattern`. + * You can read more about it in the docs for [Query Parameters and String Validations: Add regular expressions](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#add-regular-expressions). +* New Pydantic models use an improved and simplified attribute `model_config` that takes a simple dict instead of an internal class `Config` for their configuration. + * You can read more about it in the docs for [Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/). +* The attribute `schema_extra` for the internal class `Config` has been replaced by the key `json_schema_extra` in the new `model_config` dict. + * You can read more about it in the docs for [Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/). +* When you install `"fastapi[all]"` it now also includes: + * pydantic-settings - for settings management. + * pydantic-extra-types - for extra types to be used with Pydantic. +* Now Pydantic Settings is an additional optional package (included in `"fastapi[all]"`). To use settings you should now import `from pydantic_settings import BaseSettings` instead of importing from `pydantic` directly. + * You can read more about it in the docs for [Settings and Environment Variables](https://fastapi.tiangolo.com/advanced/settings/). + +* PR [#9816](https://github.com/tiangolo/fastapi/pull/9816) by [@tiangolo](https://github.com/tiangolo), included all the work done (in multiple PRs) on the beta branch (`main-pv2`). + +## 0.99.1 + +### Fixes + +* 🐛 Fix JSON Schema accepting bools as valid JSON Schemas, e.g. `additionalProperties: false`. PR [#9781](https://github.com/tiangolo/fastapi/pull/9781) by [@tiangolo](https://github.com/tiangolo). + +### Docs + +* 📝 Update source examples to use new JSON Schema examples field. PR [#9776](https://github.com/tiangolo/fastapi/pull/9776) by [@tiangolo](https://github.com/tiangolo). + +## 0.99.0 + +### Features + +* ✨ Add support for OpenAPI 3.1.0. PR [#9770](https://github.com/tiangolo/fastapi/pull/9770) by [@tiangolo](https://github.com/tiangolo). + * New support for documenting **webhooks**, read the new docs here: Advanced User Guide: OpenAPI Webhooks. + * Upgrade OpenAPI 3.1.0, this uses JSON Schema 2020-12. + * Upgrade Swagger UI to version 5.x.x, that supports OpenAPI 3.1.0. + * Updated `examples` field in `Query()`, `Cookie()`, `Body()`, etc. based on the latest JSON Schema and OpenAPI. Now it takes a list of examples and they are included directly in the JSON Schema, not outside. Read more about it (including the historical technical details) in the updated docs: Tutorial: Declare Request Example Data. + +* ✨ Add support for `deque` objects and children in `jsonable_encoder`. PR [#9433](https://github.com/tiangolo/fastapi/pull/9433) by [@cranium](https://github.com/cranium). + +### Docs + * 📝 Fix form for the FastAPI and friends newsletter. PR [#9749](https://github.com/tiangolo/fastapi/pull/9749) by [@tiangolo](https://github.com/tiangolo). + +### Translations + +* 🌐 Add Persian translation for `docs/fa/docs/advanced/sub-applications.md`. PR [#9692](https://github.com/tiangolo/fastapi/pull/9692) by [@mojtabapaso](https://github.com/mojtabapaso). +* 🌐 Add Russian translation for `docs/ru/docs/tutorial/response-model.md`. PR [#9675](https://github.com/tiangolo/fastapi/pull/9675) by [@glsglsgls](https://github.com/glsglsgls). + +### Internal + +* 🔨 Enable linenums in MkDocs Material during local live development to simplify highlighting code. PR [#9769](https://github.com/tiangolo/fastapi/pull/9769) by [@tiangolo](https://github.com/tiangolo). +* ⬆ Update httpx requirement from <0.24.0,>=0.23.0 to >=0.23.0,<0.25.0. PR [#9724](https://github.com/tiangolo/fastapi/pull/9724) by [@dependabot[bot]](https://github.com/apps/dependabot). +* ⬆ Bump mkdocs-material from 9.1.16 to 9.1.17. PR [#9746](https://github.com/tiangolo/fastapi/pull/9746) by [@dependabot[bot]](https://github.com/apps/dependabot). +* 🔥 Remove missing translation dummy pages, no longer necessary. PR [#9751](https://github.com/tiangolo/fastapi/pull/9751) by [@tiangolo](https://github.com/tiangolo). +* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#9259](https://github.com/tiangolo/fastapi/pull/9259) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). * ✨ Add Material for MkDocs Insiders features and cards. PR [#9748](https://github.com/tiangolo/fastapi/pull/9748) by [@tiangolo](https://github.com/tiangolo). * 🔥 Remove languages without translations. PR [#9743](https://github.com/tiangolo/fastapi/pull/9743) by [@tiangolo](https://github.com/tiangolo). * ✨ Refactor docs for building scripts, use MkDocs hooks, simplify (remove) configs for languages. PR [#9742](https://github.com/tiangolo/fastapi/pull/9742) by [@tiangolo](https://github.com/tiangolo). @@ -2612,7 +3593,7 @@ Note: all the previous parameters are still there, so it's still possible to dec * Upgrade Pydantic supported version to `0.29.0`. * New supported version range is `"pydantic >=0.28,<=0.29.0"`. - * This adds support for Pydantic [Generic Models](https://pydantic-docs.helpmanual.io/#generic-models), kudos to [@dmontagu](https://github.com/dmontagu). + * This adds support for Pydantic [Generic Models](https://docs.pydantic.dev/latest/#generic-models), kudos to [@dmontagu](https://github.com/dmontagu). * PR [#344](https://github.com/tiangolo/fastapi/pull/344). ## 0.30.1 @@ -2772,7 +3753,7 @@ Note: all the previous parameters are still there, so it's still possible to dec * Add OAuth2 redirect page for Swagger UI. This allows having delegated authentication in the Swagger UI docs. For this to work, you need to add `{your_origin}/docs/oauth2-redirect` to the allowed callbacks in your OAuth2 provider (in Auth0, Facebook, Google, etc). * For example, during development, it could be `http://localhost:8000/docs/oauth2-redirect`. - * Have in mind that this callback URL is independent of whichever one is used by your frontend. You might also have another callback at `https://yourdomain.com/login/callback`. + * Keep in mind that this callback URL is independent of whichever one is used by your frontend. You might also have another callback at `https://yourdomain.com/login/callback`. * This is only to allow delegated authentication in the API docs with Swagger UI. * PR [#198](https://github.com/tiangolo/fastapi/pull/198) by [@steinitzu](https://github.com/steinitzu). diff --git a/docs/en/docs/resources/index.md b/docs/en/docs/resources/index.md new file mode 100644 index 0000000000000..8c7cac43bd825 --- /dev/null +++ b/docs/en/docs/resources/index.md @@ -0,0 +1,3 @@ +# Resources + +Additional resources, external links, articles and more. ✈️ diff --git a/docs/en/docs/tutorial/background-tasks.md b/docs/en/docs/tutorial/background-tasks.md index 1782971922ab2..bc8e2af6a08d9 100644 --- a/docs/en/docs/tutorial/background-tasks.md +++ b/docs/en/docs/tutorial/background-tasks.md @@ -69,7 +69,7 @@ Using `BackgroundTasks` also works with the dependency injection system, you can {!> ../../../docs_src/background_tasks/tutorial002_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="14 16 23 26" {!> ../../../docs_src/background_tasks/tutorial002_an.py!} @@ -84,7 +84,7 @@ Using `BackgroundTasks` also works with the dependency injection system, you can {!> ../../../docs_src/background_tasks/tutorial002_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. diff --git a/docs/en/docs/tutorial/bigger-applications.md b/docs/en/docs/tutorial/bigger-applications.md index daa7353a2e258..b2d92840523a3 100644 --- a/docs/en/docs/tutorial/bigger-applications.md +++ b/docs/en/docs/tutorial/bigger-applications.md @@ -79,7 +79,7 @@ You can create the *path operations* for that module using `APIRouter`. You import it and create an "instance" the same way you would with the class `FastAPI`: -```Python hl_lines="1 3" +```Python hl_lines="1 3" title="app/routers/users.py" {!../../../docs_src/bigger_applications/app/routers/users.py!} ``` @@ -89,7 +89,7 @@ And then you use it to declare your *path operations*. Use it the same way you would use the `FastAPI` class: -```Python hl_lines="6 11 16" +```Python hl_lines="6 11 16" title="app/routers/users.py" {!../../../docs_src/bigger_applications/app/routers/users.py!} ``` @@ -114,22 +114,22 @@ We will now use a simple dependency to read a custom `X-Token` header: === "Python 3.9+" - ```Python hl_lines="3 6-8" + ```Python hl_lines="3 6-8" title="app/dependencies.py" {!> ../../../docs_src/bigger_applications/app_an_py39/dependencies.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" - ```Python hl_lines="1 5-7" + ```Python hl_lines="1 5-7" title="app/dependencies.py" {!> ../../../docs_src/bigger_applications/app_an/dependencies.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="1 4-6" + ```Python hl_lines="1 4-6" title="app/dependencies.py" {!> ../../../docs_src/bigger_applications/app/dependencies.py!} ``` @@ -160,7 +160,7 @@ We know all the *path operations* in this module have the same: So, instead of adding all that to each *path operation*, we can add it to the `APIRouter`. -```Python hl_lines="5-10 16 21" +```Python hl_lines="5-10 16 21" title="app/routers/items.py" {!../../../docs_src/bigger_applications/app/routers/items.py!} ``` @@ -212,7 +212,7 @@ And we need to get the dependency function from the module `app.dependencies`, t So we use a relative import with `..` for the dependencies: -```Python hl_lines="3" +```Python hl_lines="3" title="app/routers/items.py" {!../../../docs_src/bigger_applications/app/routers/items.py!} ``` @@ -282,7 +282,7 @@ We are not adding the prefix `/items` nor the `tags=["items"]` to each *path ope But we can still add _more_ `tags` that will be applied to a specific *path operation*, and also some extra `responses` specific to that *path operation*: -```Python hl_lines="30-31" +```Python hl_lines="30-31" title="app/routers/items.py" {!../../../docs_src/bigger_applications/app/routers/items.py!} ``` @@ -307,7 +307,7 @@ You import and create a `FastAPI` class as normally. And we can even declare [global dependencies](dependencies/global-dependencies.md){.internal-link target=_blank} that will be combined with the dependencies for each `APIRouter`: -```Python hl_lines="1 3 7" +```Python hl_lines="1 3 7" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` @@ -315,7 +315,7 @@ And we can even declare [global dependencies](dependencies/global-dependencies.m Now we import the other submodules that have `APIRouter`s: -```Python hl_lines="5" +```Python hl_lines="4-5" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` @@ -377,7 +377,7 @@ The `router` from `users` would overwrite the one from `items` and we wouldn't b So, to be able to use both of them in the same file, we import the submodules directly: -```Python hl_lines="4" +```Python hl_lines="5" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` @@ -385,7 +385,7 @@ So, to be able to use both of them in the same file, we import the submodules di Now, let's include the `router`s from the submodules `users` and `items`: -```Python hl_lines="10-11" +```Python hl_lines="10-11" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` @@ -418,7 +418,7 @@ It contains an `APIRouter` with some admin *path operations* that your organizat For this example it will be super simple. But let's say that because it is shared with other projects in the organization, we cannot modify it and add a `prefix`, `dependencies`, `tags`, etc. directly to the `APIRouter`: -```Python hl_lines="3" +```Python hl_lines="3" title="app/internal/admin.py" {!../../../docs_src/bigger_applications/app/internal/admin.py!} ``` @@ -426,7 +426,7 @@ But we still want to set a custom `prefix` when including the `APIRouter` so tha We can declare all that without having to modify the original `APIRouter` by passing those parameters to `app.include_router()`: -```Python hl_lines="14-17" +```Python hl_lines="14-17" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` @@ -449,7 +449,7 @@ We can also add *path operations* directly to the `FastAPI` app. Here we do it... just to show that we can 🤷: -```Python hl_lines="21-23" +```Python hl_lines="21-23" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` diff --git a/docs/en/docs/tutorial/body-fields.md b/docs/en/docs/tutorial/body-fields.md index 8966032ff1473..55e67fdd638d7 100644 --- a/docs/en/docs/tutorial/body-fields.md +++ b/docs/en/docs/tutorial/body-fields.md @@ -18,7 +18,7 @@ First, you have to import it: {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="4" {!> ../../../docs_src/body_fields/tutorial001_an.py!} @@ -33,7 +33,7 @@ First, you have to import it: {!> ../../../docs_src/body_fields/tutorial001_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -61,7 +61,7 @@ You can then use `Field` with model attributes: {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="12-15" {!> ../../../docs_src/body_fields/tutorial001_an.py!} @@ -76,7 +76,7 @@ You can then use `Field` with model attributes: {!> ../../../docs_src/body_fields/tutorial001_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. diff --git a/docs/en/docs/tutorial/body-multiple-params.md b/docs/en/docs/tutorial/body-multiple-params.md index b214092c9b175..ebef8eeaa9352 100644 --- a/docs/en/docs/tutorial/body-multiple-params.md +++ b/docs/en/docs/tutorial/body-multiple-params.md @@ -20,7 +20,7 @@ And you can also declare body parameters as optional, by setting the default to {!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="19-21" {!> ../../../docs_src/body_multiple_params/tutorial001_an.py!} @@ -35,7 +35,7 @@ And you can also declare body parameters as optional, by setting the default to {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -68,7 +68,7 @@ But you can also declare multiple body parameters, e.g. `item` and `user`: {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="22" {!> ../../../docs_src/body_multiple_params/tutorial002.py!} @@ -123,7 +123,7 @@ But you can instruct **FastAPI** to treat it as another body key using `Body`: {!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="24" {!> ../../../docs_src/body_multiple_params/tutorial003_an.py!} @@ -138,7 +138,7 @@ But you can instruct **FastAPI** to treat it as another body key using `Body`: {!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -197,7 +197,7 @@ For example: {!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="28" {!> ../../../docs_src/body_multiple_params/tutorial004_an.py!} @@ -212,7 +212,7 @@ For example: {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -250,7 +250,7 @@ as in: {!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="18" {!> ../../../docs_src/body_multiple_params/tutorial005_an.py!} @@ -265,7 +265,7 @@ as in: {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. diff --git a/docs/en/docs/tutorial/body-nested-models.md b/docs/en/docs/tutorial/body-nested-models.md index ffa0c0d0ef74f..4c199f0283b36 100644 --- a/docs/en/docs/tutorial/body-nested-models.md +++ b/docs/en/docs/tutorial/body-nested-models.md @@ -12,7 +12,7 @@ You can define an attribute to be a subtype. For example, a Python `list`: {!> ../../../docs_src/body_nested_models/tutorial001_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="14" {!> ../../../docs_src/body_nested_models/tutorial001.py!} @@ -73,7 +73,7 @@ So, in our example, we can make `tags` be specifically a "list of strings": {!> ../../../docs_src/body_nested_models/tutorial002_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="14" {!> ../../../docs_src/body_nested_models/tutorial002.py!} @@ -99,7 +99,7 @@ Then we can declare `tags` as a set of strings: {!> ../../../docs_src/body_nested_models/tutorial003_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="1 14" {!> ../../../docs_src/body_nested_models/tutorial003.py!} @@ -137,7 +137,7 @@ For example, we can define an `Image` model: {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9-11" {!> ../../../docs_src/body_nested_models/tutorial004.py!} @@ -159,7 +159,7 @@ And then we can use it as the type of an attribute: {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="20" {!> ../../../docs_src/body_nested_models/tutorial004.py!} @@ -183,18 +183,18 @@ This would mean that **FastAPI** would expect a body similar to: Again, doing just that declaration, with **FastAPI** you get: -* Editor support (completion, etc), even for nested models +* Editor support (completion, etc.), even for nested models * Data conversion * Data validation * Automatic documentation ## Special types and validation -Apart from normal singular types like `str`, `int`, `float`, etc. You can use more complex singular types that inherit from `str`. +Apart from normal singular types like `str`, `int`, `float`, etc. you can use more complex singular types that inherit from `str`. -To see all the options you have, checkout the docs for Pydantic's exotic types. You will see some examples in the next chapter. +To see all the options you have, checkout the docs for Pydantic's exotic types. You will see some examples in the next chapter. -For example, as in the `Image` model we have a `url` field, we can declare it to be instead of a `str`, a Pydantic's `HttpUrl`: +For example, as in the `Image` model we have a `url` field, we can declare it to be an instance of Pydantic's `HttpUrl` instead of a `str`: === "Python 3.10+" @@ -208,7 +208,7 @@ For example, as in the `Image` model we have a `url` field, we can declare it to {!> ../../../docs_src/body_nested_models/tutorial005_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="4 10" {!> ../../../docs_src/body_nested_models/tutorial005.py!} @@ -218,7 +218,7 @@ The string will be checked to be a valid URL, and documented in JSON Schema / Op ## Attributes with lists of submodels -You can also use Pydantic models as subtypes of `list`, `set`, etc: +You can also use Pydantic models as subtypes of `list`, `set`, etc.: === "Python 3.10+" @@ -232,13 +232,13 @@ You can also use Pydantic models as subtypes of `list`, `set`, etc: {!> ../../../docs_src/body_nested_models/tutorial006_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="20" {!> ../../../docs_src/body_nested_models/tutorial006.py!} ``` -This will expect (convert, validate, document, etc) a JSON body like: +This will expect (convert, validate, document, etc.) a JSON body like: ```JSON hl_lines="11" { @@ -283,7 +283,7 @@ You can define arbitrarily deeply nested models: {!> ../../../docs_src/body_nested_models/tutorial007_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9 14 20 23 27" {!> ../../../docs_src/body_nested_models/tutorial007.py!} @@ -314,7 +314,7 @@ as in: {!> ../../../docs_src/body_nested_models/tutorial008_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="15" {!> ../../../docs_src/body_nested_models/tutorial008.py!} @@ -334,15 +334,15 @@ But you don't have to worry about them either, incoming dicts are converted auto ## Bodies of arbitrary `dict`s -You can also declare a body as a `dict` with keys of some type and values of other type. +You can also declare a body as a `dict` with keys of some type and values of some other type. -Without having to know beforehand what are the valid field/attribute names (as would be the case with Pydantic models). +This way, you don't have to know beforehand what the valid field/attribute names are (as would be the case with Pydantic models). This would be useful if you want to receive keys that you don't already know. --- -Other useful case is when you want to have keys of other type, e.g. `int`. +Another useful case is when you want to have keys of another type (e.g., `int`). That's what we are going to see here. @@ -354,14 +354,14 @@ In this case, you would accept any `dict` as long as it has `int` keys with `flo {!> ../../../docs_src/body_nested_models/tutorial009_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9" {!> ../../../docs_src/body_nested_models/tutorial009.py!} ``` !!! tip - Have in mind that JSON only supports `str` as keys. + Keep in mind that JSON only supports `str` as keys. But Pydantic has automatic data conversion. diff --git a/docs/en/docs/tutorial/body-updates.md b/docs/en/docs/tutorial/body-updates.md index a32948db1a104..39d133c55f3dd 100644 --- a/docs/en/docs/tutorial/body-updates.md +++ b/docs/en/docs/tutorial/body-updates.md @@ -18,7 +18,7 @@ You can use the `jsonable_encoder` to convert the input data to data that can be {!> ../../../docs_src/body_updates/tutorial001_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="30-35" {!> ../../../docs_src/body_updates/tutorial001.py!} @@ -59,9 +59,14 @@ This means that you can send only the data that you want to update, leaving the ### Using Pydantic's `exclude_unset` parameter -If you want to receive partial updates, it's very useful to use the parameter `exclude_unset` in Pydantic's model's `.dict()`. +If you want to receive partial updates, it's very useful to use the parameter `exclude_unset` in Pydantic's model's `.model_dump()`. -Like `item.dict(exclude_unset=True)`. +Like `item.model_dump(exclude_unset=True)`. + +!!! info + In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`. + + The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2. That would generate a `dict` with only the data that was set when creating the `item` model, excluding default values. @@ -79,7 +84,7 @@ Then you can use this to generate a `dict` with only the data that was set (sent {!> ../../../docs_src/body_updates/tutorial002_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="34" {!> ../../../docs_src/body_updates/tutorial002.py!} @@ -87,9 +92,14 @@ Then you can use this to generate a `dict` with only the data that was set (sent ### Using Pydantic's `update` parameter -Now, you can create a copy of the existing model using `.copy()`, and pass the `update` parameter with a `dict` containing the data to update. +Now, you can create a copy of the existing model using `.model_copy()`, and pass the `update` parameter with a `dict` containing the data to update. + +!!! info + In Pydantic v1 the method was called `.copy()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_copy()`. + + The examples here use `.copy()` for compatibility with Pydantic v1, but you should use `.model_copy()` instead if you can use Pydantic v2. -Like `stored_item_model.copy(update=update_data)`: +Like `stored_item_model.model_copy(update=update_data)`: === "Python 3.10+" @@ -103,7 +113,7 @@ Like `stored_item_model.copy(update=update_data)`: {!> ../../../docs_src/body_updates/tutorial002_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="35" {!> ../../../docs_src/body_updates/tutorial002.py!} @@ -120,7 +130,7 @@ In summary, to apply partial updates you would: * This way you can update only the values actually set by the user, instead of overriding values already stored with default values in your model. * Create a copy of the stored model, updating it's attributes with the received partial updates (using the `update` parameter). * Convert the copied model to something that can be stored in your DB (for example, using the `jsonable_encoder`). - * This is comparable to using the model's `.dict()` method again, but it makes sure (and converts) the values to data types that can be converted to JSON, for example, `datetime` to `str`. + * This is comparable to using the model's `.model_dump()` method again, but it makes sure (and converts) the values to data types that can be converted to JSON, for example, `datetime` to `str`. * Save the data to your DB. * Return the updated model. @@ -136,7 +146,7 @@ In summary, to apply partial updates you would: {!> ../../../docs_src/body_updates/tutorial002_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="30-37" {!> ../../../docs_src/body_updates/tutorial002.py!} diff --git a/docs/en/docs/tutorial/body.md b/docs/en/docs/tutorial/body.md index 172b91fdfa61e..f9af42938c11f 100644 --- a/docs/en/docs/tutorial/body.md +++ b/docs/en/docs/tutorial/body.md @@ -6,7 +6,7 @@ A **request** body is data sent by the client to your API. A **response** body i Your API almost always has to send a **response** body. But clients don't necessarily need to send **request** bodies all the time. -To declare a **request** body, you use Pydantic models with all their power and benefits. +To declare a **request** body, you use Pydantic models with all their power and benefits. !!! info To send data, you should use one of: `POST` (the more common), `PUT`, `DELETE` or `PATCH`. @@ -25,7 +25,7 @@ First, you need to import `BaseModel` from `pydantic`: {!> ../../../docs_src/body/tutorial001_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="4" {!> ../../../docs_src/body/tutorial001.py!} @@ -43,7 +43,7 @@ Use standard Python types for all the attributes: {!> ../../../docs_src/body/tutorial001_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="7-11" {!> ../../../docs_src/body/tutorial001.py!} @@ -81,7 +81,7 @@ To add it to your *path operation*, declare it the same way you declared path an {!> ../../../docs_src/body/tutorial001_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="18" {!> ../../../docs_src/body/tutorial001.py!} @@ -155,7 +155,7 @@ Inside of the function, you can access all the attributes of the model object di {!> ../../../docs_src/body/tutorial002_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="21" {!> ../../../docs_src/body/tutorial002.py!} @@ -173,7 +173,7 @@ You can declare path parameters and request body at the same time. {!> ../../../docs_src/body/tutorial003_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="17-18" {!> ../../../docs_src/body/tutorial003.py!} @@ -191,7 +191,7 @@ You can also declare **body**, **path** and **query** parameters, all at the sam {!> ../../../docs_src/body/tutorial004_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="18" {!> ../../../docs_src/body/tutorial004.py!} diff --git a/docs/en/docs/tutorial/cookie-params.md b/docs/en/docs/tutorial/cookie-params.md index 111e93458e686..3436a7df397f8 100644 --- a/docs/en/docs/tutorial/cookie-params.md +++ b/docs/en/docs/tutorial/cookie-params.md @@ -18,7 +18,7 @@ First import `Cookie`: {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="3" {!> ../../../docs_src/cookie_params/tutorial001_an.py!} @@ -33,7 +33,7 @@ First import `Cookie`: {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -60,7 +60,7 @@ The first value is the default value, you can pass all the extra validation or a {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="10" {!> ../../../docs_src/cookie_params/tutorial001_an.py!} @@ -75,7 +75,7 @@ The first value is the default value, you can pass all the extra validation or a {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. diff --git a/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md index 498d935fe70dd..842f2adf6ba27 100644 --- a/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md @@ -18,7 +18,7 @@ In the previous example, we were returning a `dict` from our dependency ("depend {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="12" {!> ../../../docs_src/dependencies/tutorial001_an.py!} @@ -33,7 +33,7 @@ In the previous example, we were returning a `dict` from our dependency ("depend {!> ../../../docs_src/dependencies/tutorial001_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -115,7 +115,7 @@ Then, we can change the dependency "dependable" `common_parameters` from above t {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="12-16" {!> ../../../docs_src/dependencies/tutorial002_an.py!} @@ -130,7 +130,7 @@ Then, we can change the dependency "dependable" `common_parameters` from above t {!> ../../../docs_src/dependencies/tutorial002_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -153,7 +153,7 @@ Pay attention to the `__init__` method used to create the instance of the class: {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="13" {!> ../../../docs_src/dependencies/tutorial002_an.py!} @@ -168,7 +168,7 @@ Pay attention to the `__init__` method used to create the instance of the class: {!> ../../../docs_src/dependencies/tutorial002_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -191,7 +191,7 @@ Pay attention to the `__init__` method used to create the instance of the class: {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="10" {!> ../../../docs_src/dependencies/tutorial001_an.py!} @@ -206,7 +206,7 @@ Pay attention to the `__init__` method used to create the instance of the class: {!> ../../../docs_src/dependencies/tutorial001_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -241,7 +241,7 @@ Now you can declare your dependency using this class. {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="20" {!> ../../../docs_src/dependencies/tutorial002_an.py!} @@ -256,7 +256,7 @@ Now you can declare your dependency using this class. {!> ../../../docs_src/dependencies/tutorial002_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -271,7 +271,7 @@ Now you can declare your dependency using this class. Notice how we write `CommonQueryParams` twice in the above code: -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -280,7 +280,7 @@ Notice how we write `CommonQueryParams` twice in the above code: commons: CommonQueryParams = Depends(CommonQueryParams) ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] @@ -300,13 +300,13 @@ From it is that FastAPI will extract the declared parameters and that is what Fa In this case, the first `CommonQueryParams`, in: -=== "Python 3.6+" +=== "Python 3.8+" ```Python commons: Annotated[CommonQueryParams, ... ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -319,13 +319,13 @@ In this case, the first `CommonQueryParams`, in: You could actually write just: -=== "Python 3.6+" +=== "Python 3.8+" ```Python commons: Annotated[Any, Depends(CommonQueryParams)] ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -348,7 +348,7 @@ You could actually write just: {!> ../../../docs_src/dependencies/tutorial003_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="20" {!> ../../../docs_src/dependencies/tutorial003_an.py!} @@ -363,7 +363,7 @@ You could actually write just: {!> ../../../docs_src/dependencies/tutorial003_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -380,7 +380,7 @@ 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 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -389,7 +389,7 @@ But you see that we are having some code repetition here, writing `CommonQueryPa commons: CommonQueryParams = Depends(CommonQueryParams) ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] @@ -401,13 +401,13 @@ For those specific cases, you can do the following: Instead of writing: -=== "Python 3.6+" +=== "Python 3.8+" ```Python commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -418,13 +418,13 @@ Instead of writing: ...you write: -=== "Python 3.6+" +=== "Python 3.8+" ```Python commons: Annotated[CommonQueryParams, Depends()] ``` -=== "Python 3.6 non-Annotated" +=== "Python 3.8 non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -449,7 +449,7 @@ The same example would then look like: {!> ../../../docs_src/dependencies/tutorial004_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="20" {!> ../../../docs_src/dependencies/tutorial004_an.py!} @@ -464,7 +464,7 @@ The same example would then look like: {!> ../../../docs_src/dependencies/tutorial004_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. 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 935555339a25e..eaab51d1b1f38 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 @@ -20,13 +20,13 @@ It should be a `list` of `Depends()`: {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="18" {!> ../../../docs_src/dependencies/tutorial006_an.py!} ``` -=== "Python 3.6 non-Annotated" +=== "Python 3.8 non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -35,7 +35,7 @@ It should be a `list` of `Depends()`: {!> ../../../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*. +These dependencies will be executed/solved the same way as normal dependencies. But their value (if they return any) won't be passed to your *path operation function*. !!! tip Some editors check for unused function parameters, and show them as errors. @@ -63,13 +63,13 @@ They can declare request requirements (like headers) or other sub-dependencies: {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="7 12" {!> ../../../docs_src/dependencies/tutorial006_an.py!} ``` -=== "Python 3.6 non-Annotated" +=== "Python 3.8 non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -88,13 +88,13 @@ These dependencies can `raise` exceptions, the same as normal dependencies: {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9 14" {!> ../../../docs_src/dependencies/tutorial006_an.py!} ``` -=== "Python 3.6 non-Annotated" +=== "Python 3.8 non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -115,13 +115,13 @@ So, you can re-use a normal dependency (that returns a value) you already use so {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="10 15" {!> ../../../docs_src/dependencies/tutorial006_an.py!} ``` -=== "Python 3.6 non-Annotated" +=== "Python 3.8 non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. diff --git a/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md index 8a5422ac862e4..ad5aed9323edd 100644 --- a/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md @@ -1,8 +1,8 @@ # Dependencies with yield -FastAPI supports dependencies that do some extra steps after finishing. +FastAPI supports dependencies that do some extra steps after finishing. -To do this, use `yield` instead of `return`, and write the extra steps after. +To do this, use `yield` instead of `return`, and write the extra steps (code) after. !!! tip Make sure to use `yield` one single time. @@ -21,7 +21,7 @@ To do this, use `yield` instead of `return`, and write the extra steps after. For example, you could use this to create a database session and close it after finishing. -Only the code prior to and including the `yield` statement is executed before sending a response: +Only the code prior to and including the `yield` statement is executed before creating a response: ```Python hl_lines="2-4" {!../../../docs_src/dependencies/tutorial007.py!} @@ -40,7 +40,7 @@ The code following the `yield` statement is executed after the response has been ``` !!! tip - You can use `async` or normal functions. + You can use `async` or regular functions. **FastAPI** will do the right thing with each, the same as with normal dependencies. @@ -72,13 +72,13 @@ For example, `dependency_c` can have a dependency on `dependency_b`, and `depend {!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="5 13 21" {!> ../../../docs_src/dependencies/tutorial008_an.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -99,13 +99,13 @@ And, in turn, `dependency_b` needs the value from `dependency_a` (here named `de {!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="17-18 25-26" {!> ../../../docs_src/dependencies/tutorial008_an.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -114,7 +114,7 @@ And, in turn, `dependency_b` needs the value from `dependency_a` (here named `de {!> ../../../docs_src/dependencies/tutorial008.py!} ``` -The same way, you could have dependencies with `yield` and `return` mixed. +The same way, you could have some dependencies with `yield` and some other dependencies with `return`, and have some of those depend on some of the others. And you could have a single dependency that requires several other dependencies with `yield`, etc. @@ -131,24 +131,95 @@ You can have any combinations of dependencies that you want. You saw that you can use dependencies with `yield` and have `try` blocks that catch exceptions. -It might be tempting to raise an `HTTPException` or similar in the exit code, after the `yield`. But **it won't work**. +The same way, you could raise an `HTTPException` or similar in the exit code, after the `yield`. -The exit code in dependencies with `yield` is executed *after* the response is sent, so [Exception Handlers](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank} will have already run. There's nothing catching exceptions thrown by your dependencies in the exit code (after the `yield`). +!!! tip -So, if you raise an `HTTPException` after the `yield`, the default (or any custom) exception handler that catches `HTTPException`s and returns an HTTP 400 response won't be there to catch that exception anymore. + This is a somewhat advanced technique, and in most of the cases you won't really need it, as you can raise exceptions (including `HTTPException`) from inside of the rest of your application code, for example, in the *path operation function*. -This is what allows anything set in the dependency (e.g. a DB session) to, for example, be used by background tasks. + But it's there for you if you need it. 🤓 -Background tasks are run *after* the response has been sent. So there's no way to raise an `HTTPException` because there's not even a way to change the response that is *already sent*. +=== "Python 3.9+" -But if a background task creates a DB error, at least you can rollback or cleanly close the session in the dependency with `yield`, and maybe log the error or report it to a remote tracking system. + ```Python hl_lines="18-22 31" + {!> ../../../docs_src/dependencies/tutorial008b_an_py39.py!} + ``` -If you have some code that you know could raise an exception, do the most normal/"Pythonic" thing and add a `try` block in that section of the code. +=== "Python 3.8+" -If you have custom exceptions that you would like to handle *before* returning the response and possibly modifying the response, maybe even raising an `HTTPException`, create a [Custom Exception Handler](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}. + ```Python hl_lines="17-21 30" + {!> ../../../docs_src/dependencies/tutorial008b_an.py!} + ``` -!!! tip - You can still raise exceptions including `HTTPException` *before* the `yield`. But not after. +=== "Python 3.8+ non-Annotated" + + !!! tip + Prefer to use the `Annotated` version if possible. + + ```Python hl_lines="16-20 29" + {!> ../../../docs_src/dependencies/tutorial008b.py!} + ``` + +An alternative you could use to catch exceptions (and possibly also raise another `HTTPException`) is to create a [Custom Exception Handler](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}. + +## Dependencies with `yield` and `except` + +If you catch an exception using `except` in a dependency with `yield` and you don't raise it again (or raise a new exception), FastAPI won't be able to notice there was an exception, the same way that would happen with regular Python: + +=== "Python 3.9+" + + ```Python hl_lines="15-16" + {!> ../../../docs_src/dependencies/tutorial008c_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="14-15" + {!> ../../../docs_src/dependencies/tutorial008c_an.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + Prefer to use the `Annotated` version if possible. + + ```Python hl_lines="13-14" + {!> ../../../docs_src/dependencies/tutorial008c.py!} + ``` + +In this case, the client will see an *HTTP 500 Internal Server Error* response as it should, given that we are not raising an `HTTPException` or similar, but the server will **not have any logs** or any other indication of what was the error. 😱 + +### Always `raise` in Dependencies with `yield` and `except` + +If you catch an exception in a dependency with `yield`, unless you are raising another `HTTPException` or similar, you should re-raise the original exception. + +You can re-raise the same exception using `raise`: + +=== "Python 3.9+" + + ```Python hl_lines="17" + {!> ../../../docs_src/dependencies/tutorial008d_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="16" + {!> ../../../docs_src/dependencies/tutorial008d_an.py!} + ``` + + +=== "Python 3.8+ non-Annotated" + + !!! tip + Prefer to use the `Annotated` version if possible. + + ```Python hl_lines="15" + {!> ../../../docs_src/dependencies/tutorial008d.py!} + ``` + +Now the client will get the same *HTTP 500 Internal Server Error* response, but the server will have our custom `InternalError` in the logs. 😎 + +## Execution of dependencies with `yield` The sequence of execution is more or less like this diagram. Time flows from top to bottom. And each column is one of the parts interacting or executing code. @@ -161,34 +232,29 @@ participant dep as Dep with yield participant operation as Path Operation participant tasks as Background tasks - Note over client,tasks: Can raise exception for dependency, handled after response is sent - Note over client,operation: Can raise HTTPException and can change the response + Note over client,operation: Can raise exceptions, including HTTPException client ->> dep: Start request Note over dep: Run code up to yield - opt raise - dep -->> handler: Raise HTTPException + opt raise Exception + dep -->> handler: Raise Exception handler -->> client: HTTP error response - dep -->> dep: Raise other exception end dep ->> operation: Run dependency, e.g. DB session opt raise - operation -->> dep: Raise HTTPException - dep -->> handler: Auto forward exception + operation -->> dep: Raise Exception (e.g. HTTPException) + opt handle + dep -->> dep: Can catch exception, raise a new HTTPException, raise other exception + end handler -->> client: HTTP error response - operation -->> dep: Raise other exception - dep -->> handler: Auto forward exception end + operation ->> client: Return response to client Note over client,operation: Response is already sent, can't change it anymore opt Tasks operation -->> tasks: Send background tasks end opt Raise other exception - tasks -->> dep: Raise other exception - end - Note over dep: After yield - opt Handle other exception - dep -->> dep: Handle exception, can't change response. E.g. close DB session. + tasks -->> tasks: Handle exceptions in the background task code end ``` @@ -198,9 +264,40 @@ participant tasks as Background tasks After one of those responses is sent, no other response can be sent. !!! tip - This diagram shows `HTTPException`, but you could also raise any other exception for which you create a [Custom Exception Handler](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}. + This diagram shows `HTTPException`, but you could also raise any other exception that you catch in a dependency with `yield` or with a [Custom Exception Handler](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}. + + If you raise any exception, it will be passed to the dependencies with yield, including `HTTPException`. In most cases you will want to re-raise that same exception or a new one from the dependency with `yield` to make sure it's properly handled. + +## Dependencies with `yield`, `HTTPException`, `except` and Background Tasks + +!!! warning + You most probably don't need these technical details, you can skip this section and continue below. + + These details are useful mainly if you were using a version of FastAPI prior to 0.106.0 and used resources from dependencies with `yield` in background tasks. + +### Dependencies with `yield` and `except`, Technical Details + +Before FastAPI 0.110.0, if you used a dependency with `yield`, and then you captured an exception with `except` in that dependency, and you didn't raise the exception again, the exception would be automatically raised/forwarded to any exception handlers or the internal server error handler. + +This was changed in version 0.110.0 to fix unhandled memory consumption from forwarded exceptions without a handler (internal server errors), and to make it consistent with the behavior of regular Python code. + +### Background Tasks and Dependencies with `yield`, Technical Details + +Before FastAPI 0.106.0, raising exceptions after `yield` was not possible, the exit code in dependencies with `yield` was executed *after* the response was sent, so [Exception Handlers](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank} would have already run. + +This was designed this way mainly to allow using the same objects "yielded" by dependencies inside of background tasks, because the exit code would be executed after the background tasks were finished. + +Nevertheless, as this would mean waiting for the response to travel through the network while unnecessarily holding a resource in a dependency with yield (for example a database connection), this was changed in FastAPI 0.106.0. + +!!! tip + + Additionally, a background task is normally an independent set of logic that should be handled separately, with its own resources (e.g. its own database connection). + + So, this way you will probably have cleaner code. + +If you used to rely on this behavior, now you should create the resources for background tasks inside the background task itself, and use internally only data that doesn't depend on the resources of dependencies with `yield`. - If you raise any exception, it will be passed to the dependencies with yield, including `HTTPException`, and then **again** to the exception handlers. If there's no exception handler for that exception, it will then be handled by the default internal `ServerErrorMiddleware`, returning a 500 HTTP status code, to let the client know that there was an error in the server. +For example, instead of using the same database session, you would create a new database session inside of the background task, and you would obtain the objects from the database using this new session. And then instead of passing the object from the database as a parameter to the background task function, you would pass the ID of that object and then obtain the object again inside the background task function. ## Context Managers @@ -216,11 +313,11 @@ with open("./somefile.txt") as f: print(contents) ``` -Underneath, the `open("./somefile.txt")` creates an object that is a called a "Context Manager". +Underneath, the `open("./somefile.txt")` creates an object that is called a "Context Manager". When the `with` block finishes, it makes sure to close the file, even if there were exceptions. -When you create a dependency with `yield`, **FastAPI** will internally convert it to a context manager, and combine it with some other related tools. +When you create a dependency with `yield`, **FastAPI** will internally create a context manager for it, and combine it with some other related tools. ### Using context managers in dependencies with `yield` diff --git a/docs/en/docs/tutorial/dependencies/global-dependencies.md b/docs/en/docs/tutorial/dependencies/global-dependencies.md index 0989b31d46205..0dcf73176ffb6 100644 --- a/docs/en/docs/tutorial/dependencies/global-dependencies.md +++ b/docs/en/docs/tutorial/dependencies/global-dependencies.md @@ -12,13 +12,13 @@ In that case, they will be applied to all the *path operations* in the applicati {!> ../../../docs_src/dependencies/tutorial012_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="16" {!> ../../../docs_src/dependencies/tutorial012_an.py!} ``` -=== "Python 3.6 non-Annotated" +=== "Python 3.8 non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. diff --git a/docs/en/docs/tutorial/dependencies/index.md b/docs/en/docs/tutorial/dependencies/index.md index f6f4bced08a76..608ced407ea49 100644 --- a/docs/en/docs/tutorial/dependencies/index.md +++ b/docs/en/docs/tutorial/dependencies/index.md @@ -43,7 +43,7 @@ It is just a function that can take all the same parameters that a *path operati {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9-12" {!> ../../../docs_src/dependencies/tutorial001_an.py!} @@ -58,7 +58,7 @@ It is just a function that can take all the same parameters that a *path operati {!> ../../../docs_src/dependencies/tutorial001_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -106,7 +106,7 @@ And then it just returns a `dict` containing those values. {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="3" {!> ../../../docs_src/dependencies/tutorial001_an.py!} @@ -121,7 +121,7 @@ And then it just returns a `dict` containing those values. {!> ../../../docs_src/dependencies/tutorial001_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -146,7 +146,7 @@ The same way you use `Body`, `Query`, etc. with your *path operation function* p {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="16 21" {!> ../../../docs_src/dependencies/tutorial001_an.py!} @@ -161,7 +161,7 @@ The same way you use `Body`, `Query`, etc. with your *path operation function* p {!> ../../../docs_src/dependencies/tutorial001_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -231,7 +231,7 @@ But because we are using `Annotated`, we can store that `Annotated` value in a v {!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="15 19 24" {!> ../../../docs_src/dependencies/tutorial001_02_an.py!} @@ -287,9 +287,9 @@ Other common terms for this same idea of "dependency injection" are: ## **FastAPI** plug-ins -Integrations and "plug-in"s can be built using the **Dependency Injection** system. But in fact, there is actually **no need to create "plug-ins"**, as by using dependencies it's possible to declare an infinite number of integrations and interactions that become available to your *path operation functions*. +Integrations and "plug-ins" can be built using the **Dependency Injection** system. But in fact, there is actually **no need to create "plug-ins"**, as by using dependencies it's possible to declare an infinite number of integrations and interactions that become available to your *path operation functions*. -And dependencies can be created in a very simple and intuitive way that allow you to just import the Python packages you need, and integrate them with your API functions in a couple of lines of code, *literally*. +And dependencies can be created in a very simple and intuitive way that allows you to just import the Python packages you need, and integrate them with your API functions in a couple of lines of code, *literally*. You will see examples of this in the next chapters, about relational and NoSQL databases, security, etc. diff --git a/docs/en/docs/tutorial/dependencies/sub-dependencies.md b/docs/en/docs/tutorial/dependencies/sub-dependencies.md index b50de1a46cce3..1cb469a805120 100644 --- a/docs/en/docs/tutorial/dependencies/sub-dependencies.md +++ b/docs/en/docs/tutorial/dependencies/sub-dependencies.md @@ -22,7 +22,7 @@ You could create a first dependency ("dependable") like: {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9-10" {!> ../../../docs_src/dependencies/tutorial005_an.py!} @@ -37,7 +37,7 @@ You could create a first dependency ("dependable") like: {!> ../../../docs_src/dependencies/tutorial005_py310.py!} ``` -=== "Python 3.6 non-Annotated" +=== "Python 3.8 non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -66,7 +66,7 @@ Then you can create another dependency function (a "dependable") that at the sam {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="14" {!> ../../../docs_src/dependencies/tutorial005_an.py!} @@ -81,7 +81,7 @@ Then you can create another dependency function (a "dependable") that at the sam {!> ../../../docs_src/dependencies/tutorial005_py310.py!} ``` -=== "Python 3.6 non-Annotated" +=== "Python 3.8 non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -113,7 +113,7 @@ Then we can use the dependency with: {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="24" {!> ../../../docs_src/dependencies/tutorial005_an.py!} @@ -128,7 +128,7 @@ Then we can use the dependency with: {!> ../../../docs_src/dependencies/tutorial005_py310.py!} ``` -=== "Python 3.6 non-Annotated" +=== "Python 3.8 non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -161,14 +161,14 @@ And it will save the returned value in a ../../../docs_src/encoder/tutorial001_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="5 22" {!> ../../../docs_src/encoder/tutorial001.py!} diff --git a/docs/en/docs/tutorial/extra-data-types.md b/docs/en/docs/tutorial/extra-data-types.md index 7d6ffbc780cb0..e705a18e43b2f 100644 --- a/docs/en/docs/tutorial/extra-data-types.md +++ b/docs/en/docs/tutorial/extra-data-types.md @@ -36,7 +36,7 @@ Here are some of the additional data types you can use: * `datetime.timedelta`: * A Python `datetime.timedelta`. * In requests and responses will be represented as a `float` of total seconds. - * Pydantic also allows representing it as a "ISO 8601 time diff encoding", see the docs for more info. + * Pydantic also allows representing it as a "ISO 8601 time diff encoding", see the docs for more info. * `frozenset`: * In requests and responses, treated the same as a `set`: * In requests, a list will be read, eliminating duplicates and converting it to a `set`. @@ -49,7 +49,7 @@ Here are some of the additional data types you can use: * `Decimal`: * Standard Python `Decimal`. * In requests and responses, handled the same as a `float`. -* You can check all the valid pydantic data types here: Pydantic data types. +* You can check all the valid pydantic data types here: Pydantic data types. ## Example @@ -67,7 +67,7 @@ Here's an example *path operation* with parameters using some of the above types {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="1 3 13-17" {!> ../../../docs_src/extra_data_types/tutorial001_an.py!} @@ -82,7 +82,7 @@ Here's an example *path operation* with parameters using some of the above types {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -105,7 +105,7 @@ Note that the parameters inside the function have their natural data type, and y {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="19-20" {!> ../../../docs_src/extra_data_types/tutorial001_an.py!} @@ -120,7 +120,7 @@ Note that the parameters inside the function have their natural data type, and y {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. diff --git a/docs/en/docs/tutorial/extra-models.md b/docs/en/docs/tutorial/extra-models.md index e91e879e41672..49b00c73057c0 100644 --- a/docs/en/docs/tutorial/extra-models.md +++ b/docs/en/docs/tutorial/extra-models.md @@ -23,12 +23,17 @@ Here's a general idea of how the models could look like with their password fiel {!> ../../../docs_src/extra_models/tutorial001_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" {!> ../../../docs_src/extra_models/tutorial001.py!} ``` +!!! info + In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`. + + The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2. + ### About `**user_in.dict()` #### Pydantic's `.dict()` @@ -115,7 +120,7 @@ would be equivalent to: UserInDB(**user_in.dict()) ``` -...because `user_in.dict()` is a `dict`, and then we make Python "unwrap" it by passing it to `UserInDB` prepended with `**`. +...because `user_in.dict()` is a `dict`, and then we make Python "unwrap" it by passing it to `UserInDB` prefixed with `**`. So, we get a Pydantic model from the data in another Pydantic model. @@ -164,7 +169,7 @@ That way, we can declare just the differences between the models (with plaintext {!> ../../../docs_src/extra_models/tutorial002_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9 15-16 19-20 23-24" {!> ../../../docs_src/extra_models/tutorial002.py!} @@ -179,7 +184,7 @@ It will be defined in OpenAPI with `anyOf`. To do that, use the standard Python type hint `typing.Union`: !!! note - When defining a `Union`, include the most specific type first, followed by the less specific type. In the example below, the more specific `PlaneItem` comes before `CarItem` in `Union[PlaneItem, CarItem]`. + When defining a `Union`, include the most specific type first, followed by the less specific type. In the example below, the more specific `PlaneItem` comes before `CarItem` in `Union[PlaneItem, CarItem]`. === "Python 3.10+" @@ -187,7 +192,7 @@ To do that, use the standard Python type hint ../../../docs_src/extra_models/tutorial003.py!} @@ -219,7 +224,7 @@ For that, use the standard Python `typing.List` (or just `list` in Python 3.9 an {!> ../../../docs_src/extra_models/tutorial004_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="1 20" {!> ../../../docs_src/extra_models/tutorial004.py!} @@ -239,7 +244,7 @@ In this case, you can use `typing.Dict` (or just `dict` in Python 3.9 and above) {!> ../../../docs_src/extra_models/tutorial005_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="1 8" {!> ../../../docs_src/extra_models/tutorial005.py!} diff --git a/docs/en/docs/tutorial/first-steps.md b/docs/en/docs/tutorial/first-steps.md index 6ca5f39eb1640..cfa159329405c 100644 --- a/docs/en/docs/tutorial/first-steps.md +++ b/docs/en/docs/tutorial/first-steps.md @@ -99,7 +99,7 @@ It will show a JSON starting with something like: ```JSON { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": { "title": "FastAPI", "version": "0.1.0" diff --git a/docs/en/docs/tutorial/handling-errors.md b/docs/en/docs/tutorial/handling-errors.md index 8c30326cede92..98ac55d1f7722 100644 --- a/docs/en/docs/tutorial/handling-errors.md +++ b/docs/en/docs/tutorial/handling-errors.md @@ -1,6 +1,6 @@ # Handling Errors -There are many situations in where you need to notify an error to a client that is using your API. +There are many situations in which you need to notify an error to a client that is using your API. This client could be a browser with a frontend, a code from someone else, an IoT device, etc. @@ -163,7 +163,7 @@ path -> item_id !!! warning These are technical details that you might skip if it's not important for you now. -`RequestValidationError` is a sub-class of Pydantic's `ValidationError`. +`RequestValidationError` is a sub-class of Pydantic's `ValidationError`. **FastAPI** uses it so that, if you use a Pydantic model in `response_model`, and your data has an error, you will see the error in your log. @@ -234,9 +234,7 @@ You will receive a response telling you that the data is invalid containing the And **FastAPI**'s `HTTPException` error class inherits from Starlette's `HTTPException` error class. -The only difference, is that **FastAPI**'s `HTTPException` allows you to add headers to be included in the response. - -This is needed/used internally for OAuth 2.0 and some security utilities. +The only difference is that **FastAPI**'s `HTTPException` accepts any JSON-able data for the `detail` field, while Starlette's `HTTPException` only accepts strings for it. So, you can keep raising **FastAPI**'s `HTTPException` as normally in your code. diff --git a/docs/en/docs/tutorial/header-params.md b/docs/en/docs/tutorial/header-params.md index 9e928cdc6b482..bbba90998776e 100644 --- a/docs/en/docs/tutorial/header-params.md +++ b/docs/en/docs/tutorial/header-params.md @@ -18,7 +18,7 @@ First import `Header`: {!> ../../../docs_src/header_params/tutorial001_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="3" {!> ../../../docs_src/header_params/tutorial001_an.py!} @@ -33,7 +33,7 @@ First import `Header`: {!> ../../../docs_src/header_params/tutorial001_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -60,7 +60,7 @@ The first value is the default value, you can pass all the extra validation or a {!> ../../../docs_src/header_params/tutorial001_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="10" {!> ../../../docs_src/header_params/tutorial001_an.py!} @@ -75,7 +75,7 @@ The first value is the default value, you can pass all the extra validation or a {!> ../../../docs_src/header_params/tutorial001_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -120,7 +120,7 @@ If for some reason you need to disable automatic conversion of underscores to hy {!> ../../../docs_src/header_params/tutorial002_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="12" {!> ../../../docs_src/header_params/tutorial002_an.py!} @@ -135,7 +135,7 @@ If for some reason you need to disable automatic conversion of underscores to hy {!> ../../../docs_src/header_params/tutorial002_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -169,7 +169,7 @@ For example, to declare a header of `X-Token` that can appear more than once, yo {!> ../../../docs_src/header_params/tutorial003_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="10" {!> ../../../docs_src/header_params/tutorial003_an.py!} @@ -193,7 +193,7 @@ For example, to declare a header of `X-Token` that can appear more than once, yo {!> ../../../docs_src/header_params/tutorial003_py39.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. diff --git a/docs/en/docs/tutorial/metadata.md b/docs/en/docs/tutorial/metadata.md index cf13e7470fc88..504204e9874e7 100644 --- a/docs/en/docs/tutorial/metadata.md +++ b/docs/en/docs/tutorial/metadata.md @@ -9,15 +9,16 @@ You can set the following fields that are used in the OpenAPI specification and | Parameter | Type | Description | |------------|------|-------------| | `title` | `str` | The title of the API. | +| `summary` | `str` | A short summary of the API. Available since OpenAPI 3.1.0, FastAPI 0.99.0. | | `description` | `str` | A short description of the API. It can use Markdown. | | `version` | `string` | The version of the API. This is the version of your own application, not of OpenAPI. For example `2.5.0`. | | `terms_of_service` | `str` | A URL to the Terms of Service for the API. If provided, this has to be a URL. | | `contact` | `dict` | The contact information for the exposed API. It can contain several fields.
contact fields
ParameterTypeDescription
namestrThe identifying name of the contact person/organization.
urlstrThe URL pointing to the contact information. MUST be in the format of a URL.
emailstrThe email address of the contact person/organization. MUST be in the format of an email address.
| -| `license_info` | `dict` | The license information for the exposed API. It can contain several fields.
license_info fields
ParameterTypeDescription
namestrREQUIRED (if a license_info is set). The license name used for the API.
urlstrA URL to the license used for the API. MUST be in the format of a URL.
| +| `license_info` | `dict` | The license information for the exposed API. It can contain several fields.
license_info fields
ParameterTypeDescription
namestrREQUIRED (if a license_info is set). The license name used for the API.
identifierstrAn SPDX license expression for the API. The identifier field is mutually exclusive of the url field. Available since OpenAPI 3.1.0, FastAPI 0.99.0.
urlstrA URL to the license used for the API. MUST be in the format of a URL.
| You can set them as follows: -```Python hl_lines="3-16 19-31" +```Python hl_lines="3-16 19-32" {!../../../docs_src/metadata/tutorial001.py!} ``` @@ -28,6 +29,16 @@ With this configuration, the automatic API docs would look like: +## License identifier + +Since OpenAPI 3.1.0 and FastAPI 0.99.0, you can also set the `license_info` with an `identifier` instead of a `url`. + +For example: + +```Python hl_lines="31" +{!../../../docs_src/metadata/tutorial001_1.py!} +``` + ## Metadata for tags You can also add additional metadata for the different tags used to group your path operations with the parameter `openapi_tags`. diff --git a/docs/en/docs/tutorial/middleware.md b/docs/en/docs/tutorial/middleware.md index 3c6868fe4de73..492a1b065e515 100644 --- a/docs/en/docs/tutorial/middleware.md +++ b/docs/en/docs/tutorial/middleware.md @@ -33,7 +33,7 @@ The middleware function receives: ``` !!! tip - Have in mind that custom proprietary headers can be added using the 'X-' prefix. + Keep in mind that custom proprietary headers can be added using the 'X-' prefix. But if you have custom headers that you want a client in a browser to be able to see, you need to add them to your CORS configurations ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) using the parameter `expose_headers` documented in Starlette's CORS docs. diff --git a/docs/en/docs/tutorial/path-operation-configuration.md b/docs/en/docs/tutorial/path-operation-configuration.md index 7d4d4bccaf64c..babf85acb22e8 100644 --- a/docs/en/docs/tutorial/path-operation-configuration.md +++ b/docs/en/docs/tutorial/path-operation-configuration.md @@ -25,7 +25,7 @@ But if you don't remember what each number code is for, you can use the shortcut {!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="3 17" {!> ../../../docs_src/path_operation_configuration/tutorial001.py!} @@ -54,7 +54,7 @@ You can add tags to your *path operation*, pass the parameter `tags` with a `lis {!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="17 22 27" {!> ../../../docs_src/path_operation_configuration/tutorial002.py!} @@ -92,7 +92,7 @@ You can add a `summary` and `description`: {!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="20-21" {!> ../../../docs_src/path_operation_configuration/tutorial003.py!} @@ -116,7 +116,7 @@ You can write ../../../docs_src/path_operation_configuration/tutorial004.py!} @@ -142,7 +142,7 @@ You can specify the response description with the parameter `response_descriptio {!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="21" {!> ../../../docs_src/path_operation_configuration/tutorial005.py!} diff --git a/docs/en/docs/tutorial/path-params-numeric-validations.md b/docs/en/docs/tutorial/path-params-numeric-validations.md index 9255875d605b8..b5b13cfbe6f81 100644 --- a/docs/en/docs/tutorial/path-params-numeric-validations.md +++ b/docs/en/docs/tutorial/path-params-numeric-validations.md @@ -18,7 +18,7 @@ First, import `Path` from `fastapi`, and import `Annotated`: {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="3-4" {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} @@ -33,7 +33,7 @@ First, import `Path` from `fastapi`, and import `Annotated`: {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -67,7 +67,7 @@ For example, to declare a `title` metadata value for the path parameter `item_id {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="11" {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} @@ -82,7 +82,7 @@ For example, to declare a `title` metadata value for the path parameter `item_id {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -117,7 +117,7 @@ It doesn't matter for **FastAPI**. It will detect the parameters by their names, So, you can declare your function as: -=== "Python 3.6 non-Annotated" +=== "Python 3.8 non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -126,7 +126,7 @@ So, you can declare your function as: {!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!} ``` -But have in mind that if you use `Annotated`, you won't have this problem, it won't matter as you're not using the function parameter default values for `Query()` or `Path()`. +But keep in mind that if you use `Annotated`, you won't have this problem, it won't matter as you're not using the function parameter default values for `Query()` or `Path()`. === "Python 3.9+" @@ -134,7 +134,7 @@ But have in mind that if you use `Annotated`, you won't have this problem, it wo {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9" {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!} @@ -166,7 +166,7 @@ Python won't do anything with that `*`, but it will know that all the following ### Better with `Annotated` -Have in mind that if you use `Annotated`, as you are not using function parameter default values, you won't have this problem, and you probably won't need to use `*`. +Keep in mind that if you use `Annotated`, as you are not using function parameter default values, you won't have this problem, and you probably won't need to use `*`. === "Python 3.9+" @@ -174,7 +174,7 @@ Have in mind that if you use `Annotated`, as you are not using function paramete {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9" {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!} @@ -192,13 +192,13 @@ Here, with `ge=1`, `item_id` will need to be an integer number "`g`reater than o {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9" {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -220,13 +220,13 @@ The same applies for: {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9" {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -251,13 +251,13 @@ And the same for lt. {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="12" {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. diff --git a/docs/en/docs/tutorial/path-params.md b/docs/en/docs/tutorial/path-params.md index a0d70692e556b..6246d6680bfc5 100644 --- a/docs/en/docs/tutorial/path-params.md +++ b/docs/en/docs/tutorial/path-params.md @@ -46,16 +46,18 @@ But if you go to the browser at OpenAPI standard, there are many compatible tools. +And because the generated schema is from the OpenAPI standard, there are many compatible tools. Because of this, **FastAPI** itself provides an alternative API documentation (using ReDoc), which you can access at http://127.0.0.1:8000/redoc: @@ -93,7 +95,7 @@ The same way, there are many compatible tools. Including code generation tools f ## Pydantic -All the data validation is performed under the hood by Pydantic, so you get all the benefits from it. And you know you are in good hands. +All the data validation is performed under the hood by Pydantic, so you get all the benefits from it. And you know you are in good hands. You can use the same type declarations with `str`, `float`, `bool` and many other complex data types. diff --git a/docs/en/docs/tutorial/query-params-str-validations.md b/docs/en/docs/tutorial/query-params-str-validations.md index 549e6c75b58a1..24784efadd0fb 100644 --- a/docs/en/docs/tutorial/query-params-str-validations.md +++ b/docs/en/docs/tutorial/query-params-str-validations.md @@ -10,7 +10,7 @@ Let's take this application as example: {!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9" {!> ../../../docs_src/query_params_str_validations/tutorial001.py!} @@ -42,7 +42,7 @@ To achieve that, first import: {!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" In versions of Python below Python 3.9 you import `Annotated` from `typing_extensions`. @@ -73,7 +73,7 @@ We had this type annotation: q: str | None = None ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python q: Union[str, None] = None @@ -87,7 +87,7 @@ What we will do is wrap that with `Annotated`, so it becomes: q: Annotated[str | None] = None ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python q: Annotated[Union[str, None]] = None @@ -107,7 +107,7 @@ Now that we have this `Annotated` where we can put more metadata, add `Query` to {!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="10" {!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!} @@ -138,7 +138,7 @@ This is how you would use `Query()` as the default value of your function parame {!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9" {!> ../../../docs_src/query_params_str_validations/tutorial002.py!} @@ -173,7 +173,7 @@ q: str | None = None But it declares it explicitly as being a query parameter. !!! info - Have in mind that the most important part to make a parameter optional is the part: + Keep in mind that the most important part to make a parameter optional is the part: ```Python = None @@ -199,7 +199,7 @@ This will validate the data, show a clear error when the data is not valid, and ### `Query` as the default value or in `Annotated` -Have in mind that when using `Query` inside of `Annotated` you cannot use the `default` parameter for `Query`. +Keep in mind that when using `Query` inside of `Annotated` you cannot use the `default` parameter for `Query`. Instead use the actual default value of the function parameter. Otherwise, it would be inconsistent. @@ -251,7 +251,7 @@ You can also add a parameter `min_length`: {!> ../../../docs_src/query_params_str_validations/tutorial003_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="11" {!> ../../../docs_src/query_params_str_validations/tutorial003_an.py!} @@ -266,7 +266,7 @@ You can also add a parameter `min_length`: {!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -277,7 +277,7 @@ You can also add a parameter `min_length`: ## Add regular expressions -You can define a regular expression that the parameter should match: +You can define a regular expression `pattern` that the parameter should match: === "Python 3.10+" @@ -291,7 +291,7 @@ You can define a ../../../docs_src/query_params_str_validations/tutorial004_an.py!} @@ -306,7 +306,7 @@ You can define a ../../../docs_src/query_params_str_validations/tutorial004_an_py310_regex.py!} + ``` + +But know that this is deprecated and it should be updated to use the new parameter `pattern`. 🤓 + ## Default values You can, of course, use default values other than `None`. @@ -337,13 +351,13 @@ Let's say that you want to declare the `q` query parameter to have a `min_length {!> ../../../docs_src/query_params_str_validations/tutorial005_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="8" {!> ../../../docs_src/query_params_str_validations/tutorial005_an.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -391,13 +405,13 @@ So, when you need to declare a value as required while using `Query`, you can si {!> ../../../docs_src/query_params_str_validations/tutorial006_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="8" {!> ../../../docs_src/query_params_str_validations/tutorial006_an.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -421,13 +435,13 @@ There's an alternative way to explicitly declare that a value is required. You c {!> ../../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="8" {!> ../../../docs_src/query_params_str_validations/tutorial006b_an.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -461,7 +475,7 @@ To do that, you can declare that `None` is a valid type but still use `...` as t {!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="10" {!> ../../../docs_src/query_params_str_validations/tutorial006c_an.py!} @@ -476,7 +490,7 @@ To do that, you can declare that `None` is a valid type but still use `...` as t {!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -486,35 +500,10 @@ To do that, you can declare that `None` is a valid type but still use `...` as t ``` !!! tip - Pydantic, which is what powers all the data validation and serialization in FastAPI, has a special behavior when you use `Optional` or `Union[Something, None]` without a default value, you can read more about it in the Pydantic docs about Required Optional fields. - -### Use Pydantic's `Required` instead of Ellipsis (`...`) - -If you feel uncomfortable using `...`, you can also import and use `Required` from Pydantic: - -=== "Python 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!} - ``` + 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. !!! tip - 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`. + 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 `...`. ## Query parameter list / multiple values @@ -534,7 +523,7 @@ For example, to declare a query parameter `q` that can appear multiple times in {!> ../../../docs_src/query_params_str_validations/tutorial011_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="10" {!> ../../../docs_src/query_params_str_validations/tutorial011_an.py!} @@ -558,7 +547,7 @@ For example, to declare a query parameter `q` that can appear multiple times in {!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -603,7 +592,7 @@ And you can also define a default `list` of values if none are provided: {!> ../../../docs_src/query_params_str_validations/tutorial012_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="10" {!> ../../../docs_src/query_params_str_validations/tutorial012_an.py!} @@ -618,7 +607,7 @@ And you can also define a default `list` of values if none are provided: {!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -654,13 +643,13 @@ You can also use `list` directly instead of `List[str]` (or `list[str]` in Pytho {!> ../../../docs_src/query_params_str_validations/tutorial013_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="8" {!> ../../../docs_src/query_params_str_validations/tutorial013_an.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -670,7 +659,7 @@ You can also use `list` directly instead of `List[str]` (or `list[str]` in Pytho ``` !!! note - Have in mind that in this case, FastAPI won't check the contents of the list. + Keep in mind that in this case, FastAPI won't check the contents of the list. For example, `List[int]` would check (and document) that the contents of the list are integers. But `list` alone wouldn't. @@ -681,7 +670,7 @@ You can add more information about the parameter. That information will be included in the generated OpenAPI and used by the documentation user interfaces and external tools. !!! note - Have in mind that different tools might have different levels of OpenAPI support. + Keep in mind that different tools might have different levels of OpenAPI support. Some of them might not show all the extra information declared yet, although in most of the cases, the missing feature is already planned for development. @@ -699,7 +688,7 @@ You can add a `title`: {!> ../../../docs_src/query_params_str_validations/tutorial007_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="11" {!> ../../../docs_src/query_params_str_validations/tutorial007_an.py!} @@ -714,7 +703,7 @@ You can add a `title`: {!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -737,7 +726,7 @@ And a `description`: {!> ../../../docs_src/query_params_str_validations/tutorial008_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="15" {!> ../../../docs_src/query_params_str_validations/tutorial008_an.py!} @@ -748,11 +737,11 @@ And a `description`: !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="12" + ```Python hl_lines="11" {!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -791,7 +780,7 @@ Then you can declare an `alias`, and that alias is what will be used to find the {!> ../../../docs_src/query_params_str_validations/tutorial009_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="10" {!> ../../../docs_src/query_params_str_validations/tutorial009_an.py!} @@ -806,7 +795,7 @@ Then you can declare an `alias`, and that alias is what will be used to find the {!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -835,7 +824,7 @@ Then pass the parameter `deprecated=True` to `Query`: {!> ../../../docs_src/query_params_str_validations/tutorial010_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="20" {!> ../../../docs_src/query_params_str_validations/tutorial010_an.py!} @@ -846,11 +835,11 @@ Then pass the parameter `deprecated=True` to `Query`: !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="17" + ```Python hl_lines="16" {!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -879,7 +868,7 @@ To exclude a query parameter from the generated OpenAPI schema (and thus, from t {!> ../../../docs_src/query_params_str_validations/tutorial014_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="11" {!> ../../../docs_src/query_params_str_validations/tutorial014_an.py!} @@ -894,7 +883,7 @@ To exclude a query parameter from the generated OpenAPI schema (and thus, from t {!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -918,7 +907,7 @@ Validations specific for strings: * `min_length` * `max_length` -* `regex` +* `pattern` In these examples you saw how to declare validations for `str` values. diff --git a/docs/en/docs/tutorial/query-params.md b/docs/en/docs/tutorial/query-params.md index 0b74b10f81c8c..bc3b11948a117 100644 --- a/docs/en/docs/tutorial/query-params.md +++ b/docs/en/docs/tutorial/query-params.md @@ -69,7 +69,7 @@ The same way, you can declare optional query parameters, by setting their defaul {!> ../../../docs_src/query_params/tutorial002_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9" {!> ../../../docs_src/query_params/tutorial002.py!} @@ -90,7 +90,7 @@ You can also declare `bool` types, and they will be converted: {!> ../../../docs_src/query_params/tutorial003_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9" {!> ../../../docs_src/query_params/tutorial003.py!} @@ -143,7 +143,7 @@ They will be detected by name: {!> ../../../docs_src/query_params/tutorial004_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="8 10" {!> ../../../docs_src/query_params/tutorial004.py!} @@ -173,16 +173,18 @@ http://127.0.0.1:8000/items/foo-item ```JSON { - "detail": [ - { - "loc": [ - "query", - "needy" - ], - "msg": "field required", - "type": "value_error.missing" - } - ] + "detail": [ + { + "type": "missing", + "loc": [ + "query", + "needy" + ], + "msg": "Field required", + "input": null, + "url": "https://errors.pydantic.dev/2.1/v/missing" + } + ] } ``` @@ -209,7 +211,7 @@ And of course, you can define some parameters as required, some as having a defa {!> ../../../docs_src/query_params/tutorial006_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="10" {!> ../../../docs_src/query_params/tutorial006.py!} diff --git a/docs/en/docs/tutorial/request-files.md b/docs/en/docs/tutorial/request-files.md index 1fe1e7a33db99..17ac3b25d1b07 100644 --- a/docs/en/docs/tutorial/request-files.md +++ b/docs/en/docs/tutorial/request-files.md @@ -3,7 +3,7 @@ You can define files to be uploaded by the client using `File`. !!! info - To receive uploaded files, first install `python-multipart`. + To receive uploaded files, first install `python-multipart`. E.g. `pip install python-multipart`. @@ -19,13 +19,13 @@ Import `File` and `UploadFile` from `fastapi`: {!> ../../../docs_src/request_files/tutorial001_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="1" {!> ../../../docs_src/request_files/tutorial001_an.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -44,13 +44,13 @@ Create file parameters the same way you would for `Body` or `Form`: {!> ../../../docs_src/request_files/tutorial001_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="8" {!> ../../../docs_src/request_files/tutorial001_an.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -71,7 +71,7 @@ The files will be uploaded as "form data". If you declare the type of your *path operation function* parameter as `bytes`, **FastAPI** will read the file for you and you will receive the contents as `bytes`. -Have in mind that this means that the whole contents will be stored in memory. This will work well for small files. +Keep in mind that this means that the whole contents will be stored in memory. This will work well for small files. But there are several cases in which you might benefit from using `UploadFile`. @@ -85,13 +85,13 @@ Define a file parameter with a type of `UploadFile`: {!> ../../../docs_src/request_files/tutorial001_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="13" {!> ../../../docs_src/request_files/tutorial001_an.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -181,7 +181,7 @@ You can make a file optional by using standard type annotations and setting a de {!> ../../../docs_src/request_files/tutorial001_02_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="10 18" {!> ../../../docs_src/request_files/tutorial001_02_an.py!} @@ -196,7 +196,7 @@ You can make a file optional by using standard type annotations and setting a de {!> ../../../docs_src/request_files/tutorial001_02_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -215,13 +215,13 @@ You can also use `File()` with `UploadFile`, for example, to set additional meta {!> ../../../docs_src/request_files/tutorial001_03_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="8 14" {!> ../../../docs_src/request_files/tutorial001_03_an.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -244,7 +244,7 @@ To use that, declare a list of `bytes` or `UploadFile`: {!> ../../../docs_src/request_files/tutorial002_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="11 16" {!> ../../../docs_src/request_files/tutorial002_an.py!} @@ -259,7 +259,7 @@ To use that, declare a list of `bytes` or `UploadFile`: {!> ../../../docs_src/request_files/tutorial002_py39.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -285,7 +285,7 @@ And the same way as before, you can use `File()` to set additional parameters, e {!> ../../../docs_src/request_files/tutorial003_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="12 19-21" {!> ../../../docs_src/request_files/tutorial003_an.py!} @@ -300,7 +300,7 @@ And the same way as before, you can use `File()` to set additional parameters, e {!> ../../../docs_src/request_files/tutorial003_py39.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. diff --git a/docs/en/docs/tutorial/request-forms-and-files.md b/docs/en/docs/tutorial/request-forms-and-files.md index 1818946c4e087..676ed35ad8a51 100644 --- a/docs/en/docs/tutorial/request-forms-and-files.md +++ b/docs/en/docs/tutorial/request-forms-and-files.md @@ -3,7 +3,7 @@ You can define files and form fields at the same time using `File` and `Form`. !!! info - To receive uploaded files and/or form data, first install `python-multipart`. + To receive uploaded files and/or form data, first install `python-multipart`. E.g. `pip install python-multipart`. @@ -15,13 +15,13 @@ You can define files and form fields at the same time using `File` and `Form`. {!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="1" {!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -40,13 +40,13 @@ Create file and form parameters the same way you would for `Body` or `Query`: {!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9-11" {!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. diff --git a/docs/en/docs/tutorial/request-forms.md b/docs/en/docs/tutorial/request-forms.md index 5d441a6141fb2..5f8f7b14837f4 100644 --- a/docs/en/docs/tutorial/request-forms.md +++ b/docs/en/docs/tutorial/request-forms.md @@ -3,7 +3,7 @@ When you need to receive form fields instead of JSON, you can use `Form`. !!! info - To use forms, first install `python-multipart`. + To use forms, first install `python-multipart`. E.g. `pip install python-multipart`. @@ -17,13 +17,13 @@ Import `Form` from `fastapi`: {!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="1" {!> ../../../docs_src/request_forms/tutorial001_an.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -42,13 +42,13 @@ Create form parameters the same way you would for `Body` or `Query`: {!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="8" {!> ../../../docs_src/request_forms/tutorial001_an.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. diff --git a/docs/en/docs/tutorial/response-model.md b/docs/en/docs/tutorial/response-model.md index 2181cfb5ae7bb..0e6292629a613 100644 --- a/docs/en/docs/tutorial/response-model.md +++ b/docs/en/docs/tutorial/response-model.md @@ -16,7 +16,7 @@ You can use **type annotations** the same way you would for input data in functi {!> ../../../docs_src/response_model/tutorial001_01_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="18 23" {!> ../../../docs_src/response_model/tutorial001_01.py!} @@ -65,7 +65,7 @@ You can use the `response_model` parameter in any of the *path operations*: {!> ../../../docs_src/response_model/tutorial001_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="17 22 24-27" {!> ../../../docs_src/response_model/tutorial001.py!} @@ -101,7 +101,7 @@ Here we are declaring a `UserIn` model, it will contain a plaintext password: {!> ../../../docs_src/response_model/tutorial002_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9 11" {!> ../../../docs_src/response_model/tutorial002.py!} @@ -121,7 +121,7 @@ And we are using this model to declare our input and the same model to declare o {!> ../../../docs_src/response_model/tutorial002_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="18" {!> ../../../docs_src/response_model/tutorial002.py!} @@ -146,7 +146,7 @@ We can instead create an input model with the plaintext password and an output m {!> ../../../docs_src/response_model/tutorial003_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9 11 16" {!> ../../../docs_src/response_model/tutorial003.py!} @@ -160,7 +160,7 @@ Here, even though our *path operation function* is returning the same input user {!> ../../../docs_src/response_model/tutorial003_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="24" {!> ../../../docs_src/response_model/tutorial003.py!} @@ -174,7 +174,7 @@ Here, even though our *path operation function* is returning the same input user {!> ../../../docs_src/response_model/tutorial003_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="22" {!> ../../../docs_src/response_model/tutorial003.py!} @@ -208,7 +208,7 @@ And in those cases, we can use classes and inheritance to take advantage of func {!> ../../../docs_src/response_model/tutorial003_01_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9-13 15-16 20" {!> ../../../docs_src/response_model/tutorial003_01.py!} @@ -284,7 +284,7 @@ The same would happen if you had something like a its `exclude_unset` parameter to achieve this. + In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`. + + The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2. + +!!! info + FastAPI uses Pydantic model's `.dict()` with its `exclude_unset` parameter to achieve this. !!! info You can also use: @@ -386,7 +391,7 @@ So, if you send a request to that *path operation* for the item with ID `foo`, t * `response_model_exclude_defaults=True` * `response_model_exclude_none=True` - as described in the Pydantic docs for `exclude_defaults` and `exclude_none`. + as described in the Pydantic docs for `exclude_defaults` and `exclude_none`. #### Data with values for fields with defaults @@ -447,7 +452,7 @@ This can be used as a quick shortcut if you have only one Pydantic model and wan {!> ../../../docs_src/response_model/tutorial005_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="31 37" {!> ../../../docs_src/response_model/tutorial005.py!} @@ -468,7 +473,7 @@ If you forget to use a `set` and use a `list` or `tuple` instead, FastAPI will s {!> ../../../docs_src/response_model/tutorial006_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="31 37" {!> ../../../docs_src/response_model/tutorial006.py!} diff --git a/docs/en/docs/tutorial/schema-extra-example.md b/docs/en/docs/tutorial/schema-extra-example.md index e0f7ed25696db..9bb9ba4e31d91 100644 --- a/docs/en/docs/tutorial/schema-extra-example.md +++ b/docs/en/docs/tutorial/schema-extra-example.md @@ -4,34 +4,63 @@ You can declare examples of the data your app can receive. Here are several ways to do it. -## Pydantic `schema_extra` +## Extra JSON Schema data in Pydantic models -You can declare an `example` for a Pydantic model using `Config` and `schema_extra`, as described in Pydantic's docs: Schema customization: +You can declare `examples` for a Pydantic model that will be added to the generated JSON Schema. -=== "Python 3.10+" +=== "Python 3.10+ Pydantic v2" - ```Python hl_lines="13-21" + ```Python hl_lines="13-24" {!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.10+ Pydantic v1" + + ```Python hl_lines="13-23" + {!> ../../../docs_src/schema_extra_example/tutorial001_py310_pv1.py!} + ``` + +=== "Python 3.8+ Pydantic v2" - ```Python hl_lines="15-23" + ```Python hl_lines="15-26" {!> ../../../docs_src/schema_extra_example/tutorial001.py!} ``` +=== "Python 3.8+ Pydantic v1" + + ```Python hl_lines="15-25" + {!> ../../../docs_src/schema_extra_example/tutorial001_pv1.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. +=== "Pydantic v2" + + In Pydantic version 2, you would use the attribute `model_config`, that takes a `dict` as described in Pydantic's docs: Model Config. + + You can set `"json_schema_extra"` with a `dict` containing any additional data you would like to show up in the generated JSON Schema, including `examples`. + +=== "Pydantic v1" + + In Pydantic version 1, you would use an internal class `Config` and `schema_extra`, as described in Pydantic's docs: Schema customization. + + You can set `schema_extra` with a `dict` containing any additional data you would like to show up in the generated JSON Schema, including `examples`. + !!! tip You could use the same technique to extend the JSON Schema and add your own custom extra info. For example you could use it to add metadata for a frontend user interface, etc. -## `Field` additional arguments +!!! info + OpenAPI 3.1.0 (used since FastAPI 0.99.0) added support for `examples`, which is part of the **JSON Schema** standard. + + Before that, it only supported the keyword `example` with a single example. That is still supported by OpenAPI 3.1.0, but is deprecated and is not part of the JSON Schema standard. So you are encouraged to migrate `example` to `examples`. 🤓 -When using `Field()` with Pydantic models, you can also declare extra info for the **JSON Schema** by passing any other arbitrary arguments to the function. + You can read more at the end of this page. -You can use this to add `example` for each field: +## `Field` additional arguments + +When using `Field()` with Pydantic models, you can also declare additional `examples`: === "Python 3.10+" @@ -39,16 +68,13 @@ You can use this to add `example` for each field: {!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="4 10-13" {!> ../../../docs_src/schema_extra_example/tutorial002.py!} ``` -!!! warning - Keep in mind that those extra arguments passed won't add any validation, only extra information, for documentation purposes. - -## `example` and `examples` in OpenAPI +## `examples` in JSON Schema - OpenAPI When using any of: @@ -60,27 +86,27 @@ When using any of: * `Form()` * `File()` -you can also declare a data `example` or a group of `examples` with additional information that will be added to **OpenAPI**. +you can also declare a group of `examples` with additional information that will be added to their **JSON Schemas** inside of **OpenAPI**. -### `Body` with `example` +### `Body` with `examples` -Here we pass an `example` of the data expected in `Body()`: +Here we pass `examples` containing one example of the data expected in `Body()`: === "Python 3.10+" - ```Python hl_lines="22-27" + ```Python hl_lines="22-29" {!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!} ``` === "Python 3.9+" - ```Python hl_lines="22-27" + ```Python hl_lines="22-29" {!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" - ```Python hl_lines="23-28" + ```Python hl_lines="23-30" {!> ../../../docs_src/schema_extra_example/tutorial003_an.py!} ``` @@ -89,16 +115,16 @@ Here we pass an `example` of the data expected in `Body()`: !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="18-23" + ```Python hl_lines="18-25" {!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="20-25" + ```Python hl_lines="20-27" {!> ../../../docs_src/schema_extra_example/tutorial003.py!} ``` @@ -110,7 +136,71 @@ With any of the methods above it would look like this in the `/docs`: ### `Body` with multiple `examples` -Alternatively to the single `example`, you can pass `examples` using a `dict` with **multiple examples**, each with extra information that will be added to **OpenAPI** too. +You can of course also pass multiple `examples`: + +=== "Python 3.10+" + + ```Python hl_lines="23-38" + {!> ../../../docs_src/schema_extra_example/tutorial004_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="23-38" + {!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="24-39" + {!> ../../../docs_src/schema_extra_example/tutorial004_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip + Prefer to use the `Annotated` version if possible. + + ```Python hl_lines="19-34" + {!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + Prefer to use the `Annotated` version if possible. + + ```Python hl_lines="21-36" + {!> ../../../docs_src/schema_extra_example/tutorial004.py!} + ``` + +When you do this, the examples will be part of the internal **JSON Schema** for that body data. + +Nevertheless, at the time of writing this, Swagger UI, the tool in charge of showing the docs UI, doesn't support showing multiple examples for the data in **JSON Schema**. But read below for a workaround. + +### OpenAPI-specific `examples` + +Since before **JSON Schema** supported `examples` OpenAPI had support for a different field also called `examples`. + +This **OpenAPI-specific** `examples` goes in another section in the OpenAPI specification. It goes in the **details for each *path operation***, not inside each JSON Schema. + +And Swagger UI has supported this particular `examples` field for a while. So, you can use it to **show** different **examples in the docs UI**. + +The shape of this OpenAPI-specific field `examples` is a `dict` with **multiple examples** (instead of a `list`), each with extra information that will be added to **OpenAPI** too. + +This doesn't go inside of each JSON Schema contained in OpenAPI, this goes outside, in the *path operation* directly. + +### Using the `openapi_examples` Parameter + +You can declare the OpenAPI-specific `examples` in FastAPI with the parameter `openapi_examples` for: + +* `Path()` +* `Query()` +* `Header()` +* `Cookie()` +* `Body()` +* `Form()` +* `File()` The keys of the `dict` identify each example, and each value is another `dict`. @@ -121,22 +211,24 @@ 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`. +You can use it like this: + === "Python 3.10+" ```Python hl_lines="23-49" - {!> ../../../docs_src/schema_extra_example/tutorial004_an_py310.py!} + {!> ../../../docs_src/schema_extra_example/tutorial005_an_py310.py!} ``` === "Python 3.9+" ```Python hl_lines="23-49" - {!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!} + {!> ../../../docs_src/schema_extra_example/tutorial005_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="24-50" - {!> ../../../docs_src/schema_extra_example/tutorial004_an.py!} + {!> ../../../docs_src/schema_extra_example/tutorial005_an.py!} ``` === "Python 3.10+ non-Annotated" @@ -145,45 +237,90 @@ Each specific example `dict` in the `examples` can contain: Prefer to use the `Annotated` version if possible. ```Python hl_lines="19-45" - {!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!} + {!> ../../../docs_src/schema_extra_example/tutorial005_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. ```Python hl_lines="21-47" - {!> ../../../docs_src/schema_extra_example/tutorial004.py!} + {!> ../../../docs_src/schema_extra_example/tutorial005.py!} ``` -### Examples in the docs UI +### OpenAPI Examples in the Docs UI -With `examples` added to `Body()` the `/docs` would look like: +With `openapi_examples` added to `Body()` the `/docs` would look like: ## Technical Details +!!! tip + If you are already using **FastAPI** version **0.99.0 or above**, you can probably **skip** these details. + + They are more relevant for older versions, before OpenAPI 3.1.0 was available. + + You can consider this a brief OpenAPI and JSON Schema **history lesson**. 🤓 + !!! warning These are very technical details about the standards **JSON Schema** and **OpenAPI**. If the ideas above already work for you, that might be enough, and you probably don't need these details, feel free to skip them. -When you add an example inside of a Pydantic model, using `schema_extra` or `Field(example="something")` that example is added to the **JSON Schema** for that Pydantic model. +Before OpenAPI 3.1.0, OpenAPI used an older and modified version of **JSON Schema**. + +JSON Schema didn't have `examples`, so OpenAPI added it's own `example` field to its own modified version. + +OpenAPI also added `example` and `examples` fields to other parts of the specification: + +* `Parameter Object` (in the specification) that was used by FastAPI's: + * `Path()` + * `Query()` + * `Header()` + * `Cookie()` +* `Request Body Object`, in the field `content`, on the `Media Type Object` (in the specification) that was used by FastAPI's: + * `Body()` + * `File()` + * `Form()` + +!!! info + This old OpenAPI-specific `examples` parameter is now `openapi_examples` since FastAPI `0.103.0`. + +### JSON Schema's `examples` field + +But then JSON Schema added an `examples` field to a new version of the specification. + +And then the new OpenAPI 3.1.0 was based on the latest version (JSON Schema 2020-12) that included this new field `examples`. + +And now this new `examples` field takes precedence over the old single (and custom) `example` field, that is now deprecated. + +This new `examples` field in JSON Schema is **just a `list`** of examples, not a dict with extra metadata as in the other places in OpenAPI (described above). + +!!! info + Even after OpenAPI 3.1.0 was released with this new simpler integration with JSON Schema, for a while, Swagger UI, the tool that provides the automatic docs, didn't support OpenAPI 3.1.0 (it does since version 5.0.0 🎉). + + Because of that, versions of FastAPI previous to 0.99.0 still used versions of OpenAPI lower than 3.1.0. + +### Pydantic and FastAPI `examples` + +When you add `examples` inside of a Pydantic model, using `schema_extra` or `Field(examples=["something"])` that example is added to the **JSON Schema** for that Pydantic model. And that **JSON Schema** of the Pydantic model is included in the **OpenAPI** of your API, and then it's used in the docs UI. -**JSON Schema** doesn't really have a field `example` in the standards. Recent versions of JSON Schema define a field `examples`, but OpenAPI 3.0.3 is based on an older version of JSON Schema that didn't have `examples`. +In versions of FastAPI before 0.99.0 (0.99.0 and above use the newer OpenAPI 3.1.0) when you used `example` or `examples` with any of the other utilities (`Query()`, `Body()`, etc.) those examples were not added to the JSON Schema that describes that data (not even to OpenAPI's own version of JSON Schema), they were added directly to the *path operation* declaration in OpenAPI (outside the parts of OpenAPI that use JSON Schema). + +But now that FastAPI 0.99.0 and above uses OpenAPI 3.1.0, that uses JSON Schema 2020-12, and Swagger UI 5.0.0 and above, everything is more consistent and the examples are included in JSON Schema. -So, OpenAPI 3.0.3 defined its own `example` for the modified version of **JSON Schema** it uses, for the same purpose (but it's a single `example`, not `examples`), and that's what is used by the API docs UI (using Swagger UI). +### Swagger UI and OpenAPI-specific `examples` -So, although `example` is not part of JSON Schema, it is part of OpenAPI's custom version of JSON Schema, and that's what will be used by the docs UI. +Now, as Swagger UI didn't support multiple JSON Schema examples (as of 2023-08-26), users didn't have a way to show multiple examples in the docs. -But when you use `example` or `examples` with any of the other utilities (`Query()`, `Body()`, etc.) those examples are not added to the JSON Schema that describes that data (not even to OpenAPI's own version of JSON Schema), they are added directly to the *path operation* declaration in OpenAPI (outside the parts of OpenAPI that use JSON Schema). +To solve that, FastAPI `0.103.0` **added support** for declaring the same old **OpenAPI-specific** `examples` field with the new parameter `openapi_examples`. 🤓 -For `Path()`, `Query()`, `Header()`, and `Cookie()`, the `example` or `examples` are added to the OpenAPI definition, to the `Parameter Object` (in the specification). +### Summary -And for `Body()`, `File()`, and `Form()`, the `example` or `examples` are equivalently added to the OpenAPI definition, to the `Request Body Object`, in the field `content`, on the `Media Type Object` (in the specification). +I used to say I didn't like history that much... and look at me now giving "tech history" lessons. 😅 -On the other hand, there's a newer version of OpenAPI: **3.1.0**, recently released. It is based on the latest JSON Schema and most of the modifications from OpenAPI's custom version of JSON Schema are removed, in exchange of the features from the recent versions of JSON Schema, so all these small differences are reduced. Nevertheless, Swagger UI currently doesn't support OpenAPI 3.1.0, so, for now, it's better to continue using the ideas above. +In short, **upgrade to FastAPI 0.99.0 or above**, and things are much **simpler, consistent, and intuitive**, and you don't have to know all these historic details. 😎 diff --git a/docs/en/docs/tutorial/security/first-steps.md b/docs/en/docs/tutorial/security/first-steps.md index 5765cf2d62611..7d86e453eacfb 100644 --- a/docs/en/docs/tutorial/security/first-steps.md +++ b/docs/en/docs/tutorial/security/first-steps.md @@ -26,13 +26,13 @@ Copy the example in a file `main.py`: {!> ../../../docs_src/security/tutorial001_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python {!> ../../../docs_src/security/tutorial001_an.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -45,7 +45,7 @@ Copy the example in a file `main.py`: ## Run it !!! info - First install `python-multipart`. + First install `python-multipart`. E.g. `pip install python-multipart`. @@ -140,13 +140,13 @@ When we create an instance of the `OAuth2PasswordBearer` class we pass in the `t {!> ../../../docs_src/security/tutorial001_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="7" {!> ../../../docs_src/security/tutorial001_an.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -191,13 +191,13 @@ Now you can pass that `oauth2_scheme` in a dependency with `Depends`. {!> ../../../docs_src/security/tutorial001_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="11" {!> ../../../docs_src/security/tutorial001_an.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. diff --git a/docs/en/docs/tutorial/security/get-current-user.md b/docs/en/docs/tutorial/security/get-current-user.md index 1a8c5d9a8d8fd..dc6d87c9caaf8 100644 --- a/docs/en/docs/tutorial/security/get-current-user.md +++ b/docs/en/docs/tutorial/security/get-current-user.md @@ -8,13 +8,13 @@ In the previous chapter the security system (which is based on the dependency in {!> ../../../docs_src/security/tutorial001_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="11" {!> ../../../docs_src/security/tutorial001_an.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -45,7 +45,7 @@ The same way we use Pydantic to declare bodies, we can use it anywhere else: {!> ../../../docs_src/security/tutorial002_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="5 13-17" {!> ../../../docs_src/security/tutorial002_an.py!} @@ -60,7 +60,7 @@ The same way we use Pydantic to declare bodies, we can use it anywhere else: {!> ../../../docs_src/security/tutorial002_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -91,7 +91,7 @@ The same as we were doing before in the *path operation* directly, our new depen {!> ../../../docs_src/security/tutorial002_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="26" {!> ../../../docs_src/security/tutorial002_an.py!} @@ -106,7 +106,7 @@ The same as we were doing before in the *path operation* directly, our new depen {!> ../../../docs_src/security/tutorial002_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -131,7 +131,7 @@ The same as we were doing before in the *path operation* directly, our new depen {!> ../../../docs_src/security/tutorial002_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="20-23 27-28" {!> ../../../docs_src/security/tutorial002_an.py!} @@ -146,7 +146,7 @@ The same as we were doing before in the *path operation* directly, our new depen {!> ../../../docs_src/security/tutorial002_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -171,7 +171,7 @@ So now we can use the same `Depends` with our `get_current_user` in the *path op {!> ../../../docs_src/security/tutorial002_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="32" {!> ../../../docs_src/security/tutorial002_an.py!} @@ -186,7 +186,7 @@ So now we can use the same `Depends` with our `get_current_user` in the *path op {!> ../../../docs_src/security/tutorial002_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -227,7 +227,7 @@ Just use any kind of model, any kind of class, any kind of database that you nee ## Code size -This example might seem verbose. Have in mind that we are mixing security, data models, utility functions and *path operations* in the same file. +This example might seem verbose. Keep in mind that we are mixing security, data models, utility functions and *path operations* in the same file. But here's the key point. @@ -253,7 +253,7 @@ And all these thousands of *path operations* can be as small as 3 lines: {!> ../../../docs_src/security/tutorial002_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="31-33" {!> ../../../docs_src/security/tutorial002_an.py!} @@ -268,7 +268,7 @@ And all these thousands of *path operations* can be as small as 3 lines: {!> ../../../docs_src/security/tutorial002_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. diff --git a/docs/en/docs/tutorial/security/oauth2-jwt.md b/docs/en/docs/tutorial/security/oauth2-jwt.md index deb722b966e26..1c792e3d9e599 100644 --- a/docs/en/docs/tutorial/security/oauth2-jwt.md +++ b/docs/en/docs/tutorial/security/oauth2-jwt.md @@ -121,7 +121,7 @@ And another one to authenticate and return a user. {!> ../../../docs_src/security/tutorial004_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="7 49 56-57 60-61 70-76" {!> ../../../docs_src/security/tutorial004_an.py!} @@ -136,7 +136,7 @@ And another one to authenticate and return a user. {!> ../../../docs_src/security/tutorial004_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -188,7 +188,7 @@ Create a utility function to generate a new access token. {!> ../../../docs_src/security/tutorial004_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="6 13-15 29-31 79-87" {!> ../../../docs_src/security/tutorial004_an.py!} @@ -203,7 +203,7 @@ Create a utility function to generate a new access token. {!> ../../../docs_src/security/tutorial004_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -232,7 +232,7 @@ If the token is invalid, return an HTTP error right away. {!> ../../../docs_src/security/tutorial004_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="90-107" {!> ../../../docs_src/security/tutorial004_an.py!} @@ -247,7 +247,7 @@ If the token is invalid, return an HTTP error right away. {!> ../../../docs_src/security/tutorial004_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -274,7 +274,7 @@ Create a real JWT access token and return it {!> ../../../docs_src/security/tutorial004_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="118-133" {!> ../../../docs_src/security/tutorial004_an.py!} @@ -285,16 +285,16 @@ Create a real JWT access token and return it !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="114-127" + ```Python hl_lines="114-129" {!> ../../../docs_src/security/tutorial004_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="115-128" + ```Python hl_lines="115-130" {!> ../../../docs_src/security/tutorial004.py!} ``` @@ -318,7 +318,7 @@ In those cases, several of those entities could have the same ID, let's say `foo So, to avoid ID collisions, when creating the JWT token for the user, you could prefix the value of the `sub` key, e.g. with `username:`. So, in this example, the value of `sub` could have been: `username:johndoe`. -The important thing to have in mind is that the `sub` key should have a unique identifier across the entire application, and it should be a string. +The important thing to keep in mind is that the `sub` key should have a unique identifier across the entire application, and it should be a string. ## Check it diff --git a/docs/en/docs/tutorial/security/simple-oauth2.md b/docs/en/docs/tutorial/security/simple-oauth2.md index abcf6b667c573..88edc9eab9837 100644 --- a/docs/en/docs/tutorial/security/simple-oauth2.md +++ b/docs/en/docs/tutorial/security/simple-oauth2.md @@ -61,7 +61,7 @@ First, import `OAuth2PasswordRequestForm`, and use it as a dependency with `Depe {!> ../../../docs_src/security/tutorial003_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="4 79" {!> ../../../docs_src/security/tutorial003_an.py!} @@ -76,7 +76,7 @@ First, import `OAuth2PasswordRequestForm`, and use it as a dependency with `Depe {!> ../../../docs_src/security/tutorial003_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -134,7 +134,7 @@ For the error, we use the exception `HTTPException`: {!> ../../../docs_src/security/tutorial003_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="3 80-82" {!> ../../../docs_src/security/tutorial003_an.py!} @@ -149,7 +149,7 @@ For the error, we use the exception `HTTPException`: {!> ../../../docs_src/security/tutorial003_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -194,7 +194,7 @@ So, the thief won't be able to try to use those same passwords in another system {!> ../../../docs_src/security/tutorial003_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="83-86" {!> ../../../docs_src/security/tutorial003_an.py!} @@ -209,7 +209,7 @@ So, the thief won't be able to try to use those same passwords in another system {!> ../../../docs_src/security/tutorial003_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -264,7 +264,7 @@ For this simple example, we are going to just be completely insecure and return {!> ../../../docs_src/security/tutorial003_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="88" {!> ../../../docs_src/security/tutorial003_an.py!} @@ -279,7 +279,7 @@ For this simple example, we are going to just be completely insecure and return {!> ../../../docs_src/security/tutorial003_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. @@ -321,7 +321,7 @@ So, in our endpoint, we will only get a user if the user exists, was correctly a {!> ../../../docs_src/security/tutorial003_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="59-67 70-75 95" {!> ../../../docs_src/security/tutorial003_an.py!} @@ -336,7 +336,7 @@ So, in our endpoint, we will only get a user if the user exists, was correctly a {!> ../../../docs_src/security/tutorial003_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. diff --git a/docs/en/docs/tutorial/sql-databases.md b/docs/en/docs/tutorial/sql-databases.md index fd66c5add0720..1a2000f02ba6e 100644 --- a/docs/en/docs/tutorial/sql-databases.md +++ b/docs/en/docs/tutorial/sql-databases.md @@ -1,5 +1,12 @@ # SQL (Relational) Databases +!!! info + These docs are about to be updated. 🎉 + + The current version assumes Pydantic v1, and SQLAlchemy versions less than 2.0. + + The new docs will include Pydantic v2 and will use SQLModel (which is also based on SQLAlchemy) once it is updated to use Pydantic v2 as well. + **FastAPI** doesn't require you to use a SQL (relational) database. But you can use any relational database that you want. @@ -274,7 +281,7 @@ But for security, the `password` won't be in other Pydantic *models*, for exampl {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="3 6-8 11-12 23-24 27-28" {!> ../../../docs_src/sql_databases/sql_app/schemas.py!} @@ -294,7 +301,7 @@ while Pydantic *models* declare the types using `:`, the new type annotation syn name: str ``` -Have it in mind, so you don't get confused when using `=` and `:` with them. +Keep these in mind, so you don't get confused when using `=` and `:` with them. ### Create Pydantic *models* / schemas for reading / returning @@ -318,7 +325,7 @@ Not only the IDs of those items, but all the data that we defined in the Pydanti {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="15-17 31-34" {!> ../../../docs_src/sql_databases/sql_app/schemas.py!} @@ -331,7 +338,7 @@ Not only the IDs of those items, but all the data that we defined in the Pydanti Now, in the Pydantic *models* for reading, `Item` and `User`, add an internal `Config` class. -This `Config` class is used to provide configurations to Pydantic. +This `Config` class is used to provide configurations to Pydantic. In the `Config` class, set the attribute `orm_mode = True`. @@ -347,7 +354,7 @@ In the `Config` class, set the attribute `orm_mode = True`. {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="15 19-20 31 36-37" {!> ../../../docs_src/sql_databases/sql_app/schemas.py!} @@ -444,6 +451,11 @@ The steps are: {!../../../docs_src/sql_databases/sql_app/crud.py!} ``` +!!! info + In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`. + + The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2. + !!! tip The SQLAlchemy model for `User` contains a `hashed_password` that should contain a secure hashed version of the password. @@ -487,7 +499,7 @@ In a very simplistic way create the database tables: {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9" {!> ../../../docs_src/sql_databases/sql_app/main.py!} @@ -501,7 +513,7 @@ And you would also use Alembic for "migrations" (that's its main job). A "migration" is the set of steps needed whenever you change the structure of your SQLAlchemy models, add a new attribute, etc. to replicate those changes in the database, add a new column, a new table, etc. -You can find an example of Alembic in a FastAPI project in the templates from [Project Generation - Template](../project-generation.md){.internal-link target=_blank}. Specifically in the `alembic` directory in the source code. +You can find an example of Alembic in a FastAPI project in the templates from [Project Generation - Template](../project-generation.md){.internal-link target=_blank}. Specifically in the `alembic` directory in the source code. ### Create a dependency @@ -521,7 +533,7 @@ Our dependency will create a new SQLAlchemy `SessionLocal` that will be used in {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="15-20" {!> ../../../docs_src/sql_databases/sql_app/main.py!} @@ -546,7 +558,7 @@ This will then give us better editor support inside the *path operation function {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="24 32 38 47 53" {!> ../../../docs_src/sql_databases/sql_app/main.py!} @@ -567,7 +579,7 @@ Now, finally, here's the standard **FastAPI** *path operations* code. {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="23-28 31-34 37-42 45-49 52-55" {!> ../../../docs_src/sql_databases/sql_app/main.py!} @@ -617,7 +629,7 @@ def read_user(user_id: int, db: Session = Depends(get_db)): ``` !!! info - If you need to connect to your relational database asynchronously, see [Async SQL (Relational) Databases](../advanced/async-sql-databases.md){.internal-link target=_blank}. + If you need to connect to your relational database asynchronously, see [Async SQL (Relational) Databases](../how-to/async-sql-encode-databases.md){.internal-link target=_blank}. !!! note "Very Technical Details" If you are curious and have a deep technical knowledge, you can check the very technical details of how this `async def` vs `def` is handled in the [Async](../async.md#very-technical-details){.internal-link target=_blank} docs. @@ -666,7 +678,7 @@ For example, in a background task worker with ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python {!> ../../../docs_src/sql_databases/sql_app/schemas.py!} @@ -686,7 +698,7 @@ For example, in a background task worker with ../../../docs_src/sql_databases/sql_app_py39/main.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python {!> ../../../docs_src/sql_databases/sql_app/main.py!} @@ -745,7 +757,7 @@ The middleware we'll add (just a function) will create a new SQLAlchemy `Session {!> ../../../docs_src/sql_databases/sql_app_py39/alt_main.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="14-22" {!> ../../../docs_src/sql_databases/sql_app/alt_main.py!} diff --git a/docs/en/docs/tutorial/static-files.md b/docs/en/docs/tutorial/static-files.md index 7a0c36af3f4c5..311d2b1c8de14 100644 --- a/docs/en/docs/tutorial/static-files.md +++ b/docs/en/docs/tutorial/static-files.md @@ -22,7 +22,7 @@ You can serve static files automatically from a directory using `StaticFiles`. This is different from using an `APIRouter` as a mounted application is completely independent. The OpenAPI and docs from your main application won't include anything from the mounted application, etc. -You can read more about this in the **Advanced User Guide**. +You can read more about this in the [Advanced User Guide](../advanced/index.md){.internal-link target=_blank}. ## Details diff --git a/docs/en/docs/tutorial/testing.md b/docs/en/docs/tutorial/testing.md index ec133a4d0876b..3f8dd69a1d74e 100644 --- a/docs/en/docs/tutorial/testing.md +++ b/docs/en/docs/tutorial/testing.md @@ -122,7 +122,7 @@ Both *path operations* require an `X-Token` header. {!> ../../../docs_src/app_testing/app_b_an_py39/main.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python {!> ../../../docs_src/app_testing/app_b_an/main.py!} @@ -137,7 +137,7 @@ Both *path operations* require an `X-Token` header. {!> ../../../docs_src/app_testing/app_b_py310/main.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. diff --git a/docs/en/mkdocs.insiders.yml b/docs/en/mkdocs.insiders.yml index d204974b802c2..8f3538a805645 100644 --- a/docs/en/mkdocs.insiders.yml +++ b/docs/en/mkdocs.insiders.yml @@ -1,7 +1,8 @@ plugins: - social: - cards_layout_dir: ../en/layouts - cards_layout: custom - cards_layout_options: - logo: ../en/docs/img/icon-white.svg + # TODO: Re-enable once this is fixed: https://github.com/squidfunk/mkdocs-material/issues/6983 + # social: + # cards_layout_dir: ../en/layouts + # cards_layout: custom + # cards_layout_options: + # logo: ../en/docs/img/icon-white.svg typeset: diff --git a/docs/en/mkdocs.maybe-insiders.yml b/docs/en/mkdocs.maybe-insiders.yml index 8e62713345d03..37fd9338efc5f 100644 --- a/docs/en/mkdocs.maybe-insiders.yml +++ b/docs/en/mkdocs.maybe-insiders.yml @@ -1,3 +1,6 @@ # Define this here and not in the main mkdocs.yml file because that one is auto # updated and written, and the script would remove the env var INHERIT: !ENV [INSIDERS_FILE, '../en/mkdocs.no-insiders.yml'] +markdown_extensions: + pymdownx.highlight: + linenums: !ENV [LINENUMS, false] diff --git a/docs/en/mkdocs.yml b/docs/en/mkdocs.yml index 21300b9dcb1dc..9e22e3a22d7d2 100644 --- a/docs/en/mkdocs.yml +++ b/docs/en/mkdocs.yml @@ -30,6 +30,7 @@ theme: - content.code.annotate - content.code.copy - content.code.select + - navigation.tabs icon: repo: fontawesome/brands/github-alt logo: img/icon-white.svg @@ -42,151 +43,208 @@ plugins: search: null markdownextradata: data: ../en/data + redirects: + redirect_maps: + deployment/deta.md: deployment/cloud.md + advanced/sql-databases-peewee.md: how-to/sql-databases-peewee.md + advanced/async-sql-databases.md: how-to/async-sql-encode-databases.md + advanced/nosql-databases.md: how-to/nosql-databases-couchbase.md + advanced/graphql.md: how-to/graphql.md + advanced/custom-request-and-route.md: how-to/custom-request-and-route.md + advanced/conditional-openapi.md: how-to/conditional-openapi.md + advanced/extending-openapi.md: how-to/extending-openapi.md + mkdocstrings: + handlers: + python: + options: + extensions: + - griffe_typingdoc + show_root_heading: true + show_if_no_docstring: true + preload_modules: + - httpx + - starlette + inherited_members: true + members_order: source + separate_signature: true + unwrap_annotated: true + filters: + - '!^_' + merge_init_into_class: true + docstring_section_style: spacy + signature_crossrefs: true + show_symbol_type_heading: true + show_symbol_type_toc: true nav: - FastAPI: index.md -- Languages: - - en: / - - de: /de/ - - em: /em/ - - es: /es/ - - fa: /fa/ - - fr: /fr/ - - he: /he/ - - id: /id/ - - ja: /ja/ - - ko: /ko/ - - pl: /pl/ - - pt: /pt/ - - ru: /ru/ - - tr: /tr/ - - zh: /zh/ - features.md +- Learn: + - learn/index.md + - python-types.md + - async.md + - Tutorial - User Guide: + - 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 + - Dependencies: + - 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 + - Security: + - 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 User Guide: + - 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: + - 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/sub-applications.md + - advanced/behind-a-proxy.md + - advanced/templates.md + - advanced/websockets.md + - advanced/events.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/openapi-callbacks.md + - advanced/openapi-webhooks.md + - advanced/wsgi.md + - advanced/generate-clients.md + - Deployment: + - deployment/index.md + - deployment/versions.md + - deployment/https.md + - deployment/manually.md + - deployment/concepts.md + - deployment/cloud.md + - deployment/server-workers.md + - deployment/docker.md + - How To - Recipes: + - how-to/index.md + - how-to/general.md + - how-to/graphql.md + - how-to/custom-request-and-route.md + - how-to/conditional-openapi.md + - how-to/extending-openapi.md + - how-to/separate-openapi-schemas.md + - how-to/custom-docs-ui-assets.md + - how-to/configure-swagger-ui.md + - how-to/sql-databases-peewee.md + - how-to/async-sql-encode-databases.md + - how-to/nosql-databases-couchbase.md +- Reference (Code API): + - reference/index.md + - reference/fastapi.md + - reference/parameters.md + - reference/status.md + - reference/uploadfile.md + - reference/exceptions.md + - reference/dependencies.md + - reference/apirouter.md + - reference/background.md + - reference/request.md + - reference/websockets.md + - reference/httpconnection.md + - reference/response.md + - reference/responses.md + - reference/middleware.md + - OpenAPI: + - reference/openapi/index.md + - reference/openapi/docs.md + - reference/openapi/models.md + - reference/security/index.md + - reference/encoders.md + - reference/staticfiles.md + - reference/templating.md + - reference/testclient.md - fastapi-people.md -- python-types.md -- Tutorial - User Guide: - - 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 - - Dependencies: - - 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 - - Security: - - 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 User Guide: - - 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: - - 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: - - 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 -- newsletter.md -- contributing.md +- Resources: + - resources/index.md + - project-generation.md + - external-links.md + - newsletter.md +- About: + - about/index.md + - alternatives.md + - history-design-future.md + - benchmarks.md +- Help: + - help/index.md + - help-fastapi.md + - contributing.md - release-notes.md markdown_extensions: -- toc: + toc: permalink: true -- markdown.extensions.codehilite: + markdown.extensions.codehilite: guess_lang: false -- mdx_include: + mdx_include: base_path: docs -- admonition -- codehilite -- extra -- pymdownx.superfences: + admonition: null + codehilite: null + extra: null + pymdownx.superfences: custom_fences: - name: mermaid class: mermaid format: !!python/name:pymdownx.superfences.fence_code_format '' -- pymdownx.tabbed: + pymdownx.tabbed: alternate_style: true -- attr_list -- md_in_html + pymdownx.tilde: null + attr_list: null + md_in_html: null extra: analytics: provider: google @@ -209,34 +267,52 @@ extra: alternate: - link: / name: en - English + - link: /az/ + name: az - azərbaycan dili + - link: /bn/ + name: bn - বাংলা - link: /de/ - name: de - - link: /em/ - name: 😉 + name: de - Deutsch - link: /es/ name: es - español - link: /fa/ - name: fa + name: fa - فارسی - link: /fr/ name: fr - français - link: /he/ - name: he + name: he - עברית + - link: /hu/ + name: hu - magyar - link: /id/ - name: id + name: id - Bahasa Indonesia + - link: /it/ + name: it - italiano - link: /ja/ name: ja - 日本語 - link: /ko/ name: ko - 한국어 - link: /pl/ - name: pl + name: pl - Polski - link: /pt/ name: pt - português - link: /ru/ name: ru - русский язык - link: /tr/ name: tr - Türkçe + - link: /uk/ + name: uk - українська мова + - link: /ur/ + name: ur - اردو + - link: /vi/ + name: vi - Tiếng Việt + - link: /yo/ + name: yo - Yorùbá - link: /zh/ - name: zh - 汉语 + name: zh - 简体中文 + - link: /zh-hant/ + name: zh-hant - 繁體中文 + - link: /em/ + name: 😉 extra_css: - css/termynal.css - css/custom.css diff --git a/docs/en/overrides/main.html b/docs/en/overrides/main.html index 4608880f21a1a..28a912fb3f05b 100644 --- a/docs/en/overrides/main.html +++ b/docs/en/overrides/main.html @@ -34,38 +34,48 @@
+ + + + + + +
{% endblock %} -{%- block scripts %} -{{ super() }} - - - - - - - -{%- endblock %} diff --git a/docs/en/overrides/partials/copyright.html b/docs/en/overrides/partials/copyright.html new file mode 100644 index 0000000000000..dcca89abe30e1 --- /dev/null +++ b/docs/en/overrides/partials/copyright.html @@ -0,0 +1,11 @@ + diff --git a/docs/es/docs/about/index.md b/docs/es/docs/about/index.md new file mode 100644 index 0000000000000..e83400a8dc100 --- /dev/null +++ b/docs/es/docs/about/index.md @@ -0,0 +1,3 @@ +# Acerca de + +Acerca de FastAPI, su diseño, inspiración y más. 🤓 diff --git a/docs/es/docs/advanced/additional-status-codes.md b/docs/es/docs/advanced/additional-status-codes.md index 1f28ea85b738a..eaa3369ebe0b7 100644 --- a/docs/es/docs/advanced/additional-status-codes.md +++ b/docs/es/docs/advanced/additional-status-codes.md @@ -23,7 +23,7 @@ Para conseguir esto importa `JSONResponse` y devuelve ahí directamente tu conte No será serializado con el modelo, etc. - Asegurate de que la respuesta tenga los datos que quieras, y que los valores sean JSON válidos (si estás usando `JSONResponse`). + Asegúrate de que la respuesta tenga los datos que quieras, y que los valores sean JSON válidos (si estás usando `JSONResponse`). !!! note "Detalles Técnicos" También podrías utilizar `from starlette.responses import JSONResponse`. diff --git a/docs/es/docs/advanced/response-change-status-code.md b/docs/es/docs/advanced/response-change-status-code.md new file mode 100644 index 0000000000000..ecd9fad416fa3 --- /dev/null +++ b/docs/es/docs/advanced/response-change-status-code.md @@ -0,0 +1,33 @@ +# Response - Cambiar el Status Code + +Probablemente ya has leído con anterioridad que puedes establecer un [Response Status Code](../tutorial/response-status-code.md){.internal-link target=_blank} por defecto. + +Pero en algunos casos necesitas retornar un status code diferente al predeterminado. + +## Casos de uso + +Por ejemplo, imagina que quieres retornar un HTTP status code de "OK" `200` por defecto. + +Pero si los datos no existen, quieres crearlos y retornar un HTTP status code de "CREATED" `201`. + +Pero aún quieres poder filtrar y convertir los datos que retornas con un `response_model`. + +Para esos casos, puedes usar un parámetro `Response`. + +## Usar un parámetro `Response` + +Puedes declarar un parámetro de tipo `Response` en tu *función de la operación de path* (como puedes hacer para cookies y headers). + +Y luego puedes establecer el `status_code` en ese objeto de respuesta *temporal*. + +```Python hl_lines="1 9 12" +{!../../../docs_src/response_change_status_code/tutorial001.py!} +``` + +Y luego puedes retornar cualquier objeto que necesites, como normalmente lo harías (un `dict`, un modelo de base de datos, etc). + +Y si declaraste un `response_model`, aún se usará para filtrar y convertir el objeto que retornaste. + +**FastAPI** usará esa respuesta *temporal* para extraer el código de estado (también cookies y headers), y los pondrá en la respuesta final que contiene el valor que retornaste, filtrado por cualquier `response_model`. + +También puedes declarar la dependencia del parámetro `Response`, y establecer el código de estado en ellos. Pero ten en cuenta que el último en establecerse será el que gane. diff --git a/docs/es/docs/advanced/response-directly.md b/docs/es/docs/advanced/response-directly.md index 54dadf5763a9b..dee44ac08a239 100644 --- a/docs/es/docs/advanced/response-directly.md +++ b/docs/es/docs/advanced/response-directly.md @@ -21,7 +21,7 @@ Y cuando devuelves una `Response`, **FastAPI** la pasará directamente. No hará ninguna conversión de datos con modelos Pydantic, no convertirá el contenido a ningún tipo, etc. -Esto te da mucha flexibilidad. Puedes devolver cualquier tipo de dato, sobrescribir cualquer declaración de datos o validación, etc. +Esto te da mucha flexibilidad. Puedes devolver cualquier tipo de dato, sobrescribir cualquier declaración de datos o validación, etc. ## Usando el `jsonable_encoder` en una `Response` diff --git a/docs/es/docs/advanced/response-headers.md b/docs/es/docs/advanced/response-headers.md new file mode 100644 index 0000000000000..aec88a58480dd --- /dev/null +++ b/docs/es/docs/advanced/response-headers.md @@ -0,0 +1,44 @@ +# Headers de Respuesta + +## Usar un parámetro `Response` + +Puedes declarar un parámetro de tipo `Response` en tu *función de operación de path* (de manera similar como se hace con las cookies). + +Y entonces, podrás configurar las cookies en ese objeto de response *temporal*. + +```Python hl_lines="1 7-8" +{!../../../docs_src/response_headers/tutorial002.py!} +``` + +Posteriormente, puedes devolver cualquier objeto que necesites, como normalmente harías (un `dict`, un modelo de base de datos, etc). + +Si declaraste un `response_model`, este se continuará usando para filtrar y convertir el objeto que devolviste. + +**FastAPI** usará ese response *temporal* para extraer los headers (al igual que las cookies y el status code), además las pondrá en el response final que contendrá el valor retornado y filtrado por algún `response_model`. + +También puedes declarar el parámetro `Response` en dependencias, así como configurar los headers (y las cookies) en ellas. + + +## Retornar una `Response` directamente + +Adicionalmente, puedes añadir headers cuando se retorne una `Response` directamente. + +Crea un response tal como se describe en [Retornar una respuesta directamente](response-directly.md){.internal-link target=_blank} y pasa los headers como un parámetro adicional: + +```Python hl_lines="10-12" +{!../../../docs_src/response_headers/tutorial001.py!} +``` + +!!! note "Detalles Técnicos" + También podrías utilizar `from starlette.responses import Response` o `from starlette.responses import JSONResponse`. + + **FastAPI** proporciona las mismas `starlette.responses` en `fastapi.responses` sólo que de una manera más conveniente para ti, el desarrollador. En otras palabras, muchas de las responses disponibles provienen directamente de Starlette. + + + Y como la `Response` puede ser usada frecuentemente para configurar headers y cookies, **FastAPI** también la provee en `fastapi.Response`. + +## Headers Personalizados + +Ten en cuenta que se pueden añadir headers propietarios personalizados usando el prefijo 'X-'. + +Si tienes headers personalizados y deseas que un cliente pueda verlos en el navegador, es necesario que los añadas a tus configuraciones de CORS (puedes leer más en [CORS (Cross-Origin Resource Sharing)](../tutorial/cors.md){.internal-link target=_blank}), usando el parámetro `expose_headers` documentado en Starlette's CORS docs. diff --git a/docs/es/docs/advanced/security/index.md b/docs/es/docs/advanced/security/index.md new file mode 100644 index 0000000000000..e393fde4ede87 --- /dev/null +++ b/docs/es/docs/advanced/security/index.md @@ -0,0 +1,16 @@ +# Seguridad Avanzada + +## Características Adicionales + +Hay algunas características adicionales para manejar la seguridad además de las que se tratan en el [Tutorial - Guía de Usuario: Seguridad](../../tutorial/security/){.internal-link target=_blank}. + +!!! tip + Las siguientes secciones **no necesariamente son "avanzadas"**. + + Y es posible que para tu caso de uso, la solución esté en alguna de ellas. + +## Leer primero el Tutorial + +En las siguientes secciones asumimos que ya has leído el principal [Tutorial - Guía de Usuario: Seguridad](../../tutorial/security/){.internal-link target=_blank}. + +Están basadas en los mismos conceptos, pero permiten algunas funcionalidades adicionales. diff --git a/docs/es/docs/benchmarks.md b/docs/es/docs/benchmarks.md new file mode 100644 index 0000000000000..3e02d4e9f47f8 --- /dev/null +++ b/docs/es/docs/benchmarks.md @@ -0,0 +1,33 @@ +# Benchmarks + +Los benchmarks independientes de TechEmpower muestran aplicaciones de **FastAPI** que se ejecutan en Uvicorn como uno de los frameworks de Python más rápidos disponibles, solo por debajo de Starlette y Uvicorn (utilizados internamente por FastAPI). (*) + +Pero al comprobar benchmarks y comparaciones debes tener en cuenta lo siguiente. + +## Benchmarks y velocidad + +Cuando revisas los benchmarks, es común ver varias herramientas de diferentes tipos comparadas como equivalentes. + +Específicamente, para ver Uvicorn, Starlette y FastAPI comparadas entre sí (entre muchas otras herramientas). + +Cuanto más sencillo sea el problema resuelto por la herramienta, mejor rendimiento obtendrá. Y la mayoría de los benchmarks no prueban las funciones adicionales proporcionadas por la herramienta. + +La jerarquía sería: + +* **Uvicorn**: como servidor ASGI + * **Starlette**: (usa Uvicorn) un microframework web + * **FastAPI**: (usa Starlette) un microframework API con varias características adicionales para construir APIs, con validación de datos, etc. +* **Uvicorn**: + * Tendrá el mejor rendimiento, ya que no tiene mucho código extra aparte del propio servidor. + * No escribirías una aplicación directamente en Uvicorn. Eso significaría que tu código tendría que incluir más o menos, al menos, todo el código proporcionado por Starlette (o **FastAPI**). Y si hicieras eso, tu aplicación final tendría la misma sobrecarga que si hubieras usado un framework y minimizado el código de tu aplicación y los errores. + * Si estás comparando Uvicorn, compáralo con los servidores de aplicaciones Daphne, Hypercorn, uWSGI, etc. +* **Starlette**: + * Tendrá el siguiente mejor desempeño, después de Uvicorn. De hecho, Starlette usa Uvicorn para correr. Por lo tanto, probablemente sólo pueda volverse "más lento" que Uvicorn al tener que ejecutar más código. + * Pero te proporciona las herramientas para crear aplicaciones web simples, con routing basado en paths, etc. + * Si estás comparando Starlette, compáralo con Sanic, Flask, Django, etc. Frameworks web (o microframeworks). +* **FastAPI**: + * De la misma manera que Starlette usa Uvicorn y no puede ser más rápido que él, **FastAPI** usa Starlette, por lo que no puede ser más rápido que él. + * * FastAPI ofrece más características además de las de Starlette. Funciones que casi siempre necesitas al crear una API, como validación y serialización de datos. Y al usarlo, obtienes documentación automática de forma gratuita (la documentación automática ni siquiera agrega gastos generales a las aplicaciones en ejecución, se genera al iniciar). + * Si no usaras FastAPI y usaras Starlette directamente (u otra herramienta, como Sanic, Flask, Responder, etc.), tendrías que implementar toda la validación y serialización de datos tu mismo. Por lo tanto, tu aplicación final seguirá teniendo la misma sobrecarga que si se hubiera creado con FastAPI. Y en muchos casos, esta validación y serialización de datos constituye la mayor cantidad de código escrito en las aplicaciones. + * Entonces, al usar FastAPI estás ahorrando tiempo de desarrollo, errores, líneas de código y probablemente obtendrías el mismo rendimiento (o mejor) que obtendrías si no lo usaras (ya que tendrías que implementarlo todo en tu código). + * Si estás comparando FastAPI, compáralo con un framework de aplicaciones web (o conjunto de herramientas) que proporciona validación, serialización y documentación de datos, como Flask-apispec, NestJS, Molten, etc. Frameworks con validación, serialización y documentación automáticas integradas. diff --git a/docs/es/docs/deployment/index.md b/docs/es/docs/deployment/index.md new file mode 100644 index 0000000000000..74b0e22f08c16 --- /dev/null +++ b/docs/es/docs/deployment/index.md @@ -0,0 +1,21 @@ +# Despliegue - Introducción + +Desplegar una aplicación hecha con **FastAPI** es relativamente fácil. + +## ¿Qué significa desplegar una aplicación? + +**Desplegar** una aplicación significa realizar una serie de pasos para hacerla **disponible para los usuarios**. + +Para una **API web**, normalmente implica ponerla en una **máquina remota**, con un **programa de servidor** que proporcione un buen rendimiento, estabilidad, etc, para que sus **usuarios** puedan **acceder** a la aplicación de manera eficiente y sin interrupciones o problemas. + +Esto difiere en las fases de **desarrollo**, donde estás constantemente cambiando el código, rompiéndolo y arreglándolo, deteniendo y reiniciando el servidor de desarrollo, etc. + +## Estrategias de despliegue + +Existen varias formas de hacerlo dependiendo de tu caso de uso específico y las herramientas que uses. + +Puedes **desplegar un servidor** tú mismo usando un conjunto de herramientas, puedes usar **servicios en la nube** que haga parte del trabajo por ti, o usar otras posibles opciones. + +Te enseñaré algunos de los conceptos principales que debes tener en cuenta al desplegar aplicaciones hechas con **FastAPI** (aunque la mayoría de estos conceptos aplican para cualquier otro tipo de aplicación web). + +Podrás ver más detalles para tener en cuenta y algunas de las técnicas para hacerlo en las próximas secciones.✨ diff --git a/docs/es/docs/deployment/versions.md b/docs/es/docs/deployment/versions.md new file mode 100644 index 0000000000000..d8719d6bd904c --- /dev/null +++ b/docs/es/docs/deployment/versions.md @@ -0,0 +1,87 @@ +# Acerca de las versiones de FastAPI + +**FastAPI** está siendo utilizado en producción en muchas aplicaciones y sistemas. La cobertura de los tests se mantiene al 100%. Sin embargo, su desarrollo sigue siendo rápido. + +Se agregan nuevas características frecuentemente, se corrigen errores continuamente y el código está constantemente mejorando. + +Por eso las versiones actuales siguen siendo `0.x.x`, esto significa que cada versión puede potencialmente tener *breaking changes*. Las versiones siguen las convenciones de *Semantic Versioning*. + +Puedes crear aplicaciones listas para producción con **FastAPI** ahora mismo (y probablemente lo has estado haciendo por algún tiempo), solo tienes que asegurarte de usar la versión que funciona correctamente con el resto de tu código. + +## Fijar la versión de `fastapi` + +Lo primero que debes hacer en tu proyecto es "fijar" la última versión específica de **FastAPI** que sabes que funciona bien con tu aplicación. + +Por ejemplo, digamos que estás usando la versión `0.45.0` en tu aplicación. + +Si usas el archivo `requirements.txt` puedes especificar la versión con: + +```txt +fastapi==0.45.0 +``` + +esto significa que usarás específicamente la versión `0.45.0`. + +También puedes fijar las versiones de esta forma: + +```txt +fastapi>=0.45.0,<0.46.0 +``` + +esto significa que usarás la versión `0.45.0` o superiores, pero menores a la versión `0.46.0`, por ejemplo, la versión `0.45.2` sería aceptada. + +Si usas cualquier otra herramienta para manejar tus instalaciones, como Poetry, Pipenv, u otras, todas tienen una forma que puedes usar para definir versiones específicas para tus paquetes. + +## Versiones disponibles + +Puedes ver las versiones disponibles (por ejemplo, para revisar cuál es la actual) en las [Release Notes](../release-notes.md){.internal-link target=_blank}. + +## Acerca de las versiones + +Siguiendo las convenciones de *Semantic Versioning*, cualquier versión por debajo de `1.0.0` puede potencialmente tener *breaking changes*. + +FastAPI también sigue la convención de que cualquier cambio hecho en una "PATCH" version es para solucionar errores y *non-breaking changes*. + +!!! tip + El "PATCH" es el último número, por ejemplo, en `0.2.3`, la PATCH version es `3`. + +Entonces, deberías fijar la versión así: + +```txt +fastapi>=0.45.0,<0.46.0 +``` + +En versiones "MINOR" son añadidas nuevas características y posibles breaking changes. + +!!! tip + La versión "MINOR" es el número en el medio, por ejemplo, en `0.2.3`, la "MINOR" version es `2`. + +## Actualizando las versiones de FastAPI + +Para esto es recomendable primero añadir tests a tu aplicación. + +Con **FastAPI** es muy fácil (gracias a Starlette), revisa la documentación [Testing](../tutorial/testing.md){.internal-link target=_blank} + +Luego de tener los tests, puedes actualizar la versión de **FastAPI** a una más reciente y asegurarte de que tu código funciona correctamente ejecutando los tests. + +Si todo funciona correctamente, o haces los cambios necesarios para que esto suceda, y todos tus tests pasan, entonces puedes fijar tu versión de `fastapi` a la más reciente. + +## Acerca de Starlette + +No deberías fijar la versión de `starlette`. + +Diferentes versiones de **FastAPI** pueden usar una versión específica de Starlette. + +Entonces, puedes dejar que **FastAPI** se asegure por sí mismo de qué versión de Starlette usar. + +## Acerca de Pydantic + +Pydantic incluye los tests para **FastAPI** dentro de sus propios tests, esto significa que las versiones de Pydantic (superiores a `1.0.0`) son compatibles con FastAPI. + +Puedes fijar Pydantic a cualquier versión superior a `1.0.0` e inferior a `2.0.0` que funcione para ti. + +Por ejemplo: + +```txt +pydantic>=1.2.0,<2.0.0 +``` diff --git a/docs/es/docs/external-links.md b/docs/es/docs/external-links.md new file mode 100644 index 0000000000000..cfbdd68a6a78e --- /dev/null +++ b/docs/es/docs/external-links.md @@ -0,0 +1,33 @@ +# Enlaces Externos y Artículos + +**FastAPI** tiene una gran comunidad en constante crecimiento. + +Hay muchas publicaciones, artículos, herramientas y proyectos relacionados con **FastAPI**. + +Aquí hay una lista incompleta de algunos de ellos. + +!!! tip "Consejo" + Si tienes un artículo, proyecto, herramienta o cualquier cosa relacionada con **FastAPI** que aún no aparece aquí, crea un Pull Request agregándolo. + +{% for section_name, section_content in external_links.items() %} + +## {{ section_name }} + +{% for lang_name, lang_content in section_content.items() %} + +### {{ lang_name }} + +{% for item in lang_content %} + +* {{ item.title }} by {{ item.author }}. + +{% endfor %} +{% endfor %} +{% endfor %} + +## Projects + +Últimos proyectos de GitHub con el tema `fastapi`: + +
+
diff --git a/docs/es/docs/features.md b/docs/es/docs/features.md index 5d6b6509a715f..7623d8eb18628 100644 --- a/docs/es/docs/features.md +++ b/docs/es/docs/features.md @@ -1,3 +1,8 @@ +--- +hide: + - navigation +--- + # Características ## Características de FastAPI @@ -13,7 +18,7 @@ ### Documentación automática -Documentación interactiva de la API e interfaces web de exploración. Hay múltiples opciones, dos incluídas por defecto, porque el framework está basado en OpenAPI. +Documentación interactiva de la API e interfaces web de exploración. Hay múltiples opciones, dos incluidas por defecto, porque el framework está basado en OpenAPI. * Swagger UI, con exploración interactiva, llama y prueba tu API directamente desde tu navegador. @@ -25,7 +30,7 @@ Documentación interactiva de la API e interfaces web de exploración. Hay múlt ### Simplemente Python moderno -Todo está basado en las declaraciones de tipo de **Python 3.6** estándar (gracias a Pydantic). No necesitas aprender una sintáxis nueva, solo Python moderno. +Todo está basado en las declaraciones de tipo de **Python 3.8** estándar (gracias a Pydantic). No necesitas aprender una sintaxis nueva, solo Python moderno. Si necesitas un repaso de 2 minutos de cómo usar los tipos de Python (así no uses FastAPI) prueba el tutorial corto: [Python Types](python-types.md){.internal-link target=_blank}. @@ -72,9 +77,9 @@ my_second_user: User = User(**second_user_data) El framework fue diseñado en su totalidad para ser fácil e intuitivo de usar. Todas las decisiones fueron probadas en múltiples editores antes de comenzar el desarrollo para asegurar la mejor experiencia de desarrollo. -En la última encuesta a desarrolladores de Python fue claro que la característica más usada es el "autocompletado". +En la última encuesta a desarrolladores de Python fue claro que la característica más usada es el "auto-completado". -El framework **FastAPI** está creado para satisfacer eso. El autocompletado funciona en todas partes. +El framework **FastAPI** está creado para satisfacer eso. El auto-completado funciona en todas partes. No vas a tener que volver a la documentación seguido. @@ -140,13 +145,13 @@ FastAPI incluye un sistema de instances de clases que tu defines, el auto-completado, el linting, mypy y tu intuición deberían funcionar bien con tus datos validados. -* **Rápido**: - * En benchmarks Pydantic es más rápido que todas las otras libraries probadas. * Valida **estructuras complejas**: * Usa modelos jerárquicos de modelos de Pydantic, `typing` de Python, `List` y `Dict`, etc. * Los validadores también permiten que se definan fácil y claramente schemas complejos de datos. Estos son chequeados y documentados como JSON Schema. diff --git a/docs/es/docs/help/index.md b/docs/es/docs/help/index.md new file mode 100644 index 0000000000000..f6ce35e9c1b46 --- /dev/null +++ b/docs/es/docs/help/index.md @@ -0,0 +1,3 @@ +# Ayuda + +Ayuda y recibe ayuda, contribuye, involúcrate. 🤝 diff --git a/docs/es/docs/index.md b/docs/es/docs/index.md index 5b75880c02157..b3d9c8bf220b5 100644 --- a/docs/es/docs/index.md +++ b/docs/es/docs/index.md @@ -23,7 +23,7 @@ **Código Fuente**: https://github.com/tiangolo/fastapi --- -FastAPI es un web framework moderno y rápido (de alto rendimiento) para construir APIs con Python 3.6+ basado en las anotaciones de tipos estándar de Python. +FastAPI es un web framework moderno y rápido (de alto rendimiento) para construir APIs con Python 3.8+ basado en las anotaciones de tipos estándar de Python. Sus características principales son: @@ -37,7 +37,7 @@ Sus características principales son: * **Robusto**: Crea código listo para producción con documentación automática interactiva. * **Basado en estándares**: Basado y totalmente compatible con los estándares abiertos para APIs: OpenAPI (conocido previamente como Swagger) y JSON Schema. -* Esta estimación está basada en pruebas con un equipo de desarrollo interno contruyendo aplicaciones listas para producción. +* Esta estimación está basada en pruebas con un equipo de desarrollo interno construyendo aplicaciones listas para producción. ## Sponsors @@ -106,12 +106,12 @@ Si estás construyendo un app de Starlette para las partes web. -* Pydantic para las partes de datos. +* Pydantic para las partes de datos. ## Instalación @@ -295,11 +295,11 @@ Ahora ve a httpx - Requerido si quieres usar el `TestClient`. * jinja2 - Requerido si quieres usar la configuración por defecto de templates. -* python-multipart - Requerido si quieres dar soporte a "parsing" de formularios, con `request.form()`. +* python-multipart - Requerido si quieres dar soporte a "parsing" de formularios, con `request.form()`. * itsdangerous - Requerido para dar soporte a `SessionMiddleware`. * pyyaml - Requerido para dar soporte al `SchemaGenerator` de Starlette (probablemente no lo necesites con FastAPI). * graphene - Requerido para dar soporte a `GraphQLApp`. diff --git a/docs/es/docs/learn/index.md b/docs/es/docs/learn/index.md new file mode 100644 index 0000000000000..b8d26cf34fdab --- /dev/null +++ b/docs/es/docs/learn/index.md @@ -0,0 +1,5 @@ +# Aprender + +Aquí están las secciones introductorias y los tutoriales para aprender **FastAPI**. + +Podrías considerar esto como un **libro**, un **curso**, la forma **oficial** y recomendada de aprender FastAPI. 😎 diff --git a/docs/es/docs/newsletter.md b/docs/es/docs/newsletter.md new file mode 100644 index 0000000000000..f4dcfe155c380 --- /dev/null +++ b/docs/es/docs/newsletter.md @@ -0,0 +1,5 @@ +# Boletín de Noticias de FastAPI y amigos + + + + diff --git a/docs/es/docs/python-types.md b/docs/es/docs/python-types.md index e9fd61629372e..89edbb31e737e 100644 --- a/docs/es/docs/python-types.md +++ b/docs/es/docs/python-types.md @@ -2,7 +2,7 @@ **Python 3.6+** tiene soporte para "type hints" opcionales. -Estos **type hints** son una nueva sintáxis, desde Python 3.6+, que permite declarar el tipo de una variable. +Estos **type hints** son una nueva sintaxis, desde Python 3.6+, que permite declarar el tipo de una variable. Usando las declaraciones de tipos para tus variables, los editores y otras herramientas pueden proveerte un soporte mejor. @@ -33,7 +33,7 @@ La función hace lo siguiente: * Toma un `first_name` y un `last_name`. * Convierte la primera letra de cada uno en una letra mayúscula con `title()`. -* Las concatena con un espacio en la mitad. +* Las concatena con un espacio en la mitad. ```Python hl_lines="2" {!../../../docs_src/python_types/tutorial001.py!} @@ -51,9 +51,9 @@ Pero, luego tienes que llamar "ese método que convierte la primera letra en una Era `upper`? O era `uppercase`? `first_uppercase`? `capitalize`? -Luego lo intentas con el viejo amigo de los programadores, el autocompletado del editor. +Luego lo intentas con el viejo amigo de los programadores, el auto-completado del editor. -Escribes el primer parámetro de la función `first_name`, luego un punto (`.`) y luego presionas `Ctrl+Space` para iniciar el autocompletado. +Escribes el primer parámetro de la función `first_name`, luego un punto (`.`) y luego presionas `Ctrl+Space` para iniciar el auto-completado. Tristemente, no obtienes nada útil: @@ -97,7 +97,7 @@ Añadir los type hints normalmente no cambia lo que sucedería si ellos no estuv Pero ahora imagina que nuevamente estás creando la función, pero con los type hints. -En el mismo punto intentas iniciar el autocompletado con `Ctrl+Space` y ves: +En el mismo punto intentas iniciar el auto-completado con `Ctrl+Space` y ves: @@ -113,7 +113,7 @@ Mira esta función que ya tiene type hints: {!../../../docs_src/python_types/tutorial003.py!} ``` -Como el editor conoce el tipo de las variables no solo obtienes autocompletado, si no que también obtienes chequeo de errores: +Como el editor conoce el tipo de las variables no solo obtienes auto-completado, si no que también obtienes chequeo de errores: @@ -162,7 +162,7 @@ De `typing`, importa `List` (con una `L` mayúscula): {!../../../docs_src/python_types/tutorial006.py!} ``` -Declara la variable con la misma sintáxis de los dos puntos (`:`). +Declara la variable con la misma sintaxis de los dos puntos (`:`). Pon `List` como el tipo. @@ -176,7 +176,7 @@ Esto significa: la variable `items` es una `list` y cada uno de los ítems en es Con esta declaración tu editor puede proveerte soporte inclusive mientras está procesando ítems de la lista. -Sin tipos el autocompletado en este tipo de estructura es casi imposible de lograr: +Sin tipos el auto-completado en este tipo de estructura es casi imposible de lograr: @@ -237,7 +237,7 @@ Una vez más tendrás todo el soporte del editor: ## Modelos de Pydantic -Pydantic es una library de Python para llevar a cabo validación de datos. +Pydantic es una library de Python para llevar a cabo validación de datos. Tú declaras la "forma" de los datos mediante clases con atributos. @@ -254,7 +254,7 @@ Tomado de la documentación oficial de Pydantic: ``` !!! info "Información" - Para aprender más sobre Pydantic mira su documentación. + Para aprender más sobre Pydantic mira su documentación. **FastAPI** está todo basado en Pydantic. diff --git a/docs/es/docs/resources/index.md b/docs/es/docs/resources/index.md new file mode 100644 index 0000000000000..92898d319e6da --- /dev/null +++ b/docs/es/docs/resources/index.md @@ -0,0 +1,3 @@ +# Recursos + +Recursos adicionales, enlaces externos, artículos y más. ✈️ diff --git a/docs/es/docs/tutorial/first-steps.md b/docs/es/docs/tutorial/first-steps.md index efa61f9944601..2cb7e63084878 100644 --- a/docs/es/docs/tutorial/first-steps.md +++ b/docs/es/docs/tutorial/first-steps.md @@ -303,7 +303,7 @@ En este caso es una función `async`. --- -También podrías definirla como una función normal, en vez de `async def`: +También podrías definirla como una función estándar en lugar de `async def`: ```Python hl_lines="7" {!../../../docs_src/first_steps/tutorial003.py!} diff --git a/docs/es/docs/tutorial/index.md b/docs/es/docs/tutorial/index.md index 1cff8b4e3e150..f0dff02b426ed 100644 --- a/docs/es/docs/tutorial/index.md +++ b/docs/es/docs/tutorial/index.md @@ -28,7 +28,7 @@ $ uvicorn main:app --reload Se **RECOMIENDA** que escribas o copies el código, lo edites y lo ejecutes localmente. -Usarlo en tu editor de código es lo que realmente te muestra los beneficios de FastAPI, al ver la poca cantidad de código que tienes que escribir, todas las verificaciones de tipo, autocompletado, etc. +Usarlo en tu editor de código es lo que realmente te muestra los beneficios de FastAPI, al ver la poca cantidad de código que tienes que escribir, todas las verificaciones de tipo, auto-completado, etc. --- diff --git a/docs/es/docs/tutorial/path-params.md b/docs/es/docs/tutorial/path-params.md index 6432de1cdfe9b..7faa92f51c91b 100644 --- a/docs/es/docs/tutorial/path-params.md +++ b/docs/es/docs/tutorial/path-params.md @@ -25,7 +25,7 @@ Puedes declarar el tipo de un parámetro de path en la función usando las anota En este caso, `item_id` es declarado como un `int`. !!! check "Revisa" - Esto te dará soporte en el editor dentro de tu función, con chequeos de errores, autocompletado, etc. + Esto te dará soporte en el editor dentro de tu función, con chequeo de errores, auto-completado, etc. ## Conversión de datos @@ -93,7 +93,7 @@ De la misma manera hay muchas herramientas compatibles. Incluyendo herramientas ## Pydantic -Toda la validación de datos es realizada tras bastidores por Pydantic, así que obtienes todos sus beneficios. Así sabes que estás en buenas manos. +Toda la validación de datos es realizada tras bastidores por Pydantic, así que obtienes todos sus beneficios. Así sabes que estás en buenas manos. Puedes usar las mismas declaraciones de tipos con `str`, `float`, `bool` y otros tipos de datos más complejos. @@ -135,7 +135,7 @@ Luego crea atributos de clase con valores fijos, que serán los valores disponib Las Enumerations (o enums) están disponibles en Python desde la versión 3.4. !!! tip "Consejo" - Si lo estás dudando, "AlexNet", "ResNet", y "LeNet" son solo nombres de modelos de Machine Learning. + Si lo estás dudando, "AlexNet", "ResNet", y "LeNet" son solo nombres de modelos de Machine Learning. ### Declara un *parámetro de path* @@ -234,7 +234,7 @@ Entonces lo puedes usar con: Con **FastAPI**, usando declaraciones de tipo de Python intuitivas y estándares, obtienes: -* Soporte en el editor: chequeos de errores, auto-completado, etc. +* Soporte en el editor: chequeo de errores, auto-completado, etc. * "Parsing" de datos * Validación de datos * Anotación de la API y documentación automática diff --git a/docs/fa/docs/advanced/sub-applications.md b/docs/fa/docs/advanced/sub-applications.md new file mode 100644 index 0000000000000..f3a948414a155 --- /dev/null +++ b/docs/fa/docs/advanced/sub-applications.md @@ -0,0 +1,72 @@ +# زیر برنامه ها - اتصال + +اگر نیاز دارید که دو برنامه مستقل FastAPI، با OpenAPI مستقل و رابط‌های کاربری اسناد خود داشته باشید، می‌توانید یک برنامه +اصلی داشته باشید و یک (یا چند) زیر برنامه را به آن متصل کنید. + +## اتصال (mount) به یک برنامه **FastAPI** + +کلمه "Mounting" به معنای افزودن یک برنامه کاملاً مستقل در یک مسیر خاص است، که پس از آن مدیریت همه چیز در آن مسیر، با path operations (عملیات های مسیر) اعلام شده در آن زیر برنامه می باشد. + +### برنامه سطح بالا + +ابتدا برنامه اصلی سطح بالا، **FastAPI** و path operations آن را ایجاد کنید: + + +```Python hl_lines="3 6-8" +{!../../../docs_src/sub_applications/tutorial001.py!} +``` + +### زیر برنامه + +سپس، زیر برنامه خود و path operations آن را ایجاد کنید. + +این زیر برنامه فقط یکی دیگر از برنامه های استاندارد FastAPI است، اما این برنامه ای است که متصل می شود: + +```Python hl_lines="11 14-16" +{!../../../docs_src/sub_applications/tutorial001.py!} +``` + +### اتصال زیر برنامه + +در برنامه سطح بالا `app` اتصال زیر برنامه `subapi` در این نمونه `/subapi` در مسیر قرار میدهد و میشود: + +```Python hl_lines="11 19" +{!../../../docs_src/sub_applications/tutorial001.py!} +``` + +### اسناد API خودکار را بررسی کنید + +برنامه را با استفاده از ‘uvicorn‘ اجرا کنید، اگر فایل شما ‘main.py‘ نام دارد، دستور زیر را وارد کنید: +
+ +```console +$ uvicorn main:app --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +صفحه مستندات را در آدرس http://127.0.0.1:8000/docs باز کنید. + +اسناد API خودکار برنامه اصلی را مشاهده خواهید کرد که فقط شامل path operations خود می شود: + + + +و سپس اسناد زیر برنامه را در آدرس http://127.0.0.1:8000/subapi/docs. باز کنید. + +اسناد API خودکار برای زیر برنامه را خواهید دید، که فقط شامل path operations خود می شود، همه در زیر مسیر `/subapi` قرار دارند: + + + +اگر سعی کنید با هر یک از این دو رابط کاربری تعامل داشته باشید، آنها به درستی کار می کنند، زیرا مرورگر می تواند با هر یک از برنامه ها یا زیر برنامه های خاص صحبت کند. + +### جرئیات فنی : `root_path` + +هنگامی که یک زیر برنامه را همانطور که در بالا توضیح داده شد متصل می کنید, FastAPI با استفاده از مکانیزمی از مشخصات ASGI به نام `root_path` ارتباط مسیر mount را برای زیر برنامه انجام می دهد. + +به این ترتیب، زیر برنامه می داند که از آن پیشوند مسیر برای رابط کاربری اسناد (docs UI) استفاده کند. + +و زیر برنامه ها نیز می تواند زیر برنامه های متصل شده خود را داشته باشد و همه چیز به درستی کار کند، زیرا FastAPI تمام این مسیرهای `root_path` را به طور خودکار مدیریت می کند. + +در بخش [پشت پراکسی](./behind-a-proxy.md){.internal-link target=_blank}. درباره `root_path` و نحوه استفاده درست از آن بیشتر خواهید آموخت. diff --git a/docs/fa/docs/features.md b/docs/fa/docs/features.md new file mode 100644 index 0000000000000..58c34b7fccdcd --- /dev/null +++ b/docs/fa/docs/features.md @@ -0,0 +1,206 @@ +# ویژگی ها + +## ویژگی های FastAPI + +**FastAPI** موارد زیر را به شما ارائه میدهد: + +### برپایه استاندارد های باز + +* OpenAPI برای ساخت API, شامل مشخص سازی path operation ها, پارامترها, body request ها, امنیت و غیره. +* مستندسازی خودکار data model با JSON Schema (همانطور که OpenAPI خود نیز مبتنی بر JSON Schema است). +* طراحی شده بر اساس استاندارد هایی که پس از یک مطالعه دقیق بدست آمده اند بجای طرحی ناپخته و بدون فکر. +* همچنین به شما اجازه میدهد تا از تولید خودکار client code در بسیاری از زبان ها استفاده کنید. + +### مستندات خودکار + +مستندات API تعاملی و ایجاد رابط کاربری وب. از آنجایی که این فریم ورک برپایه OpenAPI میباشد، آپشن های متعددی وجود دارد که ۲ مورد بصورت پیش فرض گنجانده شده اند. + +* Swagger UI، با کاوش تعاملی، API خود را مستقیما از طریق مرورگر صدازده و تست کنید. + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) + +* مستندات API جایگزین با ReDoc. + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) + +### فقط پایتون مدرن + +همه اینها برپایه type declaration های **پایتون ۳.۶** استاندارد (به لطف Pydantic) میباشند. سینتکس جدیدی درکار نیست. تنها پایتون مدرن استاندارد. + +اگر به یک یادآوری ۲ دقیقه ای در مورد نحوه استفاده از تایپ های پایتون دارید (حتی اگر از FastAPI استفاده نمیکنید) این آموزش کوتاه را بررسی کنید: [Python Types](python-types.md){.internal-link target=\_blank}. + +شما پایتون استاندارد را با استفاده از تایپ ها مینویسید: + +```Python +from datetime import date + +from pydantic import BaseModel + +# Declare a variable as a str +# and get editor support inside the function +def main(user_id: str): + return user_id + + +# A Pydantic model +class User(BaseModel): + id: int + name: str + joined: date +``` + +که سپس میتوان به این شکل از آن استفاده کرد: + +```Python +my_user: User = User(id=3, name="John Doe", joined="2018-07-19") + +second_user_data = { + "id": 4, + "name": "Mary", + "joined": "2018-11-30", +} + +my_second_user: User = User(**second_user_data) +``` + +!!! info + `**second_user_data` یعنی: + + کلید ها و مقادیر دیکشنری `second_user_data` را مستقیما به عنوان ارگومان های key-value بفرست، که معادل است با : `User(id=4, name="Mary", joined="2018-11-30")` + +### پشتیبانی ویرایشگر + +تمام فریم ورک به گونه ای طراحی شده که استفاده از آن آسان و شهودی باشد، تمام تصمیمات حتی قبل از شروع توسعه بر روی چندین ویرایشگر آزمایش شده اند، تا از بهترین تجربه توسعه اطمینان حاصل شود. + +در آخرین نظرسنجی توسعه دهندگان پایتون کاملا مشخص بود که بیشترین ویژگی مورد استفاده از "تکمیل خودکار" است. + +تمام فریم ورک **FastAPI** برپایه ای برای براورده کردن این نیاز نیز ایجاد گشته است. تکمیل خودکار در همه جا کار میکند. + +شما به ندرت نیاز به بازگشت به مستندات را خواهید داشت. + +ببینید که چگونه ویرایشگر شما ممکن است به شما کمک کند: + +* در Visual Studio Code: + +![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) + +* در PyCharm: + +![editor support](https://fastapi.tiangolo.com/img/pycharm-completion.png) + +شما پیشنهاد های تکمیل خودکاری را خواهید گرفت که حتی ممکن است قبلا آن را غیرممکن تصور میکردید. به عنوان مثال کلید `price` در داخل بدنه JSON (که میتوانست تودرتو نیز باشد) که از یک درخواست آمده است. + +دیگر خبری از تایپ کلید اشتباهی، برگشتن به مستندات یا پایین بالا رفتن برای فهمیدن اینکه شما از `username` یا `user_name` استفاده کرده اید نیست. + +### مختصر + +FastAPI **پیش فرض** های معقولی برای همه چیز دارد، با قابلیت تنظیمات اختیاری در همه جا. تمام پارامترها را میتوانید برای انجام انچه نیاز دارید و برای تعریف API مورد نیاز خود به خوبی تنظیم کنید. + +اما به طور پیش فرض، همه چیز **کار میکند**. + +### اعتبارسنجی + +* اعتبارسنجی برای بیشتر (یا همه؟) **data type** های پایتون، شامل: + + * JSON objects (`dict`) + * آرایه های (‍‍‍‍`list`) JSON با قابلیت مشخص سازی تایپ ایتم های درون لیست. + * فیلد های رشته (`str`)، به همراه مشخص سازی حداقل و حداکثر طول رشته. + * اعداد (‍‍`int`,`float`) با حداقل و حداکثر مقدار و غیره. + +* اعتبارسنجی برای تایپ های عجیب تر، مثل: + * URL. + * Email. + * UUID. + * و غیره. + +تمام اعتبارسنجی ها توسط کتابخانه اثبات شده و قدرتمند **Pydantic** انجام میشود. + +### امنیت و احراز هویت + +امنیت و احرازهویت بدون هیچگونه ارتباط و مصالحه ای با پایگاه های داده یا مدل های داده ایجاد شده اند. + +تمام طرح های امنیتی در OpenAPI تعریف شده اند، از جمله: + +* . +* **OAuth2** (همچنین با **JWT tokens**). آموزش را در [OAuth2 with JWT](tutorial/security/oauth2-jwt.md){.internal-link target=\_blank} مشاهده کنید. +* کلید های API: + * Headers + * Query parameters + * Cookies، و غیره. + +به علاوه تمام ویژگی های امنیتی از **Statlette** (شامل **session cookies**) + +همه اینها به عنوان ابزارها و اجزای قابل استفاده ای ساخته شده اند که به راحتی با سیستم های شما، مخازن داده، پایگاه های داده رابطه ای و NoSQL و غیره ادغام میشوند. + +### Dependency Injection + +FastAPI شامل یک سیستم Dependency Injection بسیار آسان اما بسیار قدرتمند است. + +* حتی وابستگی ها نیز میتوانند وابستگی هایی داشته باشند و یک سلسله مراتب یا **"گرافی" از وابستگی ها** ایجاد کنند. + +* همه چیز توسط فریم ورک **به طور خودکار اداره میشود** + +* همه وابستگی ها میتوانند به داده های request ها نیاز داشته باشند و مستندات خودکار و محدودیت های path operation را **افزایش** دهند. + +* با قابلیت **اعتبارسنجی خودکار** حتی برای path operation parameter های تعریف شده در وابستگی ها. + +* پشتیبانی از سیستم های پیچیده احرازهویت کاربر، **اتصالات پایگاه داده** و غیره. + +* بدون هیچ ارتباطی با دیتابیس ها، فرانت اند و غیره. اما ادغام آسان و راحت با همه آنها. + +### پلاگین های نامحدود + +یا به عبارت دیگر، هیچ نیازی به آنها نیست، کد موردنیاز خود را وارد و استفاده کنید. + +هر یکپارچه سازی به گونه ای طراحی شده است که استفاده از آن بسیار ساده باشد (با وابستگی ها) که میتوانید با استفاده از همان ساختار و روشی که برای _path operation_ های خود استفاده کرده اید تنها در ۲ خط کد "پلاگین" برنامه خودتان را ایجاد کنید. + +### تست شده + +* 100% پوشش تست. + +* 100% کد بر اساس type annotate ها. + +* استفاده شده در اپلیکیشن های تولید + +## ویژگی های Starlette + +**FastAPI** کاملا (و براساس) با Starlette سازگار است. بنابراین، هرکد اضافی Starlette که دارید، نیز کار خواهد کرد. + +‍‍`FastAPI` در واقع یک زیرکلاس از `Starlette` است. بنابراین اگر از قبل Starlette را میشناسید یا با آن کار کرده اید، بیشتر قابلیت ها به همین روش کار خواهد کرد. + +با **FastAPI** شما تمام ویژگی های **Starlette** را خواهید داشت (زیرا FastAPI یک نسخه و نمونه به تمام معنا از Starlette است): + +* عملکرد به طورجدی چشمگیر. این یکی از سریعترین فریم ورک های موجود در پایتون است که همتراز با **نود جی اس** و **گو** است. +* پشتیبانی از **WebSocket**. +* تسک های درجریان در پس زمینه. +* رویداد های راه اندازی و متوفق شدن. +* تست کلاینت ساخته شده به روی HTTPX. +* **CORS**, GZip, فایل های استاتیک, پاسخ های جریانی. +* پشتیبانی از **نشست ها و کوکی ها**. +* 100% پوشش با تست. +* 100% کد براساس type annotate ها. + +## ویژگی های Pydantic + +**FastAPI** کاملا (و براساس) با Pydantic سازگار است. بنابراین هرکد Pydantic اضافی که داشته باشید، نیز کار خواهد کرد. + +از جمله کتابخانه های خارجی نیز مبتنی بر Pydantic میتوان به ORM و ODM ها برای دیتابیس ها اشاره کرد. + +این همچنین به این معناست که در خیلی از موارد میتوانید همان ابجکتی که از request میگیرید را **مستقیما به دیتابیس** بفرستید زیرا همه چیز به طور خودکار تأیید میشود. + +همین امر برعکس نیز صدق می‌کند، در بسیاری از موارد شما می‌توانید ابجکتی را که از پایگاه داده دریافت می‌کنید را **مستقیماً به کاربر** ارسال کنید. + +با FastAPI شما تمام ویژگی های Pydantic را دراختیار دارید (زیرا FastAPI برای تمام بخش مدیریت دیتا بر اساس Pydantic عمل میکند): + +* **خبری از گیج شدن نیست**: + * هیچ زبان خردی برای یادگیری تعریف طرحواره های جدید وجود ندارد. + * اگر تایپ های پایتون را میشناسید، نحوه استفاده از Pydantic را نیز میدانید. +* به خوبی با **IDE/linter/مغز** شما عمل میکند: + * به این دلیل که ساختار داده Pydantic فقط نمونه هایی از کلاس هایی هستند که شما تعریف میکنید، تکمیل خودکار، mypy، linting و مشاهده شما باید به درستی با داده های معتبر شما کار کنند. +* اعتبار سنجی **ساختارهای پیچیده**: + * استفاده از مدل های سلسله مراتبی Pydantic, `List` و `Dict` کتابخانه `typing` پایتون و غیره. + * و اعتبارسنج ها اجازه میدهند که طرحواره های داده پیچیده به طور واضح و آسان تعریف، بررسی و بر پایه JSON مستند شوند. + * شما میتوانید ابجکت های عمیقا تودرتو JSON را که همگی تایید شده و annotated شده اند را داشته باشید. +* **قابل توسعه**: + * Pydantic اجازه میدهد تا data type های سفارشی تعریف شوند یا میتوانید اعتبارسنجی را با روش هایی به روی مدل ها با validator decorator گسترش دهید. +* 100% پوشش با تست. diff --git a/docs/fa/docs/index.md b/docs/fa/docs/index.md index 2480843891c5e..e5231ec8d5ed9 100644 --- a/docs/fa/docs/index.md +++ b/docs/fa/docs/index.md @@ -32,9 +32,9 @@ FastAPI یک وب فریم‌ورک مدرن و سریع (با کارایی با * **سرعت**: کارایی بسیار بالا و قابل مقایسه با **NodeJS** و **Go** (با تشکر از Starlette و Pydantic). [یکی از سریع‌ترین فریم‌ورک‌های پایتونی موجود](#performance). -* **کدنویسی سریع**: افزایش ۲۰۰ تا ۳۰۰ درصدی سرعت توسعه فابلیت‌های جدید. * +* **کدنویسی سریع**: افزایش ۲۰۰ تا ۳۰۰ درصدی سرعت توسعه قابلیت‌های جدید. * * **باگ کمتر**: کاهش ۴۰ درصدی خطاهای انسانی (برنامه‌نویسی). * -* **غریزی**: پشتیبانی فوق‌العاده در محیط‌های توسعه یکپارچه (IDE). تکمیل در همه بخش‌های کد. کاهش زمان رفع باگ. +* **هوشمندانه**: پشتیبانی فوق‌العاده در محیط‌های توسعه یکپارچه (IDE). تکمیل در همه بخش‌های کد. کاهش زمان رفع باگ. * **آسان**: طراحی شده برای یادگیری و استفاده آسان. کاهش زمان مورد نیاز برای مراجعه به مستندات. * **کوچک**: کاهش تکرار در کد. چندین قابلیت برای هر پارامتر (منظور پارامترهای ورودی تابع هندلر می‌باشد، به بخش خلاصه در همین صفحه مراجعه شود). باگ کمتر. * **استوار**: ایجاد کدی آماده برای استفاده در محیط پروداکشن و تولید خودکار مستندات تعاملی @@ -111,7 +111,7 @@ FastAPI یک وب فریم‌ورک مدرن و سریع (با کارایی با FastAPI مبتنی بر ابزارهای قدرتمند زیر است: * فریم‌ورک Starlette برای بخش وب. -* کتابخانه Pydantic برای بخش داده‌. +* کتابخانه Pydantic برای بخش داده‌. ## نصب @@ -140,7 +140,7 @@ $ pip install "uvicorn[standard]" ## مثال ### ایجاد کنید -* فایلی به نام `main.py` با محتوای زیر ایجاد کنید : +* فایلی به نام `main.py` با محتوای زیر ایجاد کنید: ```Python from typing import Union @@ -163,7 +163,7 @@ def read_item(item_id: int, q: Union[str, None] = None):
همچنین می‌توانید از async def... نیز استفاده کنید -اگر در کدتان از `async` / `await` استفاده می‌کنید, از `async def` برای تعریف تابع خود استفاده کنید: +اگر در کدتان از `async` / `await` استفاده می‌کنید، از `async def` برای تعریف تابع خود استفاده کنید: ```Python hl_lines="9 14" from typing import Optional @@ -211,7 +211,7 @@ INFO: Application startup complete.
درباره دستور uvicorn main:app --reload... -دستور `uvicorn main:app` شامل موارد زیر است: +دستور `uvicorn main:app` شامل موارد زیر است: * `main`: فایل `main.py` (ماژول پایتون ایجاد شده). * `app`: شیء ایجاد شده در فایل `main.py` در خط `app = FastAPI()`. @@ -232,7 +232,7 @@ INFO: Application startup complete. تا اینجا شما APIای ساختید که: * درخواست‌های HTTP به _مسیرهای_ `/` و `/items/{item_id}` را دریافت می‌کند. -* هردو _مسیر_ عملیات (یا HTTP _متد_) `GET` را پشتیبانی می‌کنند. +* هردو _مسیر_ عملیات (یا HTTP _متد_) `GET` را پشتیبانی می‌کند. * _مسیر_ `/items/{item_id}` شامل _پارامتر مسیر_ `item_id` از نوع `int` است. * _مسیر_ `/items/{item_id}` شامل _پارامتر پرسمان_ اختیاری `q` از نوع `str` است. @@ -254,7 +254,7 @@ INFO: Application startup complete. ## تغییر مثال -حال فایل `main.py` را مطابق زیر ویرایش کنید تا بتوانید بدنه یک درخواست `PUT` را دریافت کنید. +حال فایل `main.py` را مطابق زیر ویرایش کنید تا بتوانید بدنه یک درخواست `PUT` را دریافت کنید. به کمک Pydantic بدنه درخواست را با انواع استاندارد پایتون تعریف کنید. @@ -298,11 +298,11 @@ def update_item(item_id: int, item: Item): ![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) -* روی دکمه "Try it out" کلیک کنید, اکنون می‌توانید پارامترهای مورد نیاز هر API را مشخص کرده و به صورت مستقیم با آنها تعامل کنید: +* روی دکمه "Try it out" کلیک کنید، اکنون می‌توانید پارامترهای مورد نیاز هر API را مشخص کرده و به صورت مستقیم با آنها تعامل کنید: ![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png) -* سپس روی دکمه "Execute" کلیک کنید, خواهید دید که واسط کاریری با APIهای تعریف شده ارتباط برقرار کرده، پارامترهای مورد نیاز را به آن‌ها ارسال می‌کند، سپس نتایج را دریافت کرده و در صفحه نشان می‌دهد: +* سپس روی دکمه "Execute" کلیک کنید، خواهید دید که واسط کاربری با APIهای تعریف شده ارتباط برقرار کرده، پارامترهای مورد نیاز را به آن‌ها ارسال می‌کند، سپس نتایج را دریافت کرده و در صفحه نشان می‌دهد: ![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png) @@ -342,7 +342,7 @@ item: Item * تکمیل کد. * بررسی انواع داده. * اعتبارسنجی داده: - * خطاهای خودکار و مشخص در هنگام نامعتبر بودن داده + * خطاهای خودکار و مشخص در هنگام نامعتبر بودن داده. * اعتبارسنجی، حتی برای اشیاء JSON تو در تو. * تبدیل داده ورودی: که از شبکه رسیده به انواع و داد‌ه‌ پایتونی. این داده‌ شامل: * JSON. @@ -366,22 +366,22 @@ item: Item به مثال قبلی باز می‌گردیم، در این مثال **FastAPI** موارد زیر را انجام می‌دهد: -* اعتبارسنجی اینکه پارامتر `item_id` در مسیر درخواست‌های `GET` و `PUT` موجود است . +* اعتبارسنجی اینکه پارامتر `item_id` در مسیر درخواست‌های `GET` و `PUT` موجود است. * اعتبارسنجی اینکه پارامتر `item_id` در درخواست‌های `GET` و `PUT` از نوع `int` است. * اگر غیر از این موارد باشد، سرویس‌گیرنده خطای مفید و مشخصی دریافت خواهد کرد. * بررسی وجود پارامتر پرسمان اختیاری `q` (مانند `http://127.0.0.1:8000/items/foo?q=somequery`) در درخواست‌های `GET`. - * از آنجا که پارامتر `q` با `= None` مقداردهی شده است, این پارامتر اختیاری است. + * از آنجا که پارامتر `q` با `= None` مقداردهی شده است، این پارامتر اختیاری است. * اگر از مقدار اولیه `None` استفاده نکنیم، این پارامتر الزامی خواهد بود (همانند بدنه درخواست در درخواست `PUT`). -* برای درخواست‌های `PUT` به آدرس `/items/{item_id}`, بدنه درخواست باید از نوع JSON تعریف شده باشد: +* برای درخواست‌های `PUT` به آدرس `/items/{item_id}`، بدنه درخواست باید از نوع JSON تعریف شده باشد: * بررسی اینکه بدنه شامل فیلدی با نام `name` و از نوع `str` است. * بررسی اینکه بدنه شامل فیلدی با نام `price` و از نوع `float` است. - * بررسی اینکه بدنه شامل فیلدی اختیاری با نام `is_offer` است, که در صورت وجود باید از نوع `bool` باشد. + * بررسی اینکه بدنه شامل فیلدی اختیاری با نام `is_offer` است، که در صورت وجود باید از نوع `bool` باشد. * تمامی این موارد برای اشیاء JSON در هر عمقی قابل بررسی می‌باشد. * تبدیل از/به JSON به صورت خودکار. -* مستندسازی همه چیز با استفاده از OpenAPI, که می‌توان از آن برای موارد زیر استفاده کرد: +* مستندسازی همه چیز با استفاده از OpenAPI، که می‌توان از آن برای موارد زیر استفاده کرد: * سیستم مستندات تعاملی. * تولید خودکار کد سرویس‌گیرنده‌ در زبان‌های برنامه‌نویسی بیشمار. -* فراهم سازی ۲ مستند تعاملی مبتنی بر وب به صورت پیش‌فرض . +* فراهم سازی ۲ مستند تعاملی مبتنی بر وب به صورت پیش‌فرض. --- @@ -413,7 +413,7 @@ item: Item **هشدار اسپویل**: بخش آموزش - راهنمای کاربر شامل موارد زیر است: -* اعلان **پارامترهای** موجود در بخش‌های دیگر درخواست، شامل: **سرآیند‌ (هدر)ها**, **کوکی‌ها**, **فیلد‌های فرم** و **فایل‌ها**. +* اعلان **پارامترهای** موجود در بخش‌های دیگر درخواست، شامل: **سرآیند‌ (هدر)ها**، **کوکی‌ها**، **فیلد‌های فرم** و **فایل‌ها**. * چگونگی تنظیم **محدودیت‌های اعتبارسنجی** به عنوان مثال `maximum_length` یا `regex`. * سیستم **Dependency Injection** قوی و کاربردی. * امنیت و تایید هویت, شامل پشتیبانی از **OAuth2** مبتنی بر **JWT tokens** و **HTTP Basic**. @@ -428,7 +428,7 @@ item: Item ## کارایی -معیار (بنچمارک‌)های مستقل TechEmpower حاکی از آن است که برنامه‌های **FastAPI** که تحت Uvicorn اجرا می‌شود، یکی از سریع‌ترین فریم‌ورک‌های مبتنی بر پایتون, است که کمی ضعیف‌تر از Starlette و Uvicorn عمل می‌کند (فریم‌ورک و سروری که FastAPI بر اساس آنها ایجاد شده است) (*) +معیار (بنچمارک‌)های مستقل TechEmpower حاکی از آن است که برنامه‌های **FastAPI** که تحت Uvicorn اجرا می‌شود، یکی از سریع‌ترین فریم‌ورک‌های مبتنی بر پایتون، است که کمی ضعیف‌تر از Starlette و Uvicorn عمل می‌کند (فریم‌ورک و سروری که FastAPI بر اساس آنها ایجاد شده است) (*) برای درک بهتری از این موضوع به بخش بنچ‌مارک‌ها مراجعه کنید. @@ -443,9 +443,9 @@ item: Item * HTTPX - در صورتی که می‌خواهید از `TestClient` استفاده کنید. * aiofiles - در صورتی که می‌خواهید از `FileResponse` و `StaticFiles` استفاده کنید. * jinja2 - در صورتی که بخواهید از پیکربندی پیش‌فرض برای قالب‌ها استفاده کنید. -* python-multipart - در صورتی که بخواهید با استفاده از `request.form()` از قابلیت "تجزیه (parse)" فرم استفاده کنید. +* python-multipart - در صورتی که بخواهید با استفاده از `request.form()` از قابلیت "تجزیه (parse)" فرم استفاده کنید. * itsdangerous - در صورتی که بخواید از `SessionMiddleware` پشتیبانی کنید. -* pyyaml - برای پشتیبانی `SchemaGenerator` در Starlet (به احتمال زیاد برای کار کردن با FastAPI به آن نیازی پیدا نمی‌کنید.). +* pyyaml - برای پشتیبانی `SchemaGenerator` در Starlet (به احتمال زیاد برای کار کردن با FastAPI به آن نیازی پیدا نمی‌کنید). * graphene - در صورتی که از `GraphQLApp` پشتیبانی می‌کنید. * ujson - در صورتی که بخواهید از `UJSONResponse` استفاده کنید. diff --git a/docs/fa/docs/tutorial/middleware.md b/docs/fa/docs/tutorial/middleware.md new file mode 100644 index 0000000000000..c5752a4b5417a --- /dev/null +++ b/docs/fa/docs/tutorial/middleware.md @@ -0,0 +1,59 @@ +# میان‌افزار - middleware + +شما میتوانید میان‌افزارها را در **FastAPI** اضافه کنید. + +"میان‌افزار" یک تابع است که با هر درخواست(request) قبل از پردازش توسط هر path operation (عملیات مسیر) خاص کار می‌کند. همچنین با هر پاسخ(response) قبل از بازگشت آن نیز کار می‌کند. + +* هر **درخواستی (request)** که به برنامه شما می آید را می گیرد. +* سپس می تواند کاری برای آن **درخواست** انجام دهید یا هر کد مورد نیازتان را اجرا کنید. +* سپس **درخواست** را به بخش دیگری از برنامه (توسط یک path operation مشخص) برای پردازش ارسال می کند. +* سپس **پاسخ** تولید شده توسط برنامه را (توسط یک path operation مشخص) دریافت می‌کند. +* می تواند کاری با **پاسخ** انجام دهید یا هر کد مورد نیازتان را اجرا کند. +* سپس **پاسخ** را برمی گرداند. + +!!! توجه "جزئیات فنی" + در صورت وجود وابستگی هایی با `yield`، کد خروجی **پس از** اجرای میان‌‌افزار اجرا خواهد شد. + + در صورت وجود هر گونه وظایف پس زمینه (که در ادامه توضیح داده می‌شوند)، تمام میان‌افزارها *پس از آن* اجرا خواهند شد. + +## ساخت یک میان افزار + +برای ایجاد یک میان‌افزار، از دکوریتور `@app.middleware("http")` در بالای یک تابع استفاده می‌شود. + +تابع میان افزار دریافت می کند: +* `درخواست` +* تابع `call_next` که `درخواست` را به عنوان پارامتر دریافت می کند + * این تابع `درخواست` را به *path operation* مربوطه ارسال می کند. + * سپس `پاسخ` تولید شده توسط *path operation* مربوطه را برمی‌گرداند. +* شما می‌توانید سپس `پاسخ` را تغییر داده و پس از آن را برگردانید. + +```Python hl_lines="8-9 11 14" +{!../../../docs_src/middleware/tutorial001.py!} +``` + +!!! نکته به خاطر داشته باشید که هدرهای اختصاصی سفارشی را می توان با استفاده از پیشوند "X-" اضافه کرد. + + اما اگر هدرهای سفارشی دارید که می‌خواهید مرورگر کاربر بتواند آنها را ببیند، باید آنها را با استفاده از پارامتر `expose_headers` که در مستندات CORS از Starlette توضیح داده شده است، به پیکربندی CORS خود اضافه کنید. + +!!! توجه "جزئیات فنی" + شما همچنین می‌توانید از `from starlette.requests import Request` استفاده کنید. + + **FastAPI** این را به عنوان یک سهولت برای شما به عنوان برنامه‌نویس فراهم می‌کند. اما این مستقیما از Starlette به دست می‌آید. + +### قبل و بعد از `پاسخ` + +شما می‌توانید کدی را برای اجرا با `درخواست`، قبل از اینکه هر *path operation* آن را دریافت کند، اضافه کنید. + +همچنین پس از تولید `پاسخ`، قبل از بازگشت آن، می‌توانید کدی را اضافه کنید. + +به عنوان مثال، می‌توانید یک هدر سفارشی به نام `X-Process-Time` که شامل زمان پردازش درخواست و تولید پاسخ به صورت ثانیه است، اضافه کنید. + +```Python hl_lines="10 12-13" +{!../../../docs_src/middleware/tutorial001.py!} +``` + + ## سایر میان افزار + +شما می‌توانید بعداً در مورد میان‌افزارهای دیگر در [راهنمای کاربر پیشرفته: میان‌افزار پیشرفته](../advanced/middleware.md){.internal-link target=_blank} بیشتر بخوانید. + +شما در بخش بعدی در مورد این که چگونه با استفاده از یک میان‌افزار، CORS را مدیریت کنید، خواهید خواند. diff --git a/docs/fa/docs/tutorial/security/index.md b/docs/fa/docs/tutorial/security/index.md new file mode 100644 index 0000000000000..4e68ba9619b01 --- /dev/null +++ b/docs/fa/docs/tutorial/security/index.md @@ -0,0 +1,100 @@ +# امنیت + +روش‌های مختلفی برای مدیریت امنیت، تأیید هویت و اعتبارسنجی وجود دارد. + +عموماً این یک موضوع پیچیده و "سخت" است. + +در بسیاری از فریم ورک ها و سیستم‌ها، فقط مدیریت امنیت و تأیید هویت نیاز به تلاش و کد نویسی زیادی دارد (در بسیاری از موارد می‌تواند 50% یا بیشتر کل کد نوشته شده باشد). + + +فریم ورک **FastAPI** ابزارهای متعددی را در اختیار شما قرار می دهد تا به راحتی، با سرعت، به صورت استاندارد و بدون نیاز به مطالعه و یادگیری همه جزئیات امنیت، در مدیریت **امنیت** به شما کمک کند. + +اما قبل از آن، بیایید برخی از مفاهیم کوچک را بررسی کنیم. + +## عجله دارید؟ + +اگر به هیچ یک از این اصطلاحات اهمیت نمی دهید و فقط نیاز به افزودن امنیت با تأیید هویت بر اساس نام کاربری و رمز عبور دارید، *همین الان* به فصل های بعدی بروید. + +## پروتکل استاندارد OAuth2 + +پروتکل استاندارد OAuth2 یک مشخصه است که چندین روش برای مدیریت تأیید هویت و اعتبار سنجی تعریف می کند. + +این مشخصه بسیار گسترده است و چندین حالت استفاده پیچیده را پوشش می دهد. + +در آن روش هایی برای تأیید هویت با استفاده از "برنامه های شخص ثالث" وجود دارد. + +این همان چیزی است که تمامی سیستم های با "ورود با فیسبوک، گوگل، توییتر، گیت هاب" در پایین آن را استفاده می کنند. + +### پروتکل استاندارد OAuth 1 + +پروتکل استاندارد OAuth1 نیز وجود داشت که با OAuth2 خیلی متفاوت است و پیچیدگی بیشتری داشت، زیرا شامل مشخصات مستقیم در مورد رمزگذاری ارتباط بود. + +در حال حاضر OAuth1 بسیار محبوب یا استفاده شده نیست. + +پروتکل استاندارد OAuth2 روش رمزگذاری ارتباط را مشخص نمی کند، بلکه انتظار دارد که برنامه شما با HTTPS سرویس دهی شود. + +!!! نکته + در بخش در مورد **استقرار** ، شما یاد خواهید گرفت که چگونه با استفاده از Traefik و Let's Encrypt رایگان HTTPS را راه اندازی کنید. + +## استاندارد OpenID Connect + +استاندارد OpenID Connect، مشخصه‌ای دیگر است که بر پایه **OAuth2** ساخته شده است. + +این مشخصه، به گسترش OAuth2 می‌پردازد و برخی مواردی که در OAuth2 نسبتاً تردید برانگیز هستند را مشخص می‌کند تا سعی شود آن را با سایر سیستم‌ها قابل ارتباط کند. + +به عنوان مثال، ورود به سیستم گوگل از OpenID Connect استفاده می‌کند (که در زیر از OAuth2 استفاده می‌کند). + +اما ورود به سیستم فیسبوک، از OpenID Connect پشتیبانی نمی‌کند. به جای آن، نسخه خودش از OAuth2 را دارد. + +### استاندارد OpenID (نه "OpenID Connect" ) + +همچنین مشخصه "OpenID" نیز وجود داشت که سعی در حل مسائل مشابه OpenID Connect داشت، اما بر پایه OAuth2 ساخته نشده بود. + +بنابراین، یک سیستم جداگانه بود. + +اکنون این مشخصه کمتر استفاده می‌شود و محبوبیت زیادی ندارد. + +## استاندارد OpenAPI + +استاندارد OpenAPI (قبلاً با نام Swagger شناخته می‌شد) یک open specification برای ساخت APIs (که در حال حاضر جزئی از بنیاد لینوکس میباشد) است. + +فریم ورک **FastAPI** بر اساس **OpenAPI** است. + +این خاصیت، امکان دارد تا چندین رابط مستندات تعاملی خودکار(automatic interactive documentation interfaces)، تولید کد و غیره وجود داشته باشد. + +مشخصه OpenAPI روشی برای تعریف چندین "schemes" دارد. + +با استفاده از آن‌ها، شما می‌توانید از همه این ابزارهای مبتنی بر استاندارد استفاده کنید، از جمله این سیستم‌های مستندات تعاملی(interactive documentation systems). + +استاندارد OpenAPI شیوه‌های امنیتی زیر را تعریف می‌کند: + +* شیوه `apiKey`: یک کلید اختصاصی برای برنامه که می‌تواند از موارد زیر استفاده شود: + * پارامتر جستجو. + * هدر. + * کوکی. +* شیوه `http`: سیستم‌های استاندارد احراز هویت HTTP، از جمله: + * مقدار `bearer`: یک هدر `Authorization` با مقدار `Bearer` به همراه یک توکن. این از OAuth2 به ارث برده شده است. + * احراز هویت پایه HTTP. + * ویژگی HTTP Digest و غیره. +* شیوه `oauth2`: تمام روش‌های OAuth2 برای مدیریت امنیت (به نام "flows"). + * چندین از این flows برای ساخت یک ارائه‌دهنده احراز هویت OAuth 2.0 مناسب هستند (مانند گوگل، فیسبوک، توییتر، گیت‌هاب و غیره): + * ویژگی `implicit` + * ویژگی `clientCredentials` + * ویژگی `authorizationCode` + * اما یک "flow" خاص وجود دارد که می‌تواند به طور کامل برای مدیریت احراز هویت در همان برنامه به کار رود: + * بررسی `password`: چند فصل بعدی به مثال‌های این مورد خواهیم پرداخت. +* شیوه `openIdConnect`: یک روش برای تعریف نحوه کشف داده‌های احراز هویت OAuth2 به صورت خودکار. + * کشف خودکار این موضوع را که در مشخصه OpenID Connect تعریف شده است، مشخص می‌کند. + +!!! نکته + ادغام سایر ارائه‌دهندگان احراز هویت/اجازه‌دهی مانند گوگل، فیسبوک، توییتر، گیت‌هاب و غیره نیز امکان‌پذیر و نسبتاً آسان است. + + مشکل پیچیده‌ترین مسئله، ساخت یک ارائه‌دهنده احراز هویت/اجازه‌دهی مانند آن‌ها است، اما **FastAPI** ابزارهای لازم برای انجام این کار را با سهولت به شما می‌دهد و همه کارهای سنگین را برای شما انجام می‌دهد. + +## ابزارهای **FastAPI** + +فریم ورک FastAPI ابزارهایی برای هر یک از این شیوه‌های امنیتی در ماژول`fastapi.security` فراهم می‌کند که استفاده از این مکانیزم‌های امنیتی را ساده‌تر می‌کند. + +در فصل‌های بعدی، شما یاد خواهید گرفت که چگونه با استفاده از این ابزارهای ارائه شده توسط **FastAPI**، امنیت را به API خود اضافه کنید. + +همچنین، خواهید دید که چگونه به صورت خودکار در سیستم مستندات تعاملی ادغام می‌شود. diff --git a/docs/fr/docs/advanced/path-operation-advanced-configuration.md b/docs/fr/docs/advanced/path-operation-advanced-configuration.md index ace9f19f93538..7ded97ce1755a 100644 --- a/docs/fr/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/fr/docs/advanced/path-operation-advanced-configuration.md @@ -66,7 +66,7 @@ Il y a un chapitre entier ici dans la documentation à ce sujet, vous pouvez le 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. + La spécification OpenAPI appelle ces métadonnées des Objets d'opération. Il contient toutes les informations sur le *chemin* et est utilisé pour générer automatiquement la documentation. diff --git a/docs/fr/docs/alternatives.md b/docs/fr/docs/alternatives.md index ee20438c3db2f..a64edd67100cb 100644 --- a/docs/fr/docs/alternatives.md +++ b/docs/fr/docs/alternatives.md @@ -371,7 +371,7 @@ Exister. ## Utilisés par **FastAPI** -### Pydantic +### Pydantic Pydantic est une bibliothèque permettant de définir la validation, la sérialisation et la documentation des données (à l'aide de JSON Schema) en se basant sur les Python type hints. @@ -387,7 +387,7 @@ Gérer toute la validation des données, leur sérialisation et la documentation ### Starlette -Starlette est un framework/toolkit léger ASGI, qui est idéal pour construire des services asyncio performants. +Starlette est un framework/toolkit léger ASGI, qui est idéal pour construire des services asyncio performants. Il est très simple et intuitif. Il est conçu pour être facilement extensible et avoir des composants modulaires. diff --git a/docs/fr/docs/async.md b/docs/fr/docs/async.md index db88c4663ce3f..af4d6ca060e58 100644 --- a/docs/fr/docs/async.md +++ b/docs/fr/docs/async.md @@ -250,7 +250,7 @@ Par exemple : ### Concurrence + Parallélisme : Web + Machine Learning -Avec **FastAPI** vous pouvez bénéficier de la concurrence qui est très courante en developement web (c'est l'attrait principal de NodeJS). +Avec **FastAPI** vous pouvez bénéficier de la concurrence qui est très courante en développement web (c'est l'attrait principal de NodeJS). Mais vous pouvez aussi profiter du parallélisme et multiprocessing afin de gérer des charges **CPU bound** qui sont récurrentes dans les systèmes de *Machine Learning*. diff --git a/docs/fr/docs/benchmarks.md b/docs/fr/docs/benchmarks.md new file mode 100644 index 0000000000000..d33c263a213d2 --- /dev/null +++ b/docs/fr/docs/benchmarks.md @@ -0,0 +1,34 @@ +# Test de performance + +Les tests de performance de TechEmpower montrent que les applications **FastAPI** tournant sous Uvicorn comme étant l'un des frameworks Python les plus rapides disponibles, seulement inférieur à Starlette et Uvicorn (tous deux utilisés au cœur de FastAPI). (*) + +Mais en prêtant attention aux tests de performance et aux comparaisons, il faut tenir compte de ce qu'il suit. + +## Tests de performance et rapidité + +Lorsque vous vérifiez les tests de performance, il est commun de voir plusieurs outils de différents types comparés comme équivalents. + +En particulier, on voit Uvicorn, Starlette et FastAPI comparés (parmi de nombreux autres outils). + +Plus le problème résolu par un outil est simple, mieux seront les performances obtenues. Et la plupart des tests de performance ne prennent pas en compte les fonctionnalités additionnelles fournies par les outils. + +La hiérarchie est la suivante : + +* **Uvicorn** : un serveur ASGI + * **Starlette** : (utilise Uvicorn) un micro-framework web + * **FastAPI**: (utilise Starlette) un micro-framework pour API disposant de fonctionnalités additionnelles pour la création d'API, avec la validation des données, etc. + +* **Uvicorn** : + * A les meilleures performances, étant donné qu'il n'a pas beaucoup de code mis-à-part le serveur en lui-même. + * On n'écrit pas une application avec uniquement Uvicorn. Cela signifie que le code devrait inclure plus ou moins, au minimum, tout le code offert par Starlette (ou **FastAPI**). Et si on fait cela, l'application finale apportera les mêmes complications que si on avait utilisé un framework et que l'on avait minimisé la quantité de code et de bugs. + * Si on compare Uvicorn, il faut le comparer à d'autre applications de serveurs comme Daphne, Hypercorn, uWSGI, etc. +* **Starlette** : + * A les seconde meilleures performances après Uvicorn. Starlette utilise en réalité Uvicorn. De ce fait, il ne peut qu’être plus "lent" qu'Uvicorn car il requiert l'exécution de plus de code. + * Cependant il nous apporte les outils pour construire une application web simple, avec un routage basé sur des chemins, etc. + * Si on compare Starlette, il faut le comparer à d'autres frameworks web (ou micorframework) comme Sanic, Flask, Django, etc. +* **FastAPI** : + * Comme Starlette, FastAPI utilise Uvicorn et ne peut donc pas être plus rapide que ce dernier. + * FastAPI apporte des fonctionnalités supplémentaires à Starlette. Des fonctionnalités qui sont nécessaires presque systématiquement lors de la création d'une API, comme la validation des données, la sérialisation. En utilisant FastAPI, on obtient une documentation automatiquement (qui ne requiert aucune manipulation pour être mise en place). + * Si on n'utilisait pas FastAPI mais directement Starlette (ou un outil équivalent comme Sanic, Flask, Responder, etc) il faudrait implémenter la validation des données et la sérialisation par nous-même. Le résultat serait donc le même dans les deux cas mais du travail supplémentaire serait à réaliser avec Starlette, surtout en considérant que la validation des données et la sérialisation représentent la plus grande quantité de code à écrire dans une application. + * De ce fait, en utilisant FastAPI on minimise le temps de développement, les bugs, le nombre de lignes de code, et on obtient les mêmes performances (si ce n'est de meilleurs performances) que l'on aurait pu avoir sans ce framework (en ayant à implémenter de nombreuses fonctionnalités importantes par nous-mêmes). + * Si on compare FastAPI, il faut le comparer à d'autres frameworks web (ou ensemble d'outils) qui fournissent la validation des données, la sérialisation et la documentation, comme Flask-apispec, NestJS, Molten, etc. diff --git a/docs/fr/docs/contributing.md b/docs/fr/docs/contributing.md new file mode 100644 index 0000000000000..8292f14bb9b3e --- /dev/null +++ b/docs/fr/docs/contributing.md @@ -0,0 +1,501 @@ +# Développement - Contribuer + +Tout d'abord, vous voudrez peut-être voir les moyens de base pour [aider FastAPI et obtenir de l'aide](help-fastapi.md){.internal-link target=_blank}. + +## Développement + +Si vous avez déjà cloné le dépôt et que vous savez que vous devez vous plonger dans le code, voici quelques directives pour mettre en place votre environnement. + +### Environnement virtuel avec `venv` + +Vous pouvez créer un environnement virtuel dans un répertoire en utilisant le module `venv` de Python : + +
+ +```console +$ python -m venv env +``` + +
+ +Cela va créer un répertoire `./env/` avec les binaires Python et vous pourrez alors installer des paquets pour cet environnement isolé. + +### Activer l'environnement + +Activez le nouvel environnement avec : + +=== "Linux, macOS" + +
+ + ```console + $ source ./env/bin/activate + ``` + +
+ +=== "Windows PowerShell" + +
+ + ```console + $ .\env\Scripts\Activate.ps1 + ``` + +
+ +=== "Windows Bash" + + Ou si vous utilisez Bash pour Windows (par exemple Git Bash): + +
+ + ```console + $ source ./env/Scripts/activate + ``` + +
+ +Pour vérifier que cela a fonctionné, utilisez : + +=== "Linux, macOS, Windows Bash" + +
+ + ```console + $ which pip + + some/directory/fastapi/env/bin/pip + ``` + +
+ +=== "Windows PowerShell" + +
+ + ```console + $ Get-Command pip + + some/directory/fastapi/env/bin/pip + ``` + +
+ +Si celui-ci montre le binaire `pip` à `env/bin/pip`, alors ça a fonctionné. 🎉 + + + +!!! tip + Chaque fois que vous installez un nouveau paquet avec `pip` sous cet environnement, activez à nouveau l'environnement. + + Cela permet de s'assurer que si vous utilisez un programme terminal installé par ce paquet (comme `flit`), vous utilisez celui de votre environnement local et pas un autre qui pourrait être installé globalement. + +### Flit + +**FastAPI** utilise Flit pour build, packager et publier le projet. + +Après avoir activé l'environnement comme décrit ci-dessus, installez `flit` : + +
+ +```console +$ pip install flit + +---> 100% +``` + +
+ +Réactivez maintenant l'environnement pour vous assurer que vous utilisez le "flit" que vous venez d'installer (et non un environnement global). + +Et maintenant, utilisez `flit` pour installer les dépendances de développement : + +=== "Linux, macOS" + +
+ + ```console + $ flit install --deps develop --symlink + + ---> 100% + ``` + +
+ +=== "Windows" + + Si vous êtes sous Windows, utilisez `--pth-file` au lieu de `--symlink` : + +
+ + ```console + $ flit install --deps develop --pth-file + + ---> 100% + ``` + +
+ +Il installera toutes les dépendances et votre FastAPI local dans votre environnement local. + +#### Utiliser votre FastAPI local + +Si vous créez un fichier Python qui importe et utilise FastAPI, et que vous l'exécutez avec le Python de votre environnement local, il utilisera votre code source FastAPI local. + +Et si vous mettez à jour le code source local de FastAPI, tel qu'il est installé avec `--symlink` (ou `--pth-file` sous Windows), lorsque vous exécutez à nouveau ce fichier Python, il utilisera la nouvelle version de FastAPI que vous venez d'éditer. + +De cette façon, vous n'avez pas à "installer" votre version locale pour pouvoir tester chaque changement. + +### Formatage + +Il existe un script que vous pouvez exécuter qui formatera et nettoiera tout votre code : + +
+ +```console +$ bash scripts/format.sh +``` + +
+ +Il effectuera également un tri automatique de touts vos imports. + +Pour qu'il puisse les trier correctement, vous devez avoir FastAPI installé localement dans votre environnement, avec la commande dans la section ci-dessus en utilisant `--symlink` (ou `--pth-file` sous Windows). + +### Formatage des imports + +Il existe un autre script qui permet de formater touts les imports et de s'assurer que vous n'avez pas d'imports inutilisés : + +
+ +```console +$ bash scripts/format-imports.sh +``` + +
+ +Comme il exécute une commande après l'autre et modifie et inverse de nombreux fichiers, il prend un peu plus de temps à s'exécuter, il pourrait donc être plus facile d'utiliser fréquemment `scripts/format.sh` et `scripts/format-imports.sh` seulement avant de commit. + +## Documentation + +Tout d'abord, assurez-vous que vous configurez votre environnement comme décrit ci-dessus, qui installera toutes les exigences. + +La documentation utilise MkDocs. + +Et il y a des outils/scripts supplémentaires en place pour gérer les traductions dans `./scripts/docs.py`. + +!!! tip + Vous n'avez pas besoin de voir le code dans `./scripts/docs.py`, vous l'utilisez simplement dans la ligne de commande. + +Toute la documentation est au format Markdown dans le répertoire `./docs/fr/`. + +De nombreux tutoriels comportent des blocs de code. + +Dans la plupart des cas, ces blocs de code sont de véritables applications complètes qui peuvent être exécutées telles quelles. + +En fait, ces blocs de code ne sont pas écrits à l'intérieur du Markdown, ce sont des fichiers Python dans le répertoire `./docs_src/`. + +Et ces fichiers Python sont inclus/injectés dans la documentation lors de la génération du site. + +### Documentation pour les tests + +La plupart des tests sont en fait effectués par rapport aux exemples de fichiers sources dans la documentation. + +Cela permet de s'assurer que : + +* La documentation est à jour. +* Les exemples de documentation peuvent être exécutés tels quels. +* La plupart des fonctionnalités sont couvertes par la documentation, assurées par la couverture des tests. + +Au cours du développement local, un script build le site et vérifie les changements éventuels, puis il est rechargé en direct : + +
+ +```console +$ python ./scripts/docs.py live + +[INFO] Serving on http://127.0.0.1:8008 +[INFO] Start watching changes +[INFO] Start detecting changes +``` + +
+ +Il servira la documentation sur `http://127.0.0.1:8008`. + +De cette façon, vous pouvez modifier la documentation/les fichiers sources et voir les changements en direct. + +#### Typer CLI (facultatif) + +Les instructions ici vous montrent comment utiliser le script à `./scripts/docs.py` avec le programme `python` directement. + +Mais vous pouvez également utiliser Typer CLI, et vous obtiendrez l'auto-complétion dans votre terminal pour les commandes après l'achèvement de l'installation. + +Si vous installez Typer CLI, vous pouvez installer la complétion avec : + +
+ +```console +$ typer --install-completion + +zsh completion installed in /home/user/.bashrc. +Completion will take effect once you restart the terminal. +``` + +
+ +### Apps et documentation en même temps + +Si vous exécutez les exemples avec, par exemple : + +
+ +```console +$ uvicorn tutorial001:app --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Comme Uvicorn utilisera par défaut le port `8000`, la documentation sur le port `8008` n'entrera pas en conflit. + +### Traductions + +L'aide aux traductions est TRÈS appréciée ! Et cela ne peut se faire sans l'aide de la communauté. 🌎 🚀 + +Voici les étapes à suivre pour aider à la traduction. + +#### Conseils et lignes directrices + +* Vérifiez les pull requests existantes pour votre langue et ajouter des reviews demandant des changements ou les approuvant. + +!!! tip + Vous pouvez ajouter des commentaires avec des suggestions de changement aux pull requests existantes. + + Consultez les documents concernant l'ajout d'un review de pull request pour l'approuver ou demander des modifications. + +* Vérifiez dans issues pour voir s'il y a une personne qui coordonne les traductions pour votre langue. + +* Ajoutez une seule pull request par page traduite. Il sera ainsi beaucoup plus facile pour les autres de l'examiner. + +Pour les langues que je ne parle pas, je vais attendre plusieurs autres reviews de la traduction avant de merge. + +* Vous pouvez également vérifier s'il existe des traductions pour votre langue et y ajouter une review, ce qui m'aidera à savoir si la traduction est correcte et je pourrai la fusionner. + +* Utilisez les mêmes exemples en Python et ne traduisez que le texte des documents. Vous n'avez pas besoin de changer quoi que ce soit pour que cela fonctionne. + +* Utilisez les mêmes images, noms de fichiers et liens. Vous n'avez pas besoin de changer quoi que ce soit pour que cela fonctionne. + +* Pour vérifier le code à 2 lettres de la langue que vous souhaitez traduire, vous pouvez utiliser le tableau Liste des codes ISO 639-1. + +#### Langue existante + +Disons que vous voulez traduire une page pour une langue qui a déjà des traductions pour certaines pages, comme l'espagnol. + +Dans le cas de l'espagnol, le code à deux lettres est `es`. Ainsi, le répertoire des traductions espagnoles se trouve à l'adresse `docs/es/`. + +!!! tip + La langue principale ("officielle") est l'anglais, qui se trouve à l'adresse "docs/en/". + +Maintenant, lancez le serveur en live pour les documents en espagnol : + +
+ +```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 +``` + +
+ +Vous pouvez maintenant aller sur http://127.0.0.1:8008 et voir vos changements en direct. + +Si vous regardez le site web FastAPI docs, vous verrez que chaque langue a toutes les pages. Mais certaines pages ne sont pas traduites et sont accompagnées d'une notification concernant la traduction manquante. + +Mais si vous le gérez localement de cette manière, vous ne verrez que les pages déjà traduites. + +Disons maintenant que vous voulez ajouter une traduction pour la section [Features](features.md){.internal-link target=_blank}. + +* Copiez le fichier à : + +``` +docs/en/docs/features.md +``` + +* Collez-le exactement au même endroit mais pour la langue que vous voulez traduire, par exemple : + +``` +docs/es/docs/features.md +``` + +!!! tip + Notez que le seul changement dans le chemin et le nom du fichier est le code de langue, qui passe de `en` à `es`. + +* Ouvrez maintenant le fichier de configuration de MkDocs pour l'anglais à + +``` +docs/en/docs/mkdocs.yml +``` + +* Trouvez l'endroit où cette `docs/features.md` se trouve dans le fichier de configuration. Quelque part comme : + +```YAML hl_lines="8" +site_name: FastAPI +# More stuff +nav: +- FastAPI: index.md +- Languages: + - en: / + - es: /es/ +- features.md +``` + +* Ouvrez le fichier de configuration MkDocs pour la langue que vous éditez, par exemple : + +``` +docs/es/docs/mkdocs.yml +``` + +* Ajoutez-le à l'endroit exact où il se trouvait pour l'anglais, par exemple : + +```YAML hl_lines="8" +site_name: FastAPI +# More stuff +nav: +- FastAPI: index.md +- Languages: + - en: / + - es: /es/ +- features.md +``` + +Assurez-vous que s'il y a d'autres entrées, la nouvelle entrée avec votre traduction est exactement dans le même ordre que dans la version anglaise. + +Si vous allez sur votre navigateur, vous verrez que maintenant les documents montrent votre nouvelle section. 🎉 + +Vous pouvez maintenant tout traduire et voir à quoi cela ressemble au fur et à mesure que vous enregistrez le fichier. + +#### Nouvelle langue + +Disons que vous voulez ajouter des traductions pour une langue qui n'est pas encore traduite, pas même quelques pages. + +Disons que vous voulez ajouter des traductions pour le Créole, et que ce n'est pas encore dans les documents. + +En vérifiant le lien ci-dessus, le code pour "Créole" est `ht`. + +L'étape suivante consiste à exécuter le script pour générer un nouveau répertoire de traduction : + +
+ +```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 +``` + +
+ +Vous pouvez maintenant vérifier dans votre éditeur de code le répertoire nouvellement créé `docs/ht/`. + +!!! tip + Créez une première demande d'extraction à l'aide de cette fonction, afin de configurer la nouvelle langue avant d'ajouter des traductions. + + Ainsi, d'autres personnes peuvent vous aider à rédiger d'autres pages pendant que vous travaillez sur la première. 🚀 + +Commencez par traduire la page principale, `docs/ht/index.md`. + +Vous pouvez ensuite continuer avec les instructions précédentes, pour une "langue existante". + +##### Nouvelle langue non prise en charge + +Si, lors de l'exécution du script du serveur en direct, vous obtenez une erreur indiquant que la langue n'est pas prise en charge, quelque chose comme : + +``` + raise TemplateNotFound(template) +jinja2.exceptions.TemplateNotFound: partials/language/xx.html +``` + +Cela signifie que le thème ne supporte pas cette langue (dans ce cas, avec un faux code de 2 lettres de `xx`). + +Mais ne vous inquiétez pas, vous pouvez définir la langue du thème en anglais et ensuite traduire le contenu des documents. + +Si vous avez besoin de faire cela, modifiez le fichier `mkdocs.yml` pour votre nouvelle langue, il aura quelque chose comme : + +```YAML hl_lines="5" +site_name: FastAPI +# More stuff +theme: + # More stuff + language: xx +``` + +Changez cette langue de `xx` (de votre code de langue) à `fr`. + +Vous pouvez ensuite relancer le serveur live. + +#### Prévisualisez le résultat + +Lorsque vous utilisez le script à `./scripts/docs.py` avec la commande `live`, il n'affiche que les fichiers et les traductions disponibles pour la langue courante. + +Mais une fois que vous avez terminé, vous pouvez tester le tout comme il le ferait en ligne. + +Pour ce faire, il faut d'abord construire tous les documents : + +
+ +```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 +``` + +
+ +Cela génère tous les documents à `./docs_build/` pour chaque langue. Cela inclut l'ajout de tout fichier dont la traduction est manquante, avec une note disant que "ce fichier n'a pas encore de traduction". Mais vous n'avez rien à faire avec ce répertoire. + +Ensuite, il construit tous ces sites MkDocs indépendants pour chaque langue, les combine, et génère le résultat final à `./site/`. + +Ensuite, vous pouvez servir cela avec le commandement `serve`: + +
+ +```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 +``` + +
+ +## Tests + +Il existe un script que vous pouvez exécuter localement pour tester tout le code et générer des rapports de couverture en HTML : + +
+ +```console +$ bash scripts/test-cov-html.sh +``` + +
+ +Cette commande génère un répertoire `./htmlcov/`, si vous ouvrez le fichier `./htmlcov/index.html` dans votre navigateur, vous pouvez explorer interactivement les régions de code qui sont couvertes par les tests, et remarquer s'il y a une région manquante. diff --git a/docs/fr/docs/deployment/deta.md b/docs/fr/docs/deployment/deta.md deleted file mode 100644 index cceb7b058c58b..0000000000000 --- a/docs/fr/docs/deployment/deta.md +++ /dev/null @@ -1,245 +0,0 @@ -# Déployer FastAPI sur Deta - -Dans cette section, vous apprendrez à déployer facilement une application **FastAPI** sur Deta en utilisant le plan tarifaire gratuit. 🎁 - -Cela vous prendra environ **10 minutes**. - -!!! info - Deta sponsorise **FastAPI**. 🎉 - -## Une application **FastAPI** de base - -* Créez un répertoire pour votre application, par exemple `./fastapideta/` et déplacez-vous dedans. - -### Le code FastAPI - -* Créer un fichier `main.py` avec : - -```Python -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): - return {"item_id": item_id} -``` - -### Dépendances - -Maintenant, dans le même répertoire, créez un fichier `requirements.txt` avec : - -```text -fastapi -``` - -!!! tip "Astuce" - Il n'est pas nécessaire d'installer Uvicorn pour déployer sur Deta, bien qu'il soit probablement souhaitable de l'installer localement pour tester votre application. - -### Structure du répertoire - -Vous aurez maintenant un répertoire `./fastapideta/` avec deux fichiers : - -``` -. -└── main.py -└── requirements.txt -``` - -## Créer un compte gratuit sur Deta - -Créez maintenant un compte gratuit -sur Deta, vous avez juste besoin d'une adresse email et d'un mot de passe. - -Vous n'avez même pas besoin d'une carte de crédit. - -## Installer le CLI (Interface en Ligne de Commande) - -Une fois que vous avez votre compte, installez le CLI de Deta : - -=== "Linux, macOS" - -
- - ```console - $ curl -fsSL https://get.deta.dev/cli.sh | sh - ``` - -
- -=== "Windows PowerShell" - -
- - ```console - $ iwr https://get.deta.dev/cli.ps1 -useb | iex - ``` - -
- -Après l'avoir installé, ouvrez un nouveau terminal afin que la nouvelle installation soit détectée. - -Dans un nouveau terminal, confirmez qu'il a été correctement installé avec : - -
- -```console -$ deta --help - -Deta command line interface for managing deta micros. -Complete documentation available at https://docs.deta.sh - -Usage: - deta [flags] - deta [command] - -Available Commands: - auth Change auth settings for a deta micro - -... -``` - -
- -!!! tip "Astuce" - Si vous rencontrez des problèmes pour installer le CLI, consultez la documentation officielle de Deta (en anglais). - -## Connexion avec le CLI - -Maintenant, connectez-vous à Deta depuis le CLI avec : - -
- -```console -$ deta login - -Please, log in from the web page. Waiting.. -Logged in successfully. -``` - -
- -Cela ouvrira un navigateur web et permettra une authentification automatique. - -## Déployer avec Deta - -Ensuite, déployez votre application avec le CLI de Deta : - -
- -```console -$ deta new - -Successfully created a new micro - -// Notice the "endpoint" 🔍 - -{ - "name": "fastapideta", - "runtime": "python3.7", - "endpoint": "https://qltnci.deta.dev", - "visor": "enabled", - "http_auth": "enabled" -} - -Adding dependencies... - - ----> 100% - - -Successfully installed fastapi-0.61.1 pydantic-1.7.2 starlette-0.13.6 -``` - -
- -Vous verrez un message JSON similaire à : - -```JSON hl_lines="4" -{ - "name": "fastapideta", - "runtime": "python3.7", - "endpoint": "https://qltnci.deta.dev", - "visor": "enabled", - "http_auth": "enabled" -} -``` - -!!! tip "Astuce" - Votre déploiement aura une URL `"endpoint"` différente. - -## Vérifiez - -Maintenant, dans votre navigateur ouvrez votre URL `endpoint`. Dans l'exemple ci-dessus, c'était -`https://qltnci.deta.dev`, mais la vôtre sera différente. - -Vous verrez la réponse JSON de votre application FastAPI : - -```JSON -{ - "Hello": "World" -} -``` - -Et maintenant naviguez vers `/docs` dans votre API, dans l'exemple ci-dessus ce serait `https://qltnci.deta.dev/docs`. - -Vous verrez votre documentation comme suit : - - - -## Activer l'accès public - -Par défaut, Deta va gérer l'authentification en utilisant des cookies pour votre compte. - -Mais une fois que vous êtes prêt, vous pouvez le rendre public avec : - -
- -```console -$ deta auth disable - -Successfully disabled http auth -``` - -
- -Maintenant, vous pouvez partager cette URL avec n'importe qui et ils seront en mesure d'accéder à votre API. 🚀 - -## HTTPS - -Félicitations ! Vous avez déployé votre application FastAPI sur Deta ! 🎉 🍰 - -Remarquez également que Deta gère correctement HTTPS pour vous, vous n'avez donc pas à vous en occuper et pouvez être sûr que vos clients auront une connexion cryptée sécurisée. ✅ 🔒 - -## Vérifiez le Visor - -À partir de l'interface graphique de votre documentation (dans une URL telle que `https://qltnci.deta.dev/docs`) -envoyez une requête à votre *opération de chemin* `/items/{item_id}`. - -Par exemple avec l'ID `5`. - -Allez maintenant sur https://web.deta.sh. - -Vous verrez qu'il y a une section à gauche appelée "Micros" avec chacune de vos applications. - -Vous verrez un onglet avec "Details", et aussi un onglet "Visor", allez à l'onglet "Visor". - -Vous pouvez y consulter les requêtes récentes envoyées à votre application. - -Vous pouvez également les modifier et les relancer. - - - -## En savoir plus - -À un moment donné, vous voudrez probablement stocker certaines données pour votre application d'une manière qui -persiste dans le temps. Pour cela, vous pouvez utiliser Deta Base, il dispose également d'un généreux **plan gratuit**. - -Vous pouvez également en lire plus dans la documentation Deta. diff --git a/docs/fr/docs/external-links.md b/docs/fr/docs/external-links.md index 002e6d2b21c8c..37b8c5b139ee3 100644 --- a/docs/fr/docs/external-links.md +++ b/docs/fr/docs/external-links.md @@ -9,70 +9,21 @@ Voici une liste incomplète de certains d'entre eux. !!! tip "Astuce" Si vous avez un article, projet, outil, ou quoi que ce soit lié à **FastAPI** qui n'est actuellement pas listé ici, créez une Pull Request l'ajoutant. -## Articles +{% for section_name, section_content in external_links.items() %} -### Anglais +## {{ section_name }} -{% if external_links %} -{% for article in external_links.articles.english %} +{% for lang_name, lang_content in section_content.items() %} -* {{ article.title }} par {{ article.author }}. -{% endfor %} -{% endif %} - -### Japonais - -{% if external_links %} -{% for article in external_links.articles.japanese %} - -* {{ article.title }} par {{ article.author }}. -{% endfor %} -{% endif %} +### {{ lang_name }} -### Vietnamien +{% for item in lang_content %} -{% if external_links %} -{% for article in external_links.articles.vietnamese %} +* {{ item.title }} by {{ item.author }}. -* {{ article.title }} par {{ article.author }}. {% endfor %} -{% endif %} - -### Russe - -{% if external_links %} -{% for article in external_links.articles.russian %} - -* {{ article.title }} par {{ article.author }}. {% endfor %} -{% endif %} - -### Allemand - -{% if external_links %} -{% for article in external_links.articles.german %} - -* {{ article.title }} par {{ article.author }}. -{% endfor %} -{% endif %} - -## Podcasts - -{% if external_links %} -{% for article in external_links.podcasts.english %} - -* {{ article.title }} par {{ article.author }}. -{% endfor %} -{% endif %} - -## Conférences - -{% if external_links %} -{% for article in external_links.talks.english %} - -* {{ article.title }} par {{ article.author }}. {% endfor %} -{% endif %} ## Projets diff --git a/docs/fr/docs/fastapi-people.md b/docs/fr/docs/fastapi-people.md index 945f0794e918f..275a9bd37c8b3 100644 --- a/docs/fr/docs/fastapi-people.md +++ b/docs/fr/docs/fastapi-people.md @@ -40,7 +40,7 @@ Ce sont les utilisateurs qui ont [aidé le plus les autres avec des problèmes ( {% if people %}
-{% for user in people.last_month_active %} +{% for user in people.last_month_experts[:10] %}
@{{ user.login }}
Questions répondues: {{ user.count }}
{% endfor %} @@ -58,7 +58,7 @@ Ils ont prouvé qu'ils étaient des experts en aidant beaucoup d'autres personne {% if people %}
-{% for user in people.experts %} +{% for user in people.experts[:50] %}
@{{ user.login }}
Questions répondues: {{ user.count }}
{% endfor %} @@ -76,7 +76,7 @@ Ils ont contribué au code source, à la documentation, aux traductions, etc. {% if people %}
-{% for user in people.top_contributors %} +{% for user in people.top_contributors[:50] %}
@{{ user.login }}
Pull Requests: {{ user.count }}
{% endfor %} @@ -100,7 +100,7 @@ Les **Principaux Reviewers** 🕵️ ont examiné le plus grand nombre de demand {% if people %}
-{% for user in people.top_reviewers %} +{% for user in people.top_translations_reviewers[:50] %}
@{{ user.login }}
Reviews: {{ user.count }}
{% endfor %} diff --git a/docs/fr/docs/features.md b/docs/fr/docs/features.md index dcc0e39ed77ac..1457df2a5c1a3 100644 --- a/docs/fr/docs/features.md +++ b/docs/fr/docs/features.md @@ -25,7 +25,7 @@ Documentation d'API interactive et interface web d'exploration. Comme le framewo ### Faite en python moderne -Tout est basé sur la déclaration de type standard de **Python 3.6** (grâce à Pydantic). Pas de nouvelles syntaxes à apprendre. Juste du Python standard et moderne. +Tout est basé sur la déclaration de type standard de **Python 3.8** (grâce à Pydantic). Pas de nouvelles syntaxes à apprendre. Juste du Python standard et moderne. Si vous souhaitez un rappel de 2 minutes sur l'utilisation des types en Python (même si vous ne comptez pas utiliser FastAPI), jetez un oeil au tutoriel suivant: [Python Types](python-types.md){.internal-link target=_blank}. @@ -71,9 +71,9 @@ my_second_user: User = User(**second_user_data) Tout le framework a été conçu pour être facile et intuitif d'utilisation, toutes les décisions de design ont été testées sur de nombreux éditeurs avant même de commencer le développement final afin d'assurer la meilleure expérience de développement possible. -Dans le dernier sondage effectué auprès de développeurs python il était clair que la fonctionnalité la plus utilisée est "l'autocomplètion". +Dans le dernier sondage effectué auprès de développeurs python il était clair que la fonctionnalité la plus utilisée est "l’autocomplétion". -Tout le framwork **FastAPI** a été conçu avec cela en tête. L'autocomplétion fonctionne partout. +Tout le framework **FastAPI** a été conçu avec cela en tête. L'autocomplétion fonctionne partout. Vous devrez rarement revenir à la documentation. @@ -136,7 +136,7 @@ FastAPI contient un système simple mais extrêmement puissant d'Starlette. Le code utilisant Starlette que vous ajouterez fonctionnera donc aussi. -En fait, `FastAPI` est un sous compposant de `Starlette`. Donc, si vous savez déjà comment utiliser Starlette, la plupart des fonctionnalités fonctionneront de la même manière. +En fait, `FastAPI` est un sous composant de `Starlette`. Donc, si vous savez déjà comment utiliser Starlette, la plupart des fonctionnalités fonctionneront de la même manière. Avec **FastAPI** vous aurez toutes les fonctionnalités de **Starlette** (FastAPI est juste Starlette sous stéroïdes): -* Des performances vraiments impressionnantes. C'est l'un des framework Python les plus rapide, à égalité avec **NodeJS** et **GO**. +* Des performances vraiment impressionnantes. C'est l'un des framework Python les plus rapide, à égalité avec **NodeJS** et **GO**. * Le support des **WebSockets**. * Le support de **GraphQL**. * Les tâches d'arrière-plan. @@ -174,13 +174,13 @@ Avec **FastAPI** vous aurez toutes les fonctionnalités de **Starlette** (FastAP ## Fonctionnalités de Pydantic -**FastAPI** est totalement compatible avec (et basé sur) Pydantic. Le code utilisant Pydantic que vous ajouterez fonctionnera donc aussi. +**FastAPI** est totalement compatible avec (et basé sur) Pydantic. Le code utilisant Pydantic que vous ajouterez fonctionnera donc aussi. Inclus des librairies externes basées, aussi, sur Pydantic, servent d'ORMs, ODMs pour les bases de données. Cela signifie aussi que, dans la plupart des cas, vous pouvez fournir l'objet reçu d'une requête **directement à la base de données**, comme tout est validé automatiquement. -Inversément, dans la plupart des cas vous pourrez juste envoyer l'objet récupéré de la base de données **directement au client** +Inversement, dans la plupart des cas vous pourrez juste envoyer l'objet récupéré de la base de données **directement au client** Avec **FastAPI** vous aurez toutes les fonctionnalités de **Pydantic** (comme FastAPI est basé sur Pydantic pour toutes les manipulations de données): @@ -189,12 +189,10 @@ Avec **FastAPI** vous aurez toutes les fonctionnalités de **Pydantic** (comme * Si vous connaissez le typage en python vous savez comment utiliser Pydantic. * Aide votre **IDE/linter/cerveau**: * Parce que les structures de données de pydantic consistent seulement en une instance de classe que vous définissez; l'auto-complétion, le linting, mypy et votre intuition devrait être largement suffisante pour valider vos données. -* **Rapide**: - * Dans les benchmarks Pydantic est plus rapide que toutes les autres librairies testées. * Valide les **structures complexes**: * Utilise les modèles hiérarchique de Pydantic, le `typage` Python pour les `Lists`, `Dict`, etc. * Et les validateurs permettent aux schémas de données complexes d'être clairement et facilement définis, validés et documentés sous forme d'un schéma JSON. - * Vous pouvez avoir des objets **JSON fortements imbriqués** tout en ayant, pour chacun, de la validation et des annotations. + * Vous pouvez avoir des objets **JSON fortement imbriqués** tout en ayant, pour chacun, de la validation et des annotations. * **Renouvelable**: * Pydantic permet de définir de nouveaux types de données ou vous pouvez étendre la validation avec des méthodes sur un modèle décoré avec le décorateur de validation * 100% de couverture de test. diff --git a/docs/fr/docs/help-fastapi.md b/docs/fr/docs/help-fastapi.md index 0995721e1e397..525c699f5f96a 100644 --- a/docs/fr/docs/help-fastapi.md +++ b/docs/fr/docs/help-fastapi.md @@ -36,8 +36,8 @@ Vous pouvez : * Me suivre sur **Twitter**. * Dites-moi comment vous utilisez FastAPI (j'adore entendre ça). * Entendre quand je fais des annonces ou que je lance de nouveaux outils. -* Vous connectez à moi sur **Linkedin**. - * Etre notifié quand je fais des annonces ou que je lance de nouveaux outils (bien que j'utilise plus souvent Twitte 🤷‍♂). +* Vous connectez à moi sur **LinkedIn**. + * Etre notifié quand je fais des annonces ou que je lance de nouveaux outils (bien que j'utilise plus souvent Twitter 🤷‍♂). * Lire ce que j’écris (ou me suivre) sur **Dev.to** ou **Medium**. * Lire d'autres idées, articles, et sur les outils que j'ai créés. * Suivez-moi pour lire quand je publie quelque chose de nouveau. @@ -84,24 +84,6 @@ Vous pouvez - Rejoindre le chat à https://gitter.im/tiangolo/fastapi - - -Rejoignez le chat sur Gitter: https://gitter.im/tiangolo/fastapi. - -Vous pouvez y avoir des conversations rapides avec d'autres personnes, aider les autres, partager des idées, etc. - -Mais gardez à l'esprit que, comme il permet une "conversation plus libre", il est facile de poser des questions trop générales et plus difficiles à répondre, de sorte que vous risquez de ne pas recevoir de réponses. - -Dans les Issues de GitHub, le modèle vous guidera pour écrire la bonne question afin que vous puissiez plus facilement obtenir une bonne réponse, ou même résoudre le problème vous-même avant même de le poser. Et dans GitHub, je peux m'assurer que je réponds toujours à tout, même si cela prend du temps. Je ne peux pas faire cela personnellement avec le chat Gitter. 😅 - -Les conversations dans Gitter ne sont pas non plus aussi facilement consultables que dans GitHub, de sorte que les questions et les réponses peuvent se perdre dans la conversation. - -De l'autre côté, il y a plus de 1000 personnes dans le chat, il y a donc de fortes chances que vous y trouviez quelqu'un à qui parler, presque tout le temps. 😄 - ## Parrainer l'auteur Vous pouvez également soutenir financièrement l'auteur (moi) via GitHub sponsors. diff --git a/docs/fr/docs/history-design-future.md b/docs/fr/docs/history-design-future.md index b77664be6c2c0..beb649121dda5 100644 --- a/docs/fr/docs/history-design-future.md +++ b/docs/fr/docs/history-design-future.md @@ -54,7 +54,7 @@ Le tout de manière à offrir la meilleure expérience de développement à tous ## Exigences -Après avoir testé plusieurs alternatives, j'ai décidé que j'allais utiliser **Pydantic** pour ses avantages. +Après avoir testé plusieurs alternatives, j'ai décidé que j'allais utiliser **Pydantic** pour ses avantages. J'y ai ensuite contribué, pour le rendre entièrement compatible avec JSON Schema, pour supporter différentes manières de définir les déclarations de contraintes, et pour améliorer le support des éditeurs (vérifications de type, autocomplétion) sur la base des tests effectués dans plusieurs éditeurs. diff --git a/docs/fr/docs/index.md b/docs/fr/docs/index.md index 7c7547be1c2cc..bc3ae3c06307d 100644 --- a/docs/fr/docs/index.md +++ b/docs/fr/docs/index.md @@ -27,7 +27,7 @@ --- -FastAPI est un framework web moderne et rapide (haute performance) pour la création d'API avec Python 3.7+, basé sur les annotations de type standard de Python. +FastAPI est un framework web moderne et rapide (haute performance) pour la création d'API avec Python 3.8+, basé sur les annotations de type standard de Python. Les principales fonctionnalités sont : @@ -115,12 +115,12 @@ Si vous souhaitez construire une application Starlette pour les parties web. -* Pydantic pour les parties données. +* Pydantic pour les parties données. ## Installation @@ -331,7 +331,7 @@ Vous faites cela avec les types Python standard modernes. Vous n'avez pas à apprendre une nouvelle syntaxe, les méthodes ou les classes d'une bibliothèque spécifique, etc. -Juste du **Python 3.7+** standard. +Juste du **Python 3.8+** standard. Par exemple, pour un `int`: @@ -424,7 +424,7 @@ Pour un exemple plus complet comprenant plus de fonctionnalités, voir le 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 . +* 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. @@ -450,8 +450,8 @@ Utilisées par Pydantic: Utilisées par Starlette : * 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()`. +* jinja2 - Obligatoire si vous souhaitez utiliser la configuration de template par défaut. +* python-multipart - Obligatoire si vous souhaitez supporter le "décodage" de formulaire avec `request.form()`. * itsdangerous - Obligatoire pour la prise en charge de `SessionMiddleware`. * pyyaml - Obligatoire pour le support `SchemaGenerator` de Starlette (vous n'en avez probablement pas besoin avec FastAPI). * ujson - Obligatoire si vous souhaitez utiliser `UJSONResponse`. diff --git a/docs/fr/docs/python-types.md b/docs/fr/docs/python-types.md index 4008ed96fc802..4232633e3d6e5 100644 --- a/docs/fr/docs/python-types.md +++ b/docs/fr/docs/python-types.md @@ -119,7 +119,7 @@ Comme l'éditeur connaît le type des variables, vous n'avez pas seulement l'aut -Maintenant que vous avez connaissance du problème, convertissez `age` en chaine de caractères grâce à `str(age)` : +Maintenant que vous avez connaissance du problème, convertissez `age` en chaîne de caractères grâce à `str(age)` : ```Python hl_lines="2" {!../../../docs_src/python_types/tutorial004.py!} @@ -265,7 +265,7 @@ Et vous aurez accès, encore une fois, au support complet offert par l'éditeur ## Les modèles Pydantic -Pydantic est une bibliothèque Python pour effectuer de la validation de données. +Pydantic est une bibliothèque Python pour effectuer de la validation de données. Vous déclarez la forme de la donnée avec des classes et des attributs. @@ -282,7 +282,7 @@ Extrait de la documentation officielle de **Pydantic** : ``` !!! info - Pour en savoir plus à propos de Pydantic, allez jeter un coup d'oeil à sa documentation. + Pour en savoir plus à propos de Pydantic, allez jeter un coup d'oeil à sa documentation. **FastAPI** est basé entièrement sur **Pydantic**. diff --git a/docs/fr/docs/tutorial/body.md b/docs/fr/docs/tutorial/body.md index 1e732d3364f9d..ae952405cbc26 100644 --- a/docs/fr/docs/tutorial/body.md +++ b/docs/fr/docs/tutorial/body.md @@ -6,7 +6,7 @@ Le corps d'une **requête** est de la donnée envoyée par le client à votre AP Votre API aura presque toujours à envoyer un corps de **réponse**. Mais un client n'a pas toujours à envoyer un corps de **requête**. -Pour déclarer un corps de **requête**, on utilise les modèles de Pydantic en profitant de tous leurs avantages et fonctionnalités. +Pour déclarer un corps de **requête**, on utilise les modèles de Pydantic en profitant de tous leurs avantages et fonctionnalités. !!! info Pour envoyer de la donnée, vous devriez utiliser : `POST` (le plus populaire), `PUT`, `DELETE` ou `PATCH`. @@ -98,7 +98,7 @@ Et vous obtenez aussi de la vérification d'erreur pour les opérations incorrec -Ce n'est pas un hasard, ce framework entier a été bati avec ce design comme objectif. +Ce n'est pas un hasard, ce framework entier a été bâti avec ce design comme objectif. Et cela a été rigoureusement testé durant la phase de design, avant toute implémentation, pour s'assurer que cela fonctionnerait avec tous les éditeurs. diff --git a/docs/fr/docs/tutorial/first-steps.md b/docs/fr/docs/tutorial/first-steps.md index 224c340c66e93..e98283f1e2e51 100644 --- a/docs/fr/docs/tutorial/first-steps.md +++ b/docs/fr/docs/tutorial/first-steps.md @@ -170,7 +170,7 @@ Si vous créez votre app avec : {!../../../docs_src/first_steps/tutorial002.py!} ``` -Et la mettez dans un fichier `main.py`, alors vous appeleriez `uvicorn` avec : +Et la mettez dans un fichier `main.py`, alors vous appelleriez `uvicorn` avec :
diff --git a/docs/fr/docs/tutorial/index.md b/docs/fr/docs/tutorial/index.md new file mode 100644 index 0000000000000..4dc202b3349eb --- /dev/null +++ b/docs/fr/docs/tutorial/index.md @@ -0,0 +1,80 @@ +# Tutoriel - Guide utilisateur - Introduction + +Ce tutoriel vous montre comment utiliser **FastAPI** avec la plupart de ses fonctionnalités, étape par étape. + +Chaque section s'appuie progressivement sur les précédentes, mais elle est structurée de manière à séparer les sujets, afin que vous puissiez aller directement à l'un d'entre eux pour résoudre vos besoins spécifiques en matière d'API. + +Il est également conçu pour fonctionner comme une référence future. + +Vous pouvez donc revenir et voir exactement ce dont vous avez besoin. + +## Exécuter le code + +Tous les blocs de code peuvent être copiés et utilisés directement (il s'agit en fait de fichiers Python testés). + +Pour exécuter l'un de ces exemples, copiez le code dans un fichier `main.py`, et commencez `uvicorn` avec : + +
+ +```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. +``` + +
+ +Il est **FORTEMENT encouragé** que vous écriviez ou copiez le code, l'éditiez et l'exécutiez localement. + +L'utiliser dans votre éditeur est ce qui vous montre vraiment les avantages de FastAPI, en voyant le peu de code que vous avez à écrire, toutes les vérifications de type, l'autocomplétion, etc. + +--- + +## Installer FastAPI + +La première étape consiste à installer FastAPI. + +Pour le tutoriel, vous voudrez peut-être l'installer avec toutes les dépendances et fonctionnalités optionnelles : + +
+ +```console +$ pip install fastapi[all] + +---> 100% +``` + +
+ +... qui comprend également `uvicorn`, que vous pouvez utiliser comme serveur pour exécuter votre code. + +!!! note + Vous pouvez également l'installer pièce par pièce. + + C'est ce que vous feriez probablement une fois que vous voudrez déployer votre application en production : + + ``` + pip install fastapi + ``` + + Installez également `uvicorn` pour qu'il fonctionne comme serveur : + + ``` + pip install uvicorn + ``` + + Et la même chose pour chacune des dépendances facultatives que vous voulez utiliser. + +## Guide utilisateur avancé + +Il existe également un **Guide d'utilisation avancé** que vous pouvez lire plus tard après ce **Tutoriel - Guide d'utilisation**. + +Le **Guide d'utilisation avancé**, qui s'appuie sur cette base, utilise les mêmes concepts et vous apprend quelques fonctionnalités supplémentaires. + +Mais vous devez d'abord lire le **Tutoriel - Guide d'utilisation** (ce que vous êtes en train de lire en ce moment). + +Il est conçu pour que vous puissiez construire une application complète avec seulement le **Tutoriel - Guide d'utilisation**, puis l'étendre de différentes manières, en fonction de vos besoins, en utilisant certaines des idées supplémentaires du **Guide d'utilisation avancé**. diff --git a/docs/fr/docs/tutorial/path-params.md b/docs/fr/docs/tutorial/path-params.md index 894d62dd46108..817545c1c6725 100644 --- a/docs/fr/docs/tutorial/path-params.md +++ b/docs/fr/docs/tutorial/path-params.md @@ -106,7 +106,7 @@ pour de nombreux langages. ## Pydantic -Toute la validation de données est effectué en arrière-plan avec Pydantic, +Toute la validation de données est effectué en arrière-plan avec Pydantic, dont vous bénéficierez de tous les avantages. Vous savez donc que vous êtes entre de bonnes mains. ## L'ordre importe diff --git a/docs/fr/docs/tutorial/query-params-str-validations.md b/docs/fr/docs/tutorial/query-params-str-validations.md new file mode 100644 index 0000000000000..f5248fe8b3297 --- /dev/null +++ b/docs/fr/docs/tutorial/query-params-str-validations.md @@ -0,0 +1,305 @@ +# Paramètres de requête et validations de chaînes de caractères + +**FastAPI** vous permet de déclarer des informations et des validateurs additionnels pour vos paramètres de requêtes. + +Commençons avec cette application pour exemple : + +```Python hl_lines="9" +{!../../../docs_src/query_params_str_validations/tutorial001.py!} +``` + +Le paramètre de requête `q` a pour type `Union[str, None]` (ou `str | None` en Python 3.10), signifiant qu'il est de type `str` mais pourrait aussi être égal à `None`, et bien sûr, la valeur par défaut est `None`, donc **FastAPI** saura qu'il n'est pas requis. + +!!! note + **FastAPI** saura que la valeur de `q` n'est pas requise grâce à la valeur par défaut `= None`. + + Le `Union` dans `Union[str, None]` permettra à votre éditeur de vous offrir un meilleur support et de détecter les erreurs. + +## Validation additionnelle + +Nous allons imposer que bien que `q` soit un paramètre optionnel, dès qu'il est fourni, **sa longueur n'excède pas 50 caractères**. + +## Importer `Query` + +Pour cela, importez d'abord `Query` depuis `fastapi` : + +```Python hl_lines="3" +{!../../../docs_src/query_params_str_validations/tutorial002.py!} +``` + +## Utiliser `Query` comme valeur par défaut + +Construisez ensuite la valeur par défaut de votre paramètre avec `Query`, en choisissant 50 comme `max_length` : + +```Python hl_lines="9" +{!../../../docs_src/query_params_str_validations/tutorial002.py!} +``` + +Comme nous devons remplacer la valeur par défaut `None` dans la fonction par `Query()`, nous pouvons maintenant définir la valeur par défaut avec le paramètre `Query(default=None)`, il sert le même objectif qui est de définir cette valeur par défaut. + +Donc : + +```Python +q: Union[str, None] = Query(default=None) +``` + +... rend le paramètre optionnel, et est donc équivalent à : + +```Python +q: Union[str, None] = None +``` + +Mais déclare explicitement `q` comme étant un paramètre de requête. + +!!! info + Gardez à l'esprit que la partie la plus importante pour rendre un paramètre optionnel est : + + ```Python + = None + ``` + + ou : + + ```Python + = Query(None) + ``` + + et utilisera ce `None` pour détecter que ce paramètre de requête **n'est pas requis**. + + Le `Union[str, None]` est uniquement là pour permettre à votre éditeur un meilleur support. + +Ensuite, nous pouvons passer d'autres paramètres à `Query`. Dans cet exemple, le paramètre `max_length` qui s'applique aux chaînes de caractères : + +```Python +q: Union[str, None] = Query(default=None, max_length=50) +``` + +Cela va valider les données, montrer une erreur claire si ces dernières ne sont pas valides, et documenter le paramètre dans le schéma `OpenAPI` de cette *path operation*. + +## Rajouter plus de validation + +Vous pouvez aussi rajouter un second paramètre `min_length` : + +```Python hl_lines="9" +{!../../../docs_src/query_params_str_validations/tutorial003.py!} +``` + +## Ajouter des validations par expressions régulières + +On peut définir une expression régulière à laquelle le paramètre doit correspondre : + +```Python hl_lines="10" +{!../../../docs_src/query_params_str_validations/tutorial004.py!} +``` + +Cette expression régulière vérifie que la valeur passée comme paramètre : + +* `^` : commence avec les caractères qui suivent, avec aucun caractère avant ceux-là. +* `fixedquery` : a pour valeur exacte `fixedquery`. +* `$` : se termine directement ensuite, n'a pas d'autres caractères après `fixedquery`. + +Si vous vous sentez perdu avec le concept d'**expression régulière**, pas d'inquiétudes. Il s'agit d'une notion difficile pour beaucoup, et l'on peut déjà réussir à faire beaucoup sans jamais avoir à les manipuler. + +Mais si vous décidez d'apprendre à les utiliser, sachez qu'ensuite vous pouvez les utiliser directement dans **FastAPI**. + +## Valeurs par défaut + +De la même façon que vous pouvez passer `None` comme premier argument pour l'utiliser comme valeur par défaut, vous pouvez passer d'autres valeurs. + +Disons que vous déclarez le paramètre `q` comme ayant une longueur minimale de `3`, et une valeur par défaut étant `"fixedquery"` : + +```Python hl_lines="7" +{!../../../docs_src/query_params_str_validations/tutorial005.py!} +``` + +!!! note "Rappel" + Avoir une valeur par défaut rend le paramètre optionnel. + +## Rendre ce paramètre requis + +Quand on ne déclare ni validation, ni métadonnée, on peut rendre le paramètre `q` requis en ne lui déclarant juste aucune valeur par défaut : + +```Python +q: str +``` + +à la place de : + +```Python +q: Union[str, None] = None +``` + +Mais maintenant, on déclare `q` avec `Query`, comme ceci : + +```Python +q: Union[str, None] = Query(default=None, min_length=3) +``` + +Donc pour déclarer une valeur comme requise tout en utilisant `Query`, il faut utiliser `...` comme premier argument : + +```Python hl_lines="7" +{!../../../docs_src/query_params_str_validations/tutorial006.py!} +``` + +!!! info + Si vous n'avez jamais vu ce `...` auparavant : c'est une des constantes natives de Python appelée "Ellipsis". + +Cela indiquera à **FastAPI** que la présence de ce paramètre est obligatoire. + +## Liste de paramètres / valeurs multiples via Query + +Quand on définit un paramètre de requête explicitement avec `Query` on peut aussi déclarer qu'il reçoit une liste de valeur, ou des "valeurs multiples". + +Par exemple, pour déclarer un paramètre de requête `q` qui peut apparaître plusieurs fois dans une URL, on écrit : + +```Python hl_lines="9" +{!../../../docs_src/query_params_str_validations/tutorial011.py!} +``` + +Ce qui fait qu'avec une URL comme : + +``` +http://localhost:8000/items/?q=foo&q=bar +``` + +vous recevriez les valeurs des multiples paramètres de requête `q` (`foo` et `bar`) dans une `list` Python au sein de votre fonction de **path operation**, dans le paramètre de fonction `q`. + +Donc la réponse de cette URL serait : + +```JSON +{ + "q": [ + "foo", + "bar" + ] +} +``` + +!!! tip "Astuce" + Pour déclarer un paramètre de requête de type `list`, comme dans l'exemple ci-dessus, il faut explicitement utiliser `Query`, sinon cela sera interprété comme faisant partie du corps de la requête. + +La documentation sera donc mise à jour automatiquement pour autoriser plusieurs valeurs : + + + +### Combiner liste de paramètres et valeurs par défaut + +Et l'on peut aussi définir une liste de valeurs par défaut si aucune n'est fournie : + +```Python hl_lines="9" +{!../../../docs_src/query_params_str_validations/tutorial012.py!} +``` + +Si vous allez à : + +``` +http://localhost:8000/items/ +``` + +la valeur par défaut de `q` sera : `["foo", "bar"]` + +et la réponse sera : + +```JSON +{ + "q": [ + "foo", + "bar" + ] +} +``` + +#### Utiliser `list` + +Il est aussi possible d'utiliser directement `list` plutôt que `List[str]` : + +```Python hl_lines="7" +{!../../../docs_src/query_params_str_validations/tutorial013.py!} +``` + +!!! note + Dans ce cas-là, **FastAPI** ne vérifiera pas le contenu de la liste. + + Par exemple, `List[int]` vérifiera (et documentera) que la liste est bien entièrement composée d'entiers. Alors qu'un simple `list` ne ferait pas cette vérification. + +## Déclarer des métadonnées supplémentaires + +On peut aussi ajouter plus d'informations sur le paramètre. + +Ces informations seront incluses dans le schéma `OpenAPI` généré et utilisées par la documentation interactive ou les outils externes utilisés. + +!!! note + Gardez en tête que les outils externes utilisés ne supportent pas forcément tous parfaitement OpenAPI. + + Il se peut donc que certains d'entre eux n'utilisent pas toutes les métadonnées que vous avez déclarées pour le moment, bien que dans la plupart des cas, les fonctionnalités manquantes ont prévu d'être implémentées. + +Vous pouvez ajouter un `title` : + +```Python hl_lines="10" +{!../../../docs_src/query_params_str_validations/tutorial007.py!} +``` + +Et une `description` : + +```Python hl_lines="13" +{!../../../docs_src/query_params_str_validations/tutorial008.py!} +``` + +## Alias de paramètres + +Imaginez que vous vouliez que votre paramètre se nomme `item-query`. + +Comme dans la requête : + +``` +http://127.0.0.1:8000/items/?item-query=foobaritems +``` + +Mais `item-query` n'est pas un nom de variable valide en Python. + +Le nom le plus proche serait `item_query`. + +Mais vous avez vraiment envie que ce soit exactement `item-query`... + +Pour cela vous pouvez déclarer un `alias`, et cet alias est ce qui sera utilisé pour trouver la valeur du paramètre : + +```Python hl_lines="9" +{!../../../docs_src/query_params_str_validations/tutorial009.py!} +``` + +## Déprécier des paramètres + +Disons que vous ne vouliez plus utiliser ce paramètre désormais. + +Il faut qu'il continue à exister pendant un certain temps car vos clients l'utilisent, mais vous voulez que la documentation mentionne clairement que ce paramètre est déprécié. + +On utilise alors l'argument `deprecated=True` de `Query` : + +```Python hl_lines="18" +{!../../../docs_src/query_params_str_validations/tutorial010.py!} +``` + +La documentation le présentera comme il suit : + + + +## Pour résumer + +Il est possible d'ajouter des validateurs et métadonnées pour vos paramètres. + +Validateurs et métadonnées génériques: + +* `alias` +* `title` +* `description` +* `deprecated` + +Validateurs spécifiques aux chaînes de caractères : + +* `min_length` +* `max_length` +* `regex` + +Parmi ces exemples, vous avez pu voir comment déclarer des validateurs pour les chaînes de caractères. + +Dans les prochains chapitres, vous verrez comment déclarer des validateurs pour d'autres types, comme les nombres. diff --git a/docs/fr/docs/tutorial/query-params.md b/docs/fr/docs/tutorial/query-params.md index 7bf3b9e7942e5..962135f63eebd 100644 --- a/docs/fr/docs/tutorial/query-params.md +++ b/docs/fr/docs/tutorial/query-params.md @@ -75,7 +75,7 @@ Ici, le paramètre `q` sera optionnel, et aura `None` comme valeur par défaut. !!! note **FastAPI** saura que `q` est optionnel grâce au `=None`. - Le `Optional` dans `Optional[str]` n'est pas utilisé par **FastAPI** (**FastAPI** n'en utilisera que la partie `str`), mais il servira tout de même à votre editeur de texte pour détecter des erreurs dans votre code. + Le `Optional` dans `Optional[str]` n'est pas utilisé par **FastAPI** (**FastAPI** n'en utilisera que la partie `str`), mais il servira tout de même à votre éditeur de texte pour détecter des erreurs dans votre code. ## Conversion des types des paramètres de requête diff --git a/docs/he/docs/index.md b/docs/he/docs/index.md index 802dbe8b5d0b7..335a227436f81 100644 --- a/docs/he/docs/index.md +++ b/docs/he/docs/index.md @@ -115,7 +115,7 @@ FastAPI היא תשתית רשת מודרנית ומהירה (ביצועים ג FastAPI עומדת על כתפי ענקיות: - Starlette לחלקי הרשת. -- Pydantic לחלקי המידע. +- Pydantic לחלקי המידע. ## התקנה @@ -446,7 +446,7 @@ item: Item - httpx - דרוש אם ברצונכם להשתמש ב - `TestClient`. - jinja2 - דרוש אם ברצונכם להשתמש בברירת המחדל של תצורת הטמפלייטים. -- python-multipart - דרוש אם ברצונכם לתמוך ב "פרסור" טפסים, באצמעות request.form(). +- python-multipart - דרוש אם ברצונכם לתמוך ב "פרסור" טפסים, באצמעות request.form(). - itsdangerous - דרוש אם ברצונכם להשתמש ב - `SessionMiddleware`. - pyyaml - דרוש אם ברצונכם להשתמש ב - `SchemaGenerator` של Starlette (כנראה שאתם לא צריכים את זה עם FastAPI). - ujson - דרוש אם ברצונכם להשתמש ב - `UJSONResponse`. diff --git a/docs/hu/docs/index.md b/docs/hu/docs/index.md new file mode 100644 index 0000000000000..75ea88c4d8095 --- /dev/null +++ b/docs/hu/docs/index.md @@ -0,0 +1,469 @@ +

+ FastAPI +

+

+ FastAPI keretrendszer, nagy teljesítmény, könnyen tanulható, gyorsan kódolható, productionre kész +

+

+ + Test + + + Coverage + + + Package version + + + Supported Python versions + +

+ +--- + +**Dokumentáció**: https://fastapi.tiangolo.com + +**Forrás kód**: https://github.com/tiangolo/fastapi + +--- +A FastAPI egy modern, gyors (nagy teljesítményű), webes keretrendszer API-ok építéséhez Python 3.8+-al, a Python szabványos típusjelöléseire építve. + + +Kulcs funkciók: + +* **Gyors**: Nagyon nagy teljesítmény, a **NodeJS**-el és a **Go**-val egyenrangú (a Starlettenek és a Pydantic-nek köszönhetően). [Az egyik leggyorsabb Python keretrendszer](#performance). +* **Gyorsan kódolható**: A funkciók fejlesztési sebességét 200-300 százalékkal megnöveli. * +* **Kevesebb hiba**: Körülbelül 40%-al csökkenti az emberi (fejlesztői) hibák számát. * +* **Intuitív**: Kiváló szerkesztő támogatás. Kiegészítés mindenhol. Kevesebb hibakereséssel töltött idő. +* **Egyszerű**: Egyszerű tanulásra és használatra tervezve. Kevesebb dokumentáció olvasással töltött idő. +* **Rövid**: Kód duplikáció minimalizálása. Több funkció minden paraméter deklarálásával. Kevesebb hiba. +* **Robosztus**: Production ready kód. Automatikus interaktív dokumentáció val. +* **Szabvány alapú**: Az API-ok nyílt szabványaira alapuló (és azokkal teljesen kompatibilis): OpenAPI (korábban Swagger néven ismert) és a JSON Schema. + +* Egy production alkalmazásokat építő belső fejlesztői csapat tesztjein alapuló becslés. + +## Szponzorok + + + +{% if sponsors %} +{% for sponsor in sponsors.gold -%} + +{% endfor -%} +{%- for sponsor in sponsors.silver -%} + +{% endfor %} +{% endif %} + + + +További szponzorok + +## Vélemények + +"_[...] 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._" + +
Kabir Khan - Microsoft (ref)
+ +--- + +"_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!_" + +
Brian Okken - Python Bytes podcast host (ref)
+ +--- + +"_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._" + +
Timothy Crosley - Hug creator (ref)
+ +--- + +"_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 [...]_" + +
Ines Montani - Matthew Honnibal - Explosion AI founders - spaCy creators (ref) - (ref)
+ +--- + +"_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._" + +
Deon Pillsbury - Cisco (ref)
+ +--- + +## **Typer**, a CLI-ok FastAPI-ja + + + +Ha egy olyan CLI alkalmazást fejlesztesz amit a parancssorban kell használni webes API helyett, tekintsd meg: **Typer**. + +**Typer** a FastAPI kistestvére. A **CLI-k FastAPI-ja**. ⌨️ 🚀 + +## Követelmények + +Python 3.8+ + +A FastAPI óriások vállán áll: + +* Starlette a webes részekhez. +* Pydantic az adat részekhez. + +## Telepítés + +
+ +```console +$ pip install fastapi + +---> 100% +``` + +
+ +A production-höz egy ASGI szerverre is szükség lesz, mint például az Uvicorn vagy a Hypercorn. + +
+ +```console +$ pip install "uvicorn[standard]" + +---> 100% +``` + +
+ +## Példa + +### Hozd létre + +* Hozz létre a `main.py` fájlt a következő tartalommal: + +```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} +``` + +
+Vagy használd az async def-et... + +Ha a kódod `async` / `await`-et, használ `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} +``` + +**Megjegyzés**: + +Ha nem tudod, tekintsd meg a _"Sietsz?"_ szekciót `async` és `await`-ről dokumentációba. + +
+ +### Futtasd le + +Indítsd el a szervert a következő paranccsal: + +
+ +```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. +``` + +
+ +
+A parancsról uvicorn main:app --reload... + +A `uvicorn main:app` parancs a következőre utal: + +* `main`: fájl `main.py` (a Python "modul"). +* `app`: a `main.py`-ban a `app = FastAPI()` sorral létrehozott objektum. +* `--reload`: kód változtatás esetén újra indítja a szervert. Csak fejlesztés közben használandó. + +
+ +### Ellenőrizd + +Nyisd meg a böngésződ a következő címen: http://127.0.0.1:8000/items/5?q=somequery. + +A következő JSON választ fogod látni: + +```JSON +{"item_id": 5, "q": "somequery"} +``` + +Máris létrehoztál egy API-t ami: + +* HTTP kéréseket fogad a `/` és `/items/{item_id}` _útvonalakon_. +* Mindkét _útvonal_ a `GET` műveletet használja (másik elnevezés: HTTP _metódus_). +* A `/items/{item_id}` _útvonalnak_ van egy _path paramétere_, az `item_id`, aminek `int` típusúnak kell lennie. +* A `/items/{item_id}` _útvonalnak_ még van egy opcionális, `str` típusú _query paramétere_ is, a `q`. + +### Interaktív API dokumentáció + +Most nyisd meg a http://127.0.0.1:8000/docs címet. + +Az automatikus interaktív API dokumentációt fogod látni (amit a Swagger UI-al hozunk létre): + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +### Alternatív API dokumentáció + +És most menj el a http://127.0.0.1:8000/redoc címre. + +Az alternatív automatikus dokumentációt fogod látni. (lásd ReDoc): + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +## Példa frissítése + +Módosítsuk a `main.py` fájlt, hogy `PUT` kérések esetén tudjon body-t fogadni. + +Deklaráld a body-t standard Python típusokkal, a Pydantic-nak köszönhetően. + +```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} +``` + +A szerver automatikusan újraindul (mert hozzáadtuk a --reload paramétert a fenti `uvicorn` parancshoz). + +### Interaktív API dokumentáció frissítése + +Most menj el a http://127.0.0.1:8000/docs címre. + +* Az interaktív API dokumentáció automatikusan frissült így már benne van az új body. + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) + +* Kattints rá a "Try it out" gombra, ennek segítségével kitöltheted a paramétereket és közvetlen használhatod az API-t: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png) + +* Ezután kattints az "Execute" gompra, a felhasználói felület kommunikálni fog az API-oddal. Elküldi a paramétereket és a visszakapott választ megmutatja a képernyődön. + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png) + +### Alternatív API dokumentáció frissítés + +Most menj el a http://127.0.0.1:8000/redoc címre. + +* Az alternatív dokumentáció szintúgy tükrözni fogja az új kérési paraméter és body-t. + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) + +### Összefoglalás + +Összegzésül, deklarálod **egyszer** a paraméterek, body, stb típusát funkciós paraméterekként. + +Ezt standard modern Python típusokkal csinálod. + +Nem kell új szintaxist, vagy specifikus könyvtár mert metódósait, stb. megtanulnod. + +Csak standard **Python 3.8+**. + +Például egy `int`-nek: + +```Python +item_id: int +``` + +Egy komplexebb `Item` modellnek: + +```Python +item: Item +``` + +... És csupán egy deklarációval megkapod a: + +* Szerkesztő támogatást, beleértve: + * Szövegkiegészítés. + * Típus ellenőrzés. +* Adatok validációja: + * Automatikus és érthető hibák amikor az adatok hibásak. + * Validáció mélyen ágyazott objektumok esetén is. +* Bemeneti adatok átváltása : a hálózatról érkező Python adatokká és típusokká. Adatok olvasása következő forrásokból: + * JSON. + * Cím paraméterek. + * Query paraméterek. + * Cookie-k. + * Header-ök. + * Formok. + * Fájlok. +* Kimeneti adatok átváltása: Python adatok is típusokról hálózati adatokká: + * válts át Python típusokat (`str`, `int`, `float`, `bool`, `list`, etc). + * `datetime` csak objektumokat. + * `UUID` objektumokat. + * Adatbázis modelleket. + * ...És sok mást. +* Automatikus interaktív dokumentáció, beleértve két alternatív dokumentációt is: + * Swagger UI. + * ReDoc. + +--- + +Visszatérve az előző kód példához. A **FastAPI**: + +* Validálja hogy van egy `item_id` mező a `GET` és `PUT` kérésekben. +* Validálja hogy az `item_id` `int` típusú a `GET` és `PUT` kérésekben. + * Ha nem akkor látni fogunk egy tiszta hibát ezzel kapcsolatban. +* ellenőrzi hogyha van egy opcionális query paraméter `q` névvel (azaz `http://127.0.0.1:8000/items/foo?q=somequery`) `GET` kérések esetén. + * Mivel a `q` paraméter `= None`-al van deklarálva, ezért opcionális. + * `None` nélkül ez a mező kötelező lenne (mint például a body `PUT` kérések esetén). +* a `/items/{item_id}` címre érkező `PUT` kérések esetén, a JSON-t a következőképpen olvassa be: + * Ellenőrzi hogy létezik a kötelező `name` nevű attribútum és `string`. + * Ellenőrzi hogy létezik a kötelező `price` nevű attribútum és `float`. + * Ellenőrzi hogy létezik a `is_offer` nevű opcionális paraméter, ami ha létezik akkor `bool` + * Ez ágyazott JSON objektumokkal is működik +* JSONről való automatikus konvertálás. +* dokumentáljuk mindent OpenAPI-al amit használható: + * Interaktív dokumentációs rendszerekkel. + * Automatikus kliens kód generáló a rendszerekkel, több nyelven. +* Hozzá tartozik kettő interaktív dokumentációs web felület. + +--- + +Eddig csak a felszínt kapargattuk, de a lényeg hogy most már könnyebben érthető hogyan működik. + +Próbáld kicserélni a következő sorban: + +```Python + return {"item_name": item.name, "item_id": item_id} +``` + +...ezt: + +```Python + ... "item_name": item.name ... +``` + +...erre: + +```Python + ... "item_price": item.price ... +``` + +... És figyeld meg hogy a szerkesztő automatikusan tudni fogja a típusokat és kiegészíti azokat: + +![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) + +Teljesebb példákért és funkciókért tekintsd meg a Tutorial - User Guide -t. + +**Spoiler veszély**: a Tutorial - User Guidehoz tartozik: + +* **Paraméterek** deklarációja különböző helyekről: **header-ök**, **cookie-k**, **form mezők** és **fájlok**. +* Hogyan állíts be **validációs feltételeket** mint a `maximum_length` vagy a `regex`. +* Nagyon hatékony és erős **Függőség Injekció** rendszerek. +* Biztonság és autentikáció beleértve, **OAuth2**, **JWT tokens** és **HTTP Basic** támogatást. +* Több haladó (de ugyanannyira könnyű) technika **mélyen ágyazott JSON modellek deklarációjára** (Pydantic-nek köszönhetően). +* **GraphQL** integráció Strawberry-vel és más könyvtárakkal. +* több extra funkció (Starlette-nek köszönhetően) pl.: + * **WebSockets** + * rendkívül könnyű tesztek HTTPX és `pytest` alapokra építve + * **CORS** + * **Cookie Sessions** + * ...és több. + +## Teljesítmény + +A független TechEmpower benchmarkok szerint az Uvicorn alatt futó **FastAPI** alkalmazások az egyik leggyorsabb Python keretrendszerek közé tartoznak, éppen lemaradva a Starlette és az Uvicorn (melyeket a FastAPI belsőleg használ) mögött.(*) + +Ezeknek a további megértéséhez: Benchmarks. + +## Opcionális követelmények + +Pydantic által használt: + +* email_validator - e-mail validációkra. +* pydantic-settings - Beállítások követésére. +* pydantic-extra-types - Extra típusok Pydantic-hoz. + +Starlette által használt: + +* httpx - Követelmény ha a `TestClient`-et akarod használni. +* jinja2 - Követelmény ha az alap template konfigurációt akarod használni. +* python-multipart - Követelmény ha "parsing"-ot akarsz támogatni, `request.form()`-al. +* itsdangerous - Követelmény `SessionMiddleware` támogatáshoz. +* pyyaml - Követelmény a Starlette `SchemaGenerator`-ának támogatásához (valószínűleg erre nincs szükség FastAPI használása esetén). +* ujson - Követelmény ha `UJSONResponse`-t akarsz használni. + +FastAPI / Starlette által használt + +* uvicorn - Szerverekhez amíg betöltik és szolgáltatják az applikációdat. +* orjson - Követelmény ha `ORJSONResponse`-t akarsz használni. + +Ezeket mind telepítheted a `pip install "fastapi[all]"` paranccsal. + +## Licensz +Ez a projekt az MIT license, licensz alatt fut diff --git a/docs/hu/mkdocs.yml b/docs/hu/mkdocs.yml new file mode 100644 index 0000000000000..de18856f445aa --- /dev/null +++ b/docs/hu/mkdocs.yml @@ -0,0 +1 @@ +INHERIT: ../en/mkdocs.yml diff --git a/docs/id/docs/index.md b/docs/id/docs/index.md deleted file mode 100644 index ed551f9102d1e..0000000000000 --- a/docs/id/docs/index.md +++ /dev/null @@ -1,465 +0,0 @@ - -{!../../../docs/missing-translation.md!} - - -

- FastAPI -

-

- FastAPI framework, high performance, easy to learn, fast to code, ready for production -

-

- - Test - - - Coverage - - - Package version - -

- ---- - -**Documentation**: https://fastapi.tiangolo.com - -**Source Code**: https://github.com/tiangolo/fastapi - ---- - -FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints. - -The key features are: - -* **Fast**: Very high performance, on par with **NodeJS** and **Go** (thanks to Starlette and Pydantic). [One of the fastest Python frameworks available](#performance). - -* **Fast to code**: Increase the speed to develop features by about 200% to 300%. * -* **Fewer bugs**: Reduce about 40% of human (developer) induced errors. * -* **Intuitive**: Great editor support. Completion everywhere. Less time debugging. -* **Easy**: Designed to be easy to use and learn. Less time reading docs. -* **Short**: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs. -* **Robust**: Get production-ready code. With automatic interactive documentation. -* **Standards-based**: Based on (and fully compatible with) the open standards for APIs: OpenAPI (previously known as Swagger) and JSON Schema. - -* estimation based on tests on an internal development team, building production applications. - -## Sponsors - - - -{% if sponsors %} -{% for sponsor in sponsors.gold -%} - -{% endfor -%} -{%- for sponsor in sponsors.silver -%} - -{% endfor %} -{% endif %} - - - -Other sponsors - -## Opinions - -"_[...] I'm using **FastAPI** a ton these days. [...] I'm actually planning to use it for all of my team's **ML services at Microsoft**. Some of them are getting integrated into the core **Windows** product and some **Office** products._" - -
Kabir Khan - Microsoft (ref)
- ---- - -"_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!_" - -
Brian Okken - Python Bytes podcast host (ref)
- ---- - -"_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._" - -
Timothy Crosley - Hug creator (ref)
- ---- - -"_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 [...]_" - -
Ines Montani - Matthew Honnibal - Explosion AI founders - spaCy creators (ref) - (ref)
- ---- - -## **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 - -
- -```console -$ pip install fastapi - ----> 100% -``` - -
- -You will also need an ASGI server, for production such as Uvicorn or Hypercorn. - -
- -```console -$ pip install "uvicorn[standard]" - ----> 100% -``` - -
- -## Example - -### Create it - -* Create a file `main.py` with: - -```Python -from typing import Optional - -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: Optional[str] = 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 Optional - -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: Optional[str] = None): - return {"item_id": item_id, "q": q} -``` - -**Note**: - -If you don't know, check the _"In a hurry?"_ section about `async` and `await` in the docs. - -
- -### Run it - -Run the server with: - -
- -```console -$ uvicorn main:app --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -INFO: Started reloader process [28720] -INFO: Started server process [28722] -INFO: Waiting for application startup. -INFO: Application startup complete. -``` - -
- -
-About the command uvicorn main:app --reload... - -The command `uvicorn main:app` refers to: - -* `main`: the file `main.py` (the Python "module"). -* `app`: the object created inside of `main.py` with the line `app = FastAPI()`. -* `--reload`: make the server restart after code changes. Only do this for development. - -
- -### Check it - -Open your browser at http://127.0.0.1:8000/items/5?q=somequery. - -You will see the JSON response as: - -```JSON -{"item_id": 5, "q": "somequery"} -``` - -You already created an API that: - -* Receives HTTP requests in the _paths_ `/` and `/items/{item_id}`. -* Both _paths_ take `GET` operations (also known as HTTP _methods_). -* The _path_ `/items/{item_id}` has a _path parameter_ `item_id` that should be an `int`. -* The _path_ `/items/{item_id}` has an optional `str` _query parameter_ `q`. - -### Interactive API docs - -Now go to http://127.0.0.1:8000/docs. - -You will see the automatic interactive API documentation (provided by Swagger UI): - -![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) - -### Alternative API docs - -And now, go to http://127.0.0.1:8000/redoc. - -You will see the alternative automatic documentation (provided by ReDoc): - -![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) - -## Example upgrade - -Now modify the file `main.py` to receive a body from a `PUT` request. - -Declare the body using standard Python types, thanks to Pydantic. - -```Python hl_lines="4 9-12 25-27" -from typing import Optional - -from fastapi import FastAPI -from pydantic import BaseModel - -app = FastAPI() - - -class Item(BaseModel): - name: str - price: float - is_offer: Optional[bool] = None - - -@app.get("/") -def read_root(): - return {"Hello": "World"} - - -@app.get("/items/{item_id}") -def read_item(item_id: int, q: Optional[str] = None): - return {"item_id": item_id, "q": q} - - -@app.put("/items/{item_id}") -def update_item(item_id: int, item: Item): - return {"item_name": item.name, "item_id": item_id} -``` - -The server should reload automatically (because you added `--reload` to the `uvicorn` command above). - -### Interactive API docs upgrade - -Now go to http://127.0.0.1:8000/docs. - -* The interactive API documentation will be automatically updated, including the new body: - -![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) - -* Click on the button "Try it out", it allows you to fill the parameters and directly interact with the API: - -![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png) - -* Then click on the "Execute" button, the user interface will communicate with your API, send the parameters, get the results and show them on the screen: - -![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png) - -### Alternative API docs upgrade - -And now, go to http://127.0.0.1:8000/redoc. - -* The alternative documentation will also reflect the new query parameter and body: - -![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) - -### Recap - -In summary, you declare **once** the types of parameters, body, etc. as function parameters. - -You do that with standard modern Python types. - -You don't have to learn a new syntax, the methods or classes of a specific library, etc. - -Just standard **Python 3.6+**. - -For example, for an `int`: - -```Python -item_id: int -``` - -or for a more complex `Item` model: - -```Python -item: Item -``` - -...and with that single declaration you get: - -* Editor support, including: - * Completion. - * Type checks. -* Validation of data: - * Automatic and clear errors when the data is invalid. - * Validation even for deeply nested JSON objects. -* Conversion of input data: coming from the network to Python data and types. Reading from: - * JSON. - * Path parameters. - * Query parameters. - * Cookies. - * Headers. - * Forms. - * Files. -* Conversion of output data: converting from Python data and types to network data (as JSON): - * Convert Python types (`str`, `int`, `float`, `bool`, `list`, etc). - * `datetime` objects. - * `UUID` objects. - * Database models. - * ...and many more. -* Automatic interactive API documentation, including 2 alternative user interfaces: - * Swagger UI. - * ReDoc. - ---- - -Coming back to the previous code example, **FastAPI** will: - -* Validate that there is an `item_id` in the path for `GET` and `PUT` requests. -* Validate that the `item_id` is of type `int` for `GET` and `PUT` requests. - * If it is not, the client will see a useful, clear error. -* Check if there is an optional query parameter named `q` (as in `http://127.0.0.1:8000/items/foo?q=somequery`) for `GET` requests. - * As the `q` parameter is declared with `= None`, it is optional. - * Without the `None` it would be required (as is the body in the case with `PUT`). -* For `PUT` requests to `/items/{item_id}`, Read the body as JSON: - * Check that it has a required attribute `name` that should be a `str`. - * Check that it has a required attribute `price` that has to be a `float`. - * Check that it has an optional attribute `is_offer`, that should be a `bool`, if present. - * All this would also work for deeply nested JSON objects. -* Convert from and to JSON automatically. -* Document everything with OpenAPI, that can be used by: - * Interactive documentation systems. - * Automatic client code generation systems, for many languages. -* Provide 2 interactive documentation web interfaces directly. - ---- - -We just scratched the surface, but you already get the idea of how it all works. - -Try changing the line with: - -```Python - return {"item_name": item.name, "item_id": item_id} -``` - -...from: - -```Python - ... "item_name": item.name ... -``` - -...to: - -```Python - ... "item_price": item.price ... -``` - -...and see how your editor will auto-complete the attributes and know their types: - -![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) - -For a more complete example including more features, see the Tutorial - User Guide. - -**Spoiler alert**: the tutorial - user guide includes: - -* Declaration of **parameters** from other different places as: **headers**, **cookies**, **form fields** and **files**. -* How to set **validation constraints** as `maximum_length` or `regex`. -* A very powerful and easy to use **Dependency Injection** system. -* Security and authentication, including support for **OAuth2** with **JWT tokens** and **HTTP Basic** auth. -* More advanced (but equally easy) techniques for declaring **deeply nested JSON models** (thanks to Pydantic). -* Many extra features (thanks to Starlette) as: - * **WebSockets** - * **GraphQL** - * 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: - -* 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). -* graphene - Required for `GraphQLApp` support. -* 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/it/docs/index.md b/docs/it/docs/index.md new file mode 100644 index 0000000000000..a69008d2b4c89 --- /dev/null +++ b/docs/it/docs/index.md @@ -0,0 +1,464 @@ + +{!../../../docs/missing-translation.md!} + + +

+ FastAPI +

+

+ FastAPI framework, alte prestazioni, facile da imparare, rapido da implementare, pronto per il rilascio in produzione +

+

+ + Build Status + + + Coverage + + + Package version + +

+ +--- + +**Documentazione**: https://fastapi.tiangolo.com + +**Codice Sorgente**: https://github.com/tiangolo/fastapi + +--- + +FastAPI è un web framework moderno e veloce (a prestazioni elevate) che serve a creare API con Python 3.6+ basato sulle annotazioni di tipo di Python. + +Le sue caratteristiche principali sono: + +* **Velocità**: Prestazioni molto elevate, alla pari di **NodeJS** e **Go** (grazie a Starlette e Pydantic). [Uno dei framework Python più veloci in circolazione](#performance). +* **Veloce da programmare**: Velocizza il lavoro consentendo il rilascio di nuove funzionalità tra il 200% e il 300% più rapidamente. * +* **Meno bug**: Riduce di circa il 40% gli errori che commettono gli sviluppatori durante la scrittura del codice. * +* **Intuitivo**: Grande supporto per gli editor di testo con autocompletamento in ogni dove. In questo modo si può dedicare meno tempo al debugging. +* **Facile**: Progettato per essere facile da usare e imparare. Si riduce il tempo da dedicare alla lettura della documentazione. +* **Sintentico**: Minimizza la duplicazione di codice. Molteplici funzionalità, ognuna con la propria dichiarazione dei parametri. Meno errori. +* **Robusto**: Crea codice pronto per la produzione con documentazione automatica interattiva. +* **Basato sugli standard**: Basato su (e completamente compatibile con) gli open standard per le API: OpenAPI (precedentemente Swagger) e JSON Schema. + +* Stima basata sull'esito di test eseguiti su codice sorgente di applicazioni rilasciate in produzione da un team interno di sviluppatori. + +## Sponsor + + + +{% if sponsors %} +{% for sponsor in sponsors.gold -%} + +{% endfor -%} +{%- for sponsor in sponsors.silver -%} + +{% endfor %} +{% endif %} + + + +Altri sponsor + +## Recensioni + +"_[...] 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._" + +
Kabir Khan - Microsoft (ref)
+ +--- + +"_We adopted the **FastAPI** library to spawn a **REST** server that can be queried to obtain **predictions**. [for Ludwig]_" + +
Piero Molino, Yaroslav Dudin, e 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!_" + +
Brian Okken - Python Bytes podcast host (ref)
+ +--- + +"_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._" + +
Timothy Crosley - Hug creator (ref)
+ +--- + +"_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 [...]_" + +
Ines Montani - Matthew Honnibal - Explosion AI founders - spaCy creators (ref) - (ref)
+ +--- + +## **Typer**, la FastAPI delle CLI + + + +Se stai sviluppando un'app CLI da usare nel terminale invece che una web API, ti consigliamo **Typer**. + +**Typer** è il fratello minore di FastAPI. Ed è stato ideato per essere la **FastAPI delle CLI**. ⌨️ 🚀 + +## Requisiti + +Python 3.6+ + +FastAPI è basata su importanti librerie: + +* Starlette per le parti web. +* Pydantic per le parti dei dati. + +## Installazione + +
+ +```console +$ pip install fastapi + +---> 100% +``` + +
+ +Per il rilascio in produzione, sarà necessario un server ASGI come Uvicorn oppure Hypercorn. + +
+ +```console +$ pip install uvicorn[standard] + +---> 100% +``` + +
+ +## Esempio + +### Crea un file + +* Crea un file `main.py` con: + +```Python +from fastapi import FastAPI +from typing import Optional + +app = FastAPI() + + +@app.get("/") +def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +def read_item(item_id: int, q: str = Optional[None]): + return {"item_id": item_id, "q": q} +``` + +
+Oppure usa async def... + +Se il tuo codice usa `async` / `await`, allora usa `async def`: + +```Python hl_lines="7 12" +from fastapi import FastAPI +from typing import Optional + +app = FastAPI() + + +@app.get("/") +async def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +async def read_item(item_id: int, q: Optional[str] = None): + return {"item_id": item_id, "q": q} +``` + +**Nota**: + +e vuoi approfondire, consulta la sezione _"In a hurry?"_ su `async` e `await` nella documentazione. + +
+ +### Esegui il server + +Puoi far partire il server così: + +
+ +```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. +``` + +
+ +
+Informazioni sul comando uvicorn main:app --reload... + +Vediamo il comando `uvicorn main:app` in dettaglio: + +* `main`: il file `main.py` (il "modulo" Python). +* `app`: l'oggetto creato dentro `main.py` con la riga di codice `app = FastAPI()`. +* `--reload`: ricarica il server se vengono rilevati cambiamenti del codice. Usalo solo durante la fase di sviluppo. + +
+ +### Testa l'API + +Apri il browser all'indirizzo http://127.0.0.1:8000/items/5?q=somequery. + +Vedrai la seguente risposta JSON: + +```JSON +{"item_id": 5, "q": "somequery"} +``` + +Hai appena creato un'API che: + +* Riceve richieste HTTP sui _paths_ `/` and `/items/{item_id}`. +* Entrambi i _paths_ accettano`GET` operations (conosciuti anche come HTTP _methods_). +* Il _path_ `/items/{item_id}` ha un _path parameter_ `item_id` che deve essere un `int`. +* Il _path_ `/items/{item_id}` ha una `str` _query parameter_ `q`. + +### Documentazione interattiva dell'API + +Adesso vai all'indirizzo http://127.0.0.1:8000/docs. + +Vedrai la documentazione interattiva dell'API (offerta da Swagger UI): + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +### Documentazione interattiva alternativa + +Adesso accedi all'url http://127.0.0.1:8000/redoc. + +Vedrai la documentazione interattiva dell'API (offerta da ReDoc): + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +## Esempio più avanzato + +Adesso modifica il file `main.py` per ricevere un _body_ da una richiesta `PUT`. + +Dichiara il _body_ usando le annotazioni di tipo standard di Python, grazie a Pydantic. + +```Python hl_lines="2 7-10 23-25" +from fastapi import FastAPI +from pydantic import BaseModel +from typing import Optional + +app = FastAPI() + + +class Item(BaseModel): + name: str + price: float + is_offer: bool = Optional[None] + + +@app.get("/") +def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +def read_item(item_id: int, q: Optional[str] = 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} +``` + +Il server dovrebbe ricaricarsi in automatico (perché hai specificato `--reload` al comando `uvicorn` lanciato precedentemente). + +### Aggiornamento della documentazione interattiva + +Adesso vai su http://127.0.0.1:8000/docs. + +* La documentazione interattiva dell'API verrà automaticamente aggiornata, includendo il nuovo _body_: + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) + +* Fai click sul pulsante "Try it out", che ti permette di inserire i parametri per interagire direttamente con l'API: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png) + +* Successivamente, premi sul pulsante "Execute". L'interfaccia utente comunicherà con la tua API, invierà i parametri, riceverà i risultati della richiesta, e li mostrerà sullo schermo: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png) + +### Aggiornamento della documentazione alternativa + +Ora vai su http://127.0.0.1:8000/redoc. + +* Anche la documentazione alternativa dell'API mostrerà il nuovo parametro della query e il _body_: + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) + +### Riepilogo + +Ricapitolando, è sufficiente dichiarare **una sola volta** i tipi dei parametri, del body, ecc. come parametri di funzioni. + +Questo con le annotazioni per i tipi standard di Python. + +Non c'è bisogno di imparare una nuova sintassi, metodi o classi specifici a una libreria, ecc. + +È normalissimo **Python 3.6+**. + +Per esempio, per un `int`: + +```Python +item_id: int +``` + +o per un modello `Item` più complesso: + +```Python +item: Item +``` + +...e con quella singola dichiarazione hai in cambio: + +* Supporto per gli editor di testo, incluso: + * Autocompletamento. + * Controllo sulle annotazioni di tipo. +* Validazione dei dati: + * Errori chiari e automatici quando i dati sono invalidi. + * Validazione anche per gli oggetti JSON più complessi. +* Conversione dei dati di input: da risorse esterne a dati e tipi di Python. È possibile leggere da: + * JSON. + * Path parameters. + * Query parameters. + * Cookies. + * Headers. + * Form. + * File. +* Conversione dei dati di output: converte dati e tipi di Python a dati per la rete (come JSON): + * Converte i tipi di Python (`str`, `int`, `float`, `bool`, `list`, ecc). + * Oggetti `datetime`. + * Oggetti `UUID`. + * Modelli del database. + * ...e molto di più. +* Generazione di una documentazione dell'API interattiva, con scelta dell'interfaccia grafica: + * Swagger UI. + * ReDoc. + +--- + +Tornando al precedente esempio, **FastAPI**: + +* Validerà che esiste un `item_id` nel percorso delle richieste `GET` e `PUT`. +* Validerà che `item_id` sia di tipo `int` per le richieste `GET` e `PUT`. + * Se non lo è, il client vedrà un errore chiaro e utile. +* Controllerà se ci sia un parametro opzionale chiamato `q` (per esempio `http://127.0.0.1:8000/items/foo?q=somequery`) per le richieste `GET`. + * Siccome il parametro `q` è dichiarato con `= None`, è opzionale. + * Senza il `None` sarebbe stato obbligatorio (come per il body della richiesta `PUT`). +* Per le richieste `PUT` su `/items/{item_id}`, leggerà il body come JSON, questo comprende: + * verifica che la richiesta abbia un attributo obbligatorio `name` e che sia di tipo `str`. + * verifica che la richiesta abbia un attributo obbligatorio `price` e che sia di tipo `float`. + * verifica che la richiesta abbia un attributo opzionale `is_offer` e che sia di tipo `bool`, se presente. + * Tutto questo funzionerebbe anche con oggetti JSON più complessi. +* Convertirà *da* e *a* JSON automaticamente. +* Documenterà tutto con OpenAPI, che può essere usato per: + * Sistemi di documentazione interattivi. + * Sistemi di generazione di codice dal lato client, per molti linguaggi. +* Fornirà 2 interfacce di documentazione dell'API interattive. + +--- + +Questa è solo la punta dell'iceberg, ma dovresti avere già un'idea di come il tutto funzioni. + +Prova a cambiare questa riga di codice: + +```Python + return {"item_name": item.name, "item_id": item_id} +``` + +...da: + +```Python + ... "item_name": item.name ... +``` + +...a: + +```Python + ... "item_price": item.price ... +``` + +...e osserva come il tuo editor di testo autocompleterà gli attributi e sarà in grado di riconoscere i loro tipi: + +![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) + +Per un esempio più completo che mostra più funzionalità del framework, consulta Tutorial - Guida Utente. + +**Spoiler alert**: il tutorial - Guida Utente include: + +* Dichiarazione di **parameters** da altri posti diversi come: **headers**, **cookies**, **form fields** e **files**. +* Come stabilire **vincoli di validazione** come `maximum_length` o `regex`. +* Un sistema di **Dependency Injection** facile da usare e molto potente. +e potente. +* Sicurezza e autenticazione, incluso il supporto per **OAuth2** con **token JWT** e autenticazione **HTTP Basic**. +* Tecniche più avanzate (ma ugualmente semplici) per dichiarare **modelli JSON altamente nidificati** (grazie a Pydantic). +* E altre funzionalità (grazie a Starlette) come: + * **WebSockets** + * **GraphQL** + * test molto facili basati su `requests` e `pytest` + * **CORS** + * **Cookie Sessions** + * ...e altro ancora. + +## Prestazioni + +Benchmark indipendenti di TechEmpower mostrano che **FastAPI** basato su Uvicorn è uno dei framework Python più veloci in circolazione, solamente dietro a Starlette e Uvicorn (usate internamente da FastAPI). (*) + +Per approfondire, consulta la sezione Benchmarks. + +## Dipendenze opzionali + +Usate da Pydantic: + +* ujson - per un "parsing" di JSON più veloce. +* email_validator - per la validazione di email. + +Usate da Starlette: + +* requests - Richiesto se vuoi usare il `TestClient`. +* aiofiles - Richiesto se vuoi usare `FileResponse` o `StaticFiles`. +* jinja2 - Richiesto se vuoi usare la configurazione template di default. +* python-multipart - Richiesto se vuoi supportare il "parsing" con `request.form()`. +* itsdangerous - Richiesto per usare `SessionMiddleware`. +* pyyaml - Richiesto per il supporto dello `SchemaGenerator` di Starlette (probabilmente non ti serve con FastAPI). +* graphene - Richiesto per il supporto di `GraphQLApp`. +* ujson - Richiesto se vuoi usare `UJSONResponse`. + +Usate da FastAPI / Starlette: + +* uvicorn - per il server che carica e serve la tua applicazione. +* orjson - ichiesto se vuoi usare `ORJSONResponse`. + +Puoi installarle tutte con `pip install fastapi[all]`. + +## Licenza + +Questo progetto è concesso in licenza in base ai termini della licenza MIT. diff --git a/docs/it/mkdocs.yml b/docs/it/mkdocs.yml new file mode 100644 index 0000000000000..de18856f445aa --- /dev/null +++ b/docs/it/mkdocs.yml @@ -0,0 +1 @@ +INHERIT: ../en/mkdocs.yml diff --git a/docs/ja/docs/alternatives.md b/docs/ja/docs/alternatives.md index ca6b29a0776db..ce4b364080cda 100644 --- a/docs/ja/docs/alternatives.md +++ b/docs/ja/docs/alternatives.md @@ -342,7 +342,7 @@ OpenAPIやJSON Schemaのような標準に基づいたものではありませ ## **FastAPI**が利用しているもの -### Pydantic +### Pydantic Pydanticは、Pythonの型ヒントを元にデータのバリデーション、シリアライゼーション、 (JSON Schemaを使用した) ドキュメントを定義するライブラリです。 diff --git a/docs/ja/docs/deployment/concepts.md b/docs/ja/docs/deployment/concepts.md new file mode 100644 index 0000000000000..38cbca2192468 --- /dev/null +++ b/docs/ja/docs/deployment/concepts.md @@ -0,0 +1,323 @@ +# デプロイメントのコンセプト + +**FastAPI**を用いたアプリケーションをデプロイするとき、もしくはどのようなタイプのWeb APIであっても、おそらく気になるコンセプトがいくつかあります。 + +それらを活用することでアプリケーションを**デプロイするための最適な方法**を見つけることができます。 + +重要なコンセプトのいくつかを紹介します: + +* セキュリティ - HTTPS +* 起動時の実行 +* 再起動 +* レプリケーション(実行中のプロセス数) +* メモリー +* 開始前の事前のステップ + +これらが**デプロイメント**にどのような影響を与えるかを見ていきましょう。 + +最終的な目的は、**安全な方法で**APIクライアントに**サービスを提供**し、**中断を回避**するだけでなく、**計算リソース**(例えばリモートサーバー/仮想マシン)を可能な限り効率的に使用することです。🚀 + +この章では前述した**コンセプト**についてそれぞれ説明します。 + +この説明を通して、普段とは非常に異なる環境や存在しないであろう**将来の**環境に対し、デプロイの方法を決める上で必要な**直感**を与えてくれることを願っています。 + +これらのコンセプトを意識することにより、**あなた自身のAPI**をデプロイするための最適な方法を**評価**し、**設計**することができるようになるでしょう。 + +次の章では、FastAPIアプリケーションをデプロイするための**具体的なレシピ**を紹介します。 + +しかし、今はこれらの重要な**コンセプトに基づくアイデア**を確認しましょう。これらのコンセプトは、他のどのタイプのWeb APIにも当てはまります。💡 + +## セキュリティ - HTTPS + + +[前チャプターのHTTPSについて](./https.md){.internal-link target=_blank}では、HTTPSがどのようにAPIを暗号化するのかについて学びました。 + +通常、アプリケーションサーバにとって**外部の**コンポーネントである**TLS Termination Proxy**によって提供されることが一般的です。このプロキシは通信の暗号化を担当します。 + +さらにセキュアな通信において、HTTPS証明書の定期的な更新を行いますが、これはTLS Termination Proxyと同じコンポーネントが担当することもあれば、別のコンポーネントが担当することもあります。 + +### HTTPS 用ツールの例 +TLS Termination Proxyとして使用できるツールには以下のようなものがあります: + +* Traefik + * 証明書の更新を自動的に処理 ✨ +* Caddy + * 証明書の更新を自動的に処理 ✨ +* Nginx + * 証明書更新のためにCertbotのような外部コンポーネントを使用 +* HAProxy + * 証明書更新のためにCertbotのような外部コンポーネントを使用 +* Nginx のような Ingress Controller を持つ Kubernetes + * 証明書の更新に cert-manager のような外部コンポーネントを使用 +* クラウド・プロバイダーがサービスの一部として内部的に処理(下記を参照👇) + +もう1つの選択肢は、HTTPSのセットアップを含んだより多くの作業を行う**クラウド・サービス**を利用することです。 このサービスには制限があったり、料金が高くなったりする可能性があります。しかしその場合、TLS Termination Proxyを自分でセットアップする必要はないです。 + +次の章で具体例をいくつか紹介します。 + +--- + +次に考慮すべきコンセプトは、実際のAPIを実行するプログラム(例:Uvicorn)に関連するものすべてです。 + +## プログラム と プロセス + +私たちは「**プロセス**」という言葉についてたくさん話すので、その意味や「**プログラム**」という言葉との違いを明確にしておくと便利です。 + +### プログラムとは何か + +**プログラム**という言葉は、一般的にいろいろなものを表現するのに使われます: + +* プログラマが書く**コード**、**Pythonファイル** +* OSによって実行することができるファイル(例: `python`, `python.exe` or `uvicorn`) +* OS上で**実行**している間、CPUを使用し、メモリ上に何かを保存する特定のプログラム(**プロセス**とも呼ばれる) + +### プロセスとは何か + +**プロセス**という言葉は通常、より具体的な意味で使われ、OSで実行されているものだけを指します(先ほどの最後の説明のように): + +* OS上で**実行**している特定のプログラム + * これはファイルやコードを指すのではなく、OSによって**実行**され、管理されているものを指します。 +* どんなプログラムやコードも、それが**実行されているときにだけ機能**します。つまり、**プロセスとして実行されているときだけ**です。 +* プロセスは、ユーザーにあるいはOSによって、 **終了**(あるいは "kill")させることができます。その時点で、プロセスは実行/実行されることを停止し、それ以降は**何もできなくなります**。 +* コンピュータで実行されている各アプリケーションは、実行中のプログラムや各ウィンドウなど、その背後にいくつかのプロセスを持っています。そして通常、コンピュータが起動している間、**多くのプロセスが**同時に実行されています。 +* **同じプログラム**の**複数のプロセス**が同時に実行されていることがあります。 + +OSの「タスク・マネージャー」や「システム・モニター」(または同様のツール)を確認すれば、これらのプロセスの多くが実行されているの見ることができるでしょう。 + +例えば、同じブラウザプログラム(Firefox、Chrome、Edgeなど)を実行しているプロセスが複数あることがわかります。通常、1つのタブにつき1つのプロセスが実行され、さらに他のプロセスも実行されます。 + + + +--- + +さて、**プロセス**と**プログラム**という用語の違いを確認したところで、デプロイメントについて話を続けます。 + +## 起動時の実行 + +ほとんどの場合、Web APIを作成するときは、クライアントがいつでもアクセスできるように、**常に**中断されることなく**実行される**ことを望みます。もちろん、特定の状況でのみ実行させたい特別な理由がある場合は別ですが、その時間のほとんどは、常に実行され、**利用可能**であることを望みます。 + +### リモートサーバー上での実行 + +リモートサーバー(クラウドサーバー、仮想マシンなど)をセットアップするときにできる最も簡単なことは、ローカルで開発するときと同じように、Uvicorn(または同様のもの)を手動で実行することです。 この方法は**開発中**には役に立つと思われます。 + +しかし、サーバーへの接続が切れた場合、**実行中のプロセス**はおそらくダウンしてしまうでしょう。 + +そしてサーバーが再起動された場合(アップデートやクラウドプロバイダーからのマイグレーションの後など)、おそらくあなたはそれに**気づかないでしょう**。そのため、プロセスを手動で再起動しなければならないことすら気づかないでしょう。つまり、APIはダウンしたままなのです。😱 + +### 起動時に自動的に実行 + +一般的に、サーバープログラム(Uvicornなど)はサーバー起動時に自動的に開始され、**人の介入**を必要とせずに、APIと一緒にプロセスが常に実行されるようにしたいと思われます(UvicornがFastAPIアプリを実行するなど)。 + +### 別のプログラムの用意 + +これを実現するために、通常は**別のプログラム**を用意し、起動時にアプリケーションが実行されるようにします。そして多くの場合、他のコンポーネントやアプリケーション、例えばデータベースも実行されるようにします。 + +### 起動時に実行するツールの例 + +実行するツールの例をいくつか挙げます: + +* Docker +* Kubernetes +* Docker Compose +* Swarm モードによる Docker +* Systemd +* Supervisor +* クラウドプロバイダーがサービスの一部として内部的に処理 +* そのほか... + +次の章で、より具体的な例を挙げていきます。 + +## 再起動 + +起動時にアプリケーションが実行されることを確認するのと同様に、失敗後にアプリケーションが**再起動**されることも確認したいと思われます。 + +### 我々は間違いを犯す + +私たち人間は常に**間違い**を犯します。ソフトウェアには、ほとんど常に**バグ**があらゆる箇所に隠されています。🐛 + +### 小さなエラーは自動的に処理される + +FastAPIでWeb APIを構築する際に、コードにエラーがある場合、FastAPIは通常、エラーを引き起こした単一のリクエストにエラーを含めます。🛡 + +クライアントはそのリクエストに対して**500 Internal Server Error**を受け取りますが、アプリケーションは完全にクラッシュするのではなく、次のリクエストのために動作を続けます。 + +### 重大なエラー - クラッシュ + +しかしながら、**アプリケーション全体をクラッシュさせるようなコードを書いて**UvicornとPythonをクラッシュさせるようなケースもあるかもしれません。💥 + +それでも、ある箇所でエラーが発生したからといって、アプリケーションを停止させたままにしたくないでしょう。 少なくとも壊れていない*パスオペレーション*については、**実行し続けたい**はずです。 + +### クラッシュ後の再起動 + +しかし、実行中の**プロセス**をクラッシュさせるような本当にひどいエラーの場合、少なくとも2〜3回ほどプロセスを**再起動**させる外部コンポーネントが必要でしょう。 + +!!! tip + ...とはいえ、アプリケーション全体が**すぐにクラッシュする**のであれば、いつまでも再起動し続けるのは意味がないでしょう。しかし、その場合はおそらく開発中か少なくともデプロイ直後に気づくと思われます。 + + そこで、**将来**クラッシュする可能性があり、それでも再スタートさせることに意味があるような、主なケースに焦点を当ててみます。 + +あなたはおそらく**外部コンポーネント**がアプリケーションの再起動を担当することを望むと考えます。 なぜなら、その時点でUvicornとPythonを使った同じアプリケーションはすでにクラッシュしており、同じアプリケーションの同じコードに対して何もできないためです。 + +### 自動的に再起動するツールの例 + +ほとんどの場合、前述した**起動時にプログラムを実行する**ために使用されるツールは、自動で**再起動**することにも利用されます。 + +例えば、次のようなものがあります: + +* Docker +* Kubernetes +* Docker Compose +* Swarm モードによる Docker +* Systemd +* Supervisor +* クラウドプロバイダーがサービスの一部として内部的に処理 +* そのほか... + +## レプリケーション - プロセスとメモリー + +FastAPI アプリケーションでは、Uvicorn のようなサーバープログラムを使用し、**1つのプロセス**で1度に複数のクライアントに同時に対応できます。 + +しかし、多くの場合、複数のワーカー・プロセスを同時に実行したいと考えるでしょう。 + +### 複数のプロセス - Worker + +クライアントの数が単一のプロセスで処理できる数を超えており(たとえば仮想マシンがそれほど大きくない場合)、かつサーバーの CPU に**複数のコア**がある場合、同じアプリケーションで同時に**複数のプロセス**を実行させ、すべてのリクエストを分散させることができます。 + +同じAPIプログラムの**複数のプロセス**を実行する場合、それらは一般的に**Worker/ワーカー**と呼ばれます。 + +### ワーカー・プロセス と ポート + + +[HTTPSについて](./https.md){.internal-link target=_blank}のドキュメントで、1つのサーバーで1つのポートとIPアドレスの組み合わせでリッスンできるのは1つのプロセスだけであることを覚えていますでしょうか? + +これはいまだに同じです。 + +そのため、**複数のプロセス**を同時に持つには**ポートでリッスンしている単一のプロセス**が必要であり、それが何らかの方法で各ワーカー・プロセスに通信を送信することが求められます。 + +### プロセスあたりのメモリー + +さて、プログラムがメモリにロードする際には、例えば機械学習モデルや大きなファイルの内容を変数に入れたりする場合では、**サーバーのメモリ(RAM)**を少し消費します。 + +そして複数のプロセスは通常、**メモリを共有しません**。これは、実行中の各プロセスがそれぞれ独自の変数やメモリ等を持っていることを意味します。つまり、コード内で大量のメモリを消費している場合、**各プロセス**は同等の量のメモリを消費することになります。 + +### サーバーメモリー + +例えば、あなたのコードが **1GBのサイズの機械学習モデル**をロードする場合、APIで1つのプロセスを実行すると、少なくとも1GBのRAMを消費します。 + +また、**4つのプロセス**(4つのワーカー)を起動すると、それぞれが1GBのRAMを消費します。つまり、合計でAPIは**4GBのRAM**を消費することになります。 + +リモートサーバーや仮想マシンのRAMが3GBしかない場合、4GB以上のRAMをロードしようとすると問題が発生します。🚨 + +### 複数プロセス - 例 + +この例では、2つの**ワーカー・プロセス**を起動し制御する**マネージャー・ プロセス**があります。 + +このマネージャー・ プロセスは、おそらくIPの**ポート**でリッスンしているものです。そして、すべての通信をワーカー・プロセスに転送します。 + +これらのワーカー・プロセスは、アプリケーションを実行するものであり、**リクエスト**を受けて**レスポンス**を返すための主要な計算を行い、あなたが変数に入れたものは何でもRAMにロードします。 + + + +そしてもちろん、同じマシンでは、あなたのアプリケーションとは別に、**他のプロセス**も実行されているでしょう。 + +興味深いことに、各プロセスが使用する**CPU**の割合は時間とともに大きく**変動**する可能性がありますが、**メモリ(RAM)**は通常、多かれ少なかれ**安定**します。 + +毎回同程度の計算を行うAPIがあり、多くのクライアントがいるのであれば、**CPU使用率**もおそらく**安定**するでしょう(常に急激に上下するのではなく)。 + +### レプリケーション・ツールと戦略の例 + +これを実現するにはいくつかのアプローチがありますが、具体的な戦略については次の章(Dockerやコンテナの章など)で詳しく説明します。 + +考慮すべき主な制約は、**パブリックIP**の**ポート**を処理する**単一の**コンポーネントが存在しなければならないということです。 + +そして、レプリケートされた**プロセス/ワーカー**に通信を**送信**する方法を持つ必要があります。 + +考えられる組み合わせと戦略をいくつか紹介します: + +* **Gunicorn**が**Uvicornワーカー**を管理 + * Gunicornは**IP**と**ポート**をリッスンする**プロセスマネージャ**で、レプリケーションは**複数のUvicornワーカー・プロセス**を持つことによって行われる。 +* **Uvicorn**が**Uvicornワーカー**を管理 + * 1つのUvicornの**プロセスマネージャー**が**IP**と**ポート**をリッスンし、**複数のUvicornワーカー・プロセス**を起動する。 +* **Kubernetes**やその他の分散**コンテナ・システム** + * **Kubernetes**レイヤーの何かが**IP**と**ポート**をリッスンする。レプリケーションは、**複数のコンテナ**にそれぞれ**1つのUvicornプロセス**を実行させることで行われる。 +* **クラウド・サービス**によるレプリケーション + * クラウド・サービスはおそらく**あなたのためにレプリケーションを処理**します。**実行するプロセス**や使用する**コンテナイメージ**を定義できるかもしれませんが、いずれにせよ、それはおそらく**単一のUvicornプロセス**であり、クラウドサービスはそのレプリケーションを担当するでしょう。 + +!!! tip + これらの**コンテナ**やDockerそしてKubernetesに関する項目が、まだあまり意味をなしていなくても心配しないでください。 + + + コンテナ・イメージ、Docker、Kubernetesなどについては、次の章で詳しく説明します: [コンテナ内のFastAPI - Docker](./docker.md){.internal-link target=_blank}. + +## 開始前の事前のステップ + +アプリケーションを**開始する前**に、いくつかのステップを実行したい場合が多くあります。 + +例えば、**データベース・マイグレーション** を実行したいかもしれません。 + +しかしほとんどの場合、これらの手順を**1度**に実行したいと考えるでしょう。 + +そのため、アプリケーションを開始する前の**事前のステップ**を実行する**単一のプロセス**を用意したいと思われます。 + +そして、それらの事前のステップを実行しているのが単一のプロセスであることを確認する必要があります。このことはその後アプリケーション自体のために**複数のプロセス**(複数のワーカー)を起動した場合も同様です。 + +これらのステップが**複数のプロセス**によって実行された場合、**並列**に実行されることによって作業が**重複**することになります。そして、もしそのステップがデータベースのマイグレーションのような繊細なものであった場合、互いに競合を引き起こす可能性があります。 + +もちろん、事前のステップを何度も実行しても問題がない場合もあり、その際は対処がかなり楽になります。 + +!!! tip + また、セットアップによっては、アプリケーションを開始する前の**事前のステップ**が必要ない場合もあることを覚えておいてください。 + + その場合は、このようなことを心配する必要はないです。🤷 + +### 事前ステップの戦略例 + +これは**システムを**デプロイする方法に**大きく依存**するだろうし、おそらくプログラムの起動方法や再起動の処理などにも関係してくるでしょう。 + +考えられるアイデアをいくつか挙げてみます: + +* アプリコンテナの前に実行されるKubernetesのInitコンテナ +* 事前のステップを実行し、アプリケーションを起動するbashスクリプト + * 利用するbashスクリプトを起動/再起動したり、エラーを検出したりする方法は以前として必要になるでしょう。 + +!!! tip + + コンテナを使った具体的な例については、次の章で紹介します: [コンテナ内のFastAPI - Docker](./docker.md){.internal-link target=_blank}. + +## リソースの利用 + +あなたのサーバーは**リソース**であり、プログラムを実行しCPUの計算時間や利用可能なRAMメモリを消費または**利用**することができます。 + +システムリソースをどれくらい消費/利用したいですか? 「少ない方が良い」と考えるのは簡単かもしれないですが、実際には、**クラッシュせずに可能な限り**最大限に活用したいでしょう。 + +3台のサーバーにお金を払っているにも関わらず、そのRAMとCPUを少ししか使っていないとしたら、おそらく**お金を無駄にしている** 💸、おそらく**サーバーの電力を無駄にしている** 🌎ことになるでしょう。 + +その場合は、サーバーを2台だけにして、そのリソース(CPU、メモリ、ディスク、ネットワーク帯域幅など)をより高い割合で使用する方がよいでしょう。 + +一方、2台のサーバーがあり、そのCPUとRAMの**100%を使用している**場合、ある時点で1つのプロセスがより多くのメモリを要求し、サーバーはディスクを「メモリ」として使用しないといけません。(何千倍も遅くなる可能性があります。) +もしくは**クラッシュ**することもあれば、あるいはあるプロセスが何らかの計算をする必要があり、そしてCPUが再び空くまで待たなければならないかもしれません。 + +この場合、**1つ余分なサーバー**を用意し、その上でいくつかのプロセスを実行し、すべてのサーバーが**十分なRAMとCPU時間を持つようにする**のがよいでしょう。 + +また、何らかの理由でAPIの利用が急増する可能性もあります。もしかしたらそれが流行ったのかもしれないし、他のサービスやボットが使い始めたのかもしれないです。そのような場合に備えて、余分なリソースを用意しておくと安心でしょう。 + +例えば、リソース使用率の**50%から90%の範囲**で**任意の数字**をターゲットとすることができます。 + +重要なのは、デプロイメントを微調整するためにターゲットを設定し測定することが、おそらく使用したい主要な要素であることです。 + +`htop`のような単純なツールを使って、サーバーで使用されているCPUやRAM、あるいは各プロセスで使用されている量を見ることができます。あるいは、より複雑な監視ツールを使って、サーバに分散して使用することもできます。 + +## まとめ + +アプリケーションのデプロイ方法を決定する際に、考慮すべきであろう主要なコンセプトのいくつかを紹介していきました: + +* セキュリティ - HTTPS +* 起動時の実行 +* 再起動 +* レプリケーション(実行中のプロセス数) +* メモリー +* 開始前の事前ステップ + +これらの考え方とその適用方法を理解することで、デプロイメントを設定したり調整したりする際に必要な直感的な判断ができるようになるはずです。🤓 + +次のセクションでは、あなたが取り得る戦略について、より具体的な例を挙げます。🚀 diff --git a/docs/ja/docs/deployment/deta.md b/docs/ja/docs/deployment/deta.md deleted file mode 100644 index 723f169a00f10..0000000000000 --- a/docs/ja/docs/deployment/deta.md +++ /dev/null @@ -1,240 +0,0 @@ -# Deta にデプロイ - -このセクションでは、**FastAPI** アプリケーションを Deta の無料プランを利用して、簡単にデプロイする方法を学習します。🎁 - -所要時間は約**10分**です。 - -!!! info "備考" - Deta は **FastAPI** のスポンサーです。🎉 - -## ベーシックな **FastAPI** アプリ - -* アプリのためのディレクトリ (例えば `./fastapideta/`) を作成し、その中に入ってください。 - -### FastAPI のコード - -* 以下の `main.py` ファイルを作成してください: - -```Python -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): - return {"item_id": item_id} -``` - -### Requirements - -では、同じディレクトリに以下の `requirements.txt` ファイルを作成してください: - -```text -fastapi -``` - -!!! tip "豆知識" - アプリのローカルテストのために Uvicorn をインストールしたくなるかもしれませんが、Deta へのデプロイには不要です。 - -### ディレクトリ構造 - -以下の2つのファイルと1つの `./fastapideta/` ディレクトリがあるはずです: - -``` -. -└── main.py -└── requirements.txt -``` - -## Detaの無料アカウントの作成 - -それでは、Detaの無料アカウントを作成しましょう。必要なものはメールアドレスとパスワードだけです。 - -クレジットカードさえ必要ありません。 - -## CLIのインストール - -アカウントを取得したら、Deta CLI をインストールしてください: - -=== "Linux, macOS" - -
- - ```console - $ curl -fsSL https://get.deta.dev/cli.sh | sh - ``` - -
- -=== "Windows PowerShell" - -
- - ```console - $ iwr https://get.deta.dev/cli.ps1 -useb | iex - ``` - -
- -インストールしたら、インストールした CLI を有効にするために新たなターミナルを開いてください。 - -新たなターミナル上で、正しくインストールされたか確認します: - -
- -```console -$ deta --help - -Deta command line interface for managing deta micros. -Complete documentation available at https://docs.deta.sh - -Usage: - deta [flags] - deta [command] - -Available Commands: - auth Change auth settings for a deta micro - -... -``` - -
- -!!! tip "豆知識" - CLI のインストールに問題が発生した場合は、Deta 公式ドキュメントを参照してください。 - -## CLIでログイン - -CLI から Deta にログインしてみましょう: - -
- -```console -$ deta login - -Please, log in from the web page. Waiting.. -Logged in successfully. -``` - -
- -自動的にウェブブラウザが開いて、認証処理が行われます。 - -## Deta でデプロイ - -次に、アプリケーションを Deta CLIでデプロイしましょう: - -
- -```console -$ deta new - -Successfully created a new micro - -// Notice the "endpoint" 🔍 - -{ - "name": "fastapideta", - "runtime": "python3.7", - "endpoint": "https://qltnci.deta.dev", - "visor": "enabled", - "http_auth": "enabled" -} - -Adding dependencies... - - ----> 100% - - -Successfully installed fastapi-0.61.1 pydantic-1.7.2 starlette-0.13.6 -``` - -
- -次のようなJSONメッセージが表示されます: - -```JSON hl_lines="4" -{ - "name": "fastapideta", - "runtime": "python3.7", - "endpoint": "https://qltnci.deta.dev", - "visor": "enabled", - "http_auth": "enabled" -} -``` - -!!! tip "豆知識" - あなたのデプロイでは異なる `"endpoint"` URLが表示されるでしょう。 - -## 確認 - -それでは、`endpoint` URLをブラウザで開いてみましょう。上記の例では `https://qltnci.deta.dev` ですが、あなたのURLは異なるはずです。 - -FastAPIアプリから返ってきたJSONレスポンスが表示されます: - -```JSON -{ - "Hello": "World" -} -``` - -そして `/docs` へ移動してください。上記の例では、`https://qltnci.deta.dev/docs` です。 - -次のようなドキュメントが表示されます: - - - -## パブリックアクセスの有効化 - -デフォルトでは、Deta はクッキーを用いてアカウントの認証を行います。 - -しかし、準備が整えば、以下の様に公開できます: - -
- -```console -$ deta auth disable - -Successfully disabled http auth -``` - -
- -ここで、URLを共有するとAPIにアクセスできるようになります。🚀 - -## HTTPS - -おめでとうございます!あなたの FastAPI アプリが Deta へデプロイされました!🎉 🍰 - -また、DetaがHTTPSを正しく処理するため、その処理を行う必要がなく、クライアントは暗号化された安全な通信が利用できます。✅ 🔒 - -## Visor を確認 - -ドキュメントUI (`https://qltnci.deta.dev/docs` のようなURLにある) は *path operation* `/items/{item_id}` へリクエストを送ることができます。 - -ID `5` の例を示します。 - -まず、https://web.deta.sh へアクセスします。 - -左側に各アプリの 「Micros」 というセクションが表示されます。 - -また、「Details」や「Visor」タブが表示されています。「Visor」タブへ移動してください。 - -そこでアプリに送られた直近のリクエストが調べられます。 - -また、それらを編集してリプレイできます。 - - - -## さらに詳しく知る - -様々な箇所で永続的にデータを保存したくなるでしょう。そのためには Deta Base を使用できます。惜しみない **無料利用枠** もあります。 - -詳しくは Deta ドキュメントを参照してください。 diff --git a/docs/ja/docs/deployment/docker.md b/docs/ja/docs/deployment/docker.md index f10312b5161c6..ca9dedc3c1c9a 100644 --- a/docs/ja/docs/deployment/docker.md +++ b/docs/ja/docs/deployment/docker.md @@ -1,71 +1,157 @@ -# Dockerを使用したデプロイ +# コンテナ内のFastAPI - Docker -このセクションでは以下の使い方の紹介とガイドへのリンクが確認できます: +FastAPIアプリケーションをデプロイする場合、一般的なアプローチは**Linuxコンテナ・イメージ**をビルドすることです。 -* **5分**程度で、**FastAPI** のアプリケーションを、パフォーマンスを最大限に発揮するDockerイメージ (コンテナ)にする。 -* (オプション) 開発者として必要な範囲でHTTPSを理解する。 -* **20分**程度で、自動的なHTTPS生成とともにDockerのSwarmモード クラスタをセットアップする (月5ドルのシンプルなサーバー上で)。 -* **10分**程度で、DockerのSwarmモード クラスタを使って、HTTPSなどを使用した完全な**FastAPI** アプリケーションの作成とデプロイ。 +基本的には **Docker**を用いて行われます。生成されたコンテナ・イメージは、いくつかの方法のいずれかでデプロイできます。 -デプロイのために、**Docker** を利用できます。セキュリティ、再現性、開発のシンプルさなどに利点があります。 +Linuxコンテナの使用には、**セキュリティ**、**反復可能性(レプリカビリティ)**、**シンプリシティ**など、いくつかの利点があります。 -Dockerを使う場合、公式のDockerイメージが利用できます: +!!! tip + TODO: なぜか遷移できない + お急ぎで、すでにこれらの情報をご存じですか? [以下の`Dockerfile`の箇所👇](#build-a-docker-image-for-fastapi)へジャンプしてください。 -## tiangolo/uvicorn-gunicorn-fastapi +
+Dockerfile プレビュー 👀 -このイメージは「自動チューニング」機構を含んでいます。犠牲を払うことなく、ただコードを加えるだけで自動的に高パフォーマンスを実現できます。 +```Dockerfile +FROM python:3.9 -ただし、環境変数や設定ファイルを使って全ての設定の変更や更新を行えます。 +WORKDIR /code -!!! tip "豆知識" - 全ての設定とオプションを確認するには、Dockerイメージページを開いて下さい: tiangolo/uvicorn-gunicorn-fastapi. +COPY ./requirements.txt /code/requirements.txt -## `Dockerfile` の作成 +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt -* プロジェクトディレクトリへ移動。 -* 以下の`Dockerfile` を作成: +COPY ./app /code/app -```Dockerfile -FROM tiangolo/uvicorn-gunicorn-fastapi:python3.7 +CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] -COPY ./app /app +# If running behind a proxy like Nginx or Traefik add --proxy-headers +# CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80", "--proxy-headers"] ``` -### より大きなアプリケーション +
-[Bigger Applications with Multiple Files](tutorial/bigger-applications.md){.internal-link target=_blank} セクションに倣う場合は、`Dockerfile` は上記の代わりに、以下の様になるかもしれません: +## コンテナとは何か -```Dockerfile -FROM tiangolo/uvicorn-gunicorn-fastapi:python3.7 +コンテナ(主にLinuxコンテナ)は、同じシステム内の他のコンテナ(他のアプリケーションやコンポーネント)から隔離された状態を保ちながら、すべての依存関係や必要なファイルを含むアプリケーションをパッケージ化する非常に**軽量**な方法です。 -COPY ./app /app/app -``` +Linuxコンテナは、ホスト(マシン、仮想マシン、クラウドサーバーなど)の同じLinuxカーネルを使用して実行されます。これは、(OS全体をエミュレートする完全な仮想マシンと比べて)非常に軽量であることを意味します。 -### Raspberry Piなどのアーキテクチャ +このように、コンテナは**リソースをほとんど消費しません**が、プロセスを直接実行するのに匹敵する量です(仮想マシンはもっと消費します)。 -Raspberry Pi (ARMプロセッサ搭載)やそれ以外のアーキテクチャでDockerが作動している場合、(マルチアーキテクチャである) Pythonベースイメージを使って、一から`Dockerfile`を作成し、Uvicornを単体で使用できます。 +コンテナはまた、独自の**分離された**実行プロセス(通常は1つのプロセスのみ)や、ファイルシステム、ネットワークを持ちます。 このことはデプロイ、セキュリティ、開発などを簡素化させます。 -この場合、`Dockerfile` は以下の様になるかもしれません: +## コンテナ・イメージとは何か -```Dockerfile -FROM python:3.7 +**コンテナ**は、**コンテナ・イメージ**から実行されます。 -RUN pip install fastapi uvicorn +コンテナ・イメージは、コンテナ内に存在すべきすべてのファイルや環境変数、そしてデフォルトのコマンド/プログラムを**静的に**バージョン化したものです。 ここでの**静的**とは、コンテナ**イメージ**は実行されておらず、パッケージ化されたファイルとメタデータのみであることを意味します。 -EXPOSE 80 +保存された静的コンテンツである「**コンテナイメージ**」とは対照的に、「**コンテナ**」は通常、実行中のインスタンス、つまり**実行**されているものを指します。 -COPY ./app /app +**コンテナ**が起動され実行されるとき(**コンテナイメージ**から起動されるとき)、ファイルや環境変数などが作成されたり変更されたりする可能性があります。 -CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] +これらの変更はそのコンテナ内にのみ存在しますが、基盤となるコンテナ・イメージには残りません(ディスクに保存されません)。 + +コンテナイメージは **プログラム** ファイルやその内容、例えば `python` と `main.py` ファイルに匹敵します。 + +そして、**コンテナ**自体は(**コンテナイメージ**とは対照的に)イメージをもとにした実際の実行中のインスタンスであり、**プロセス**に匹敵します。 + +実際、コンテナが実行されているのは、**プロセスが実行されている**ときだけです(通常は単一のプロセスだけです)。 コンテナ内で実行中のプロセスがない場合、コンテナは停止します。 + +## コンテナ・イメージ + +Dockerは、**コンテナ・イメージ**と**コンテナ**を作成・管理するための主要なツールの1つです。 + +そして、DockerにはDockerイメージ(コンテナ)を共有するDocker Hubというものがあります。 + +Docker Hubは 多くのツールや環境、データベース、アプリケーションに対応している予め作成された**公式のコンテナ・イメージ**をパブリックに提供しています。 + +例えば、公式イメージの1つにPython Imageがあります。 + +その他にも、データベースなどさまざまなイメージがあります: + +* PostgreSQL +* MySQL +* MongoDB +* Redis, etc. + +予め作成されたコンテナ・イメージを使用することで、異なるツールを**組み合わせて**使用することが非常に簡単になります。例えば、新しいデータベースを試す場合に特に便利です。ほとんどの場合、**公式イメージ**を使い、環境変数で設定するだけで良いです。 + +そうすれば多くの場合、コンテナとDockerについて学び、その知識をさまざまなツールやコンポーネントによって再利用することができます。 + +つまり、データベース、Pythonアプリケーション、Reactフロントエンド・アプリケーションを備えたウェブ・サーバーなど、さまざまなものを**複数のコンテナ**で実行し、それらを内部ネットワーク経由で接続します。 + +すべてのコンテナ管理システム(DockerやKubernetesなど)には、こうしたネットワーキング機能が統合されています。 + +## コンテナとプロセス + +通常、**コンテナ・イメージ**はそのメタデータに**コンテナ**の起動時に実行されるデフォルトのプログラムまたはコマンドと、そのプログラムに渡されるパラメータを含みます。コマンドラインでの操作とよく似ています。 + +**コンテナ**が起動されると、そのコマンド/プログラムが実行されます(ただし、別のコマンド/プログラムをオーバーライドして実行させることもできます)。 + +コンテナは、**メイン・プロセス**(コマンドまたはプログラム)が実行されている限り実行されます。 + +コンテナは通常**1つのプロセス**を持ちますが、メイン・プロセスからサブ・プロセスを起動することも可能で、そうすれば同じコンテナ内に**複数のプロセス**を持つことになります。 + +しかし、**少なくとも1つの実行中のプロセス**がなければ、実行中のコンテナを持つことはできないです。メイン・プロセスが停止すれば、コンテナも停止します。 + +## Build a Docker Image for FastAPI + +ということで、何か作りましょう!🚀 + +FastAPI用の**Dockerイメージ**を、**公式Python**イメージに基づいて**ゼロから**ビルドする方法をお見せします。 + +これは**ほとんどの場合**にやりたいことです。例えば: + +* **Kubernetes**または同様のツールを使用する場合 +* **Raspberry Pi**で実行する場合 +* コンテナ・イメージを実行してくれるクラウド・サービスなどを利用する場合 + +### パッケージ要件(package requirements) + +アプリケーションの**パッケージ要件**は通常、何らかのファイルに記述されているはずです。 + +パッケージ要件は主に**インストール**するために使用するツールに依存するでしょう。 + +最も一般的な方法は、`requirements.txt` ファイルにパッケージ名とそのバージョンを 1 行ずつ書くことです。 + +もちろん、[FastAPI バージョンについて](./versions.md){.internal-link target=_blank}で読んだのと同じアイデアを使用して、バージョンの範囲を設定します。 + +例えば、`requirements.txt` は次のようになります: + +``` +fastapi>=0.68.0,<0.69.0 +pydantic>=1.8.0,<2.0.0 +uvicorn>=0.15.0,<0.16.0 ``` -## **FastAPI** コードの作成 +そして通常、例えば `pip` を使ってこれらのパッケージの依存関係をインストールします: + +
-* `app` ディレクトリを作成し、移動。 -* 以下の`main.py` ファイルを作成: +```console +$ pip install -r requirements.txt +---> 100% +Successfully installed fastapi pydantic uvicorn +``` + +
+ +!!! info + パッケージの依存関係を定義しインストールするためのフォーマットやツールは他にもあります。 + + Poetryを使った例は、後述するセクションでご紹介します。👇 + +### **FastAPI**コードを作成する + +* `app` ディレクトリを作成し、その中に入ります +* 空のファイル `__init__.py` を作成します +* `main.py` ファイルを作成します: ```Python -from typing import Optional +from typing import Union from fastapi import FastAPI @@ -78,23 +164,136 @@ def read_root(): @app.get("/items/{item_id}") -def read_item(item_id: int, q: Optional[str] = None): +def read_item(item_id: int, q: Union[str, None] = None): return {"item_id": item_id, "q": q} ``` -* ここでは、以下の様なディレクトリ構造になっているはずです: +### Dockerfile + +同じプロジェクト・ディレクトリに`Dockerfile`というファイルを作成します: + +```{ .dockerfile .annotate } +# (1) +FROM python:3.9 + +# (2) +WORKDIR /code + +# (3) +COPY ./requirements.txt /code/requirements.txt + +# (4) +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt + +# (5) +COPY ./app /code/app + +# (6) +CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] +``` + +1. 公式のPythonベースイメージから始めます + +2. 現在の作業ディレクトリを `/code` に設定します + + ここに `requirements.txt` ファイルと `app` ディレクトリを置きます。 + +3. 要件が書かれたファイルを `/code` ディレクトリにコピーします + + 残りのコードではなく、最初に必要なファイルだけをコピーしてください。 + + このファイルは**頻繁には変更されない**ので、Dockerはこのステップではそれを検知し**キャッシュ**を使用し、次のステップでもキャッシュを有効にします。 + +4. 要件ファイルにあるパッケージの依存関係をインストールします + `--no-cache-dir` オプションはダウンロードしたパッケージをローカルに保存しないように `pip` に指示します。これは、同じパッケージをインストールするために `pip` を再度実行する場合にのみ有効ですが、コンテナで作業する場合はそうではないです。 + + !!! note + `--no-cache-dir`は`pip`に関連しているだけで、Dockerやコンテナとは何の関係もないです。 + + `--upgrade` オプションは、パッケージが既にインストールされている場合、`pip` にアップグレードするように指示します。 + + 何故ならファイルをコピーする前のステップは**Dockerキャッシュ**によって検出される可能性があるためであり、このステップも利用可能な場合は**Dockerキャッシュ**を使用します。 + + このステップでキャッシュを使用すると、開発中にイメージを何度もビルドする際に、**毎回**すべての依存関係を**ダウンロードしてインストールする**代わりに多くの**時間**を**節約**できます。 + +5. ./app` ディレクトリを `/code` ディレクトリの中にコピーする。 + + これには**最も頻繁に変更される**すべてのコードが含まれているため、Dockerの**キャッシュ**は**これ以降のステップ**に簡単に使用されることはありません。 + + そのため、コンテナイメージのビルド時間を最適化するために、`Dockerfile`の **最後** にこれを置くことが重要です。 + +6. `uvicorn`サーバーを実行するための**コマンド**を設定します + + `CMD` は文字列のリストを取り、それぞれの文字列はスペースで区切られたコマンドラインに入力するものです。 + + このコマンドは **現在の作業ディレクトリ**から実行され、上記の `WORKDIR /code` にて設定した `/code` ディレクトリと同じです。 + + そのためプログラムは `/code` で開始しその中にあなたのコードがある `./app` ディレクトリがあるので、**Uvicorn** は `app.main` から `app` を参照し、**インポート** することができます。 + +!!! tip + コード内の"+"の吹き出しをクリックして、各行が何をするのかをレビューしてください。👆 + +これで、次のようなディレクトリ構造になるはずです: ``` . ├── app +│   ├── __init__.py │ └── main.py -└── Dockerfile +├── Dockerfile +└── requirements.txt +``` + +#### TLS Termination Proxyの裏側 + +Nginx や Traefik のような TLS Termination Proxy (ロードバランサ) の後ろでコンテナを動かしている場合は、`--proxy-headers`オプションを追加します。 + +このオプションは、Uvicornにプロキシ経由でHTTPSで動作しているアプリケーションに対して、送信されるヘッダを信頼するよう指示します。 + +```Dockerfile +CMD ["uvicorn", "app.main:app", "--proxy-headers", "--host", "0.0.0.0", "--port", "80"] +``` + +#### Dockerキャッシュ + +この`Dockerfile`には重要なトリックがあり、まず**依存関係だけのファイル**をコピーします。その理由を説明します。 + +```Dockerfile +COPY ./requirements.txt /code/requirements.txt +``` + +Dockerや他のツールは、これらのコンテナイメージを**段階的に**ビルドし、**1つのレイヤーを他のレイヤーの上に**追加します。`Dockerfile`の先頭から開始し、`Dockerfile`の各命令によって作成されたファイルを追加していきます。 + +Dockerや同様のツールは、イメージをビルドする際に**内部キャッシュ**も使用します。前回コンテナイメージを構築したときからファイルが変更されていない場合、ファイルを再度コピーしてゼロから新しいレイヤーを作成する代わりに、**前回作成した同じレイヤーを再利用**します。 + +ただファイルのコピーを避けるだけではあまり改善されませんが、そのステップでキャッシュを利用したため、**次のステップ**でキャッシュを使うことができます。 + +例えば、依存関係をインストールする命令のためにキャッシュを使うことができます: + +```Dockerfile +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt ``` -## Dockerイメージをビルド +パッケージ要件のファイルは**頻繁に変更されることはありません**。そのため、そのファイルだけをコピーすることで、Dockerはそのステップでは**キャッシュ**を使用することができます。 + +そして、Dockerは**次のステップのためにキャッシュ**を使用し、それらの依存関係をダウンロードしてインストールすることができます。そして、ここで**多くの時間を節約**します。✨ ...そして退屈な待ち時間を避けることができます。😪😆 + +パッケージの依存関係をダウンロードしてインストールするには**数分**かかりますが、**キャッシュ**を使えば**せいぜい数秒**です。 -* プロジェクトディレクトリ (`app` ディレクトリを含んだ、`Dockerfile` のある場所) へ移動 -* FastAPIイメージのビルド: +加えて、開発中にコンテナ・イメージを何度もビルドして、コードの変更が機能しているかどうかをチェックすることになるため、多くの時間を節約することができます。 + +そして`Dockerfile`の最終行の近くですべてのコードをコピーします。この理由は、**最も頻繁に**変更されるものなので、このステップの後にあるものはほとんどキャッシュを使用することができないのためです。 + +```Dockerfile +COPY ./app /code/app +``` + +### Dockerイメージをビルドする + +すべてのファイルが揃ったので、コンテナ・イメージをビルドしましょう。 + +* プロジェクトディレクトリに移動します(`Dockerfile`がある場所で、`app`ディレクトリがあります) +* FastAPI イメージをビルドします:
@@ -106,9 +305,14 @@ $ docker build -t myimage .
-## Dockerコンテナを起動 +!!! tip + 末尾の `.` に注目してほしいです。これは `./` と同じ意味です。 これはDockerにコンテナイメージのビルドに使用するディレクトリを指示します。 + + この場合、同じカレント・ディレクトリ(`.`)です。 -* 用意したイメージを基にしたコンテナの起動: +### Dockerコンテナの起動する + +* イメージに基づいてコンテナを実行します:
@@ -118,62 +322,394 @@ $ docker run -d --name mycontainer -p 80:80 myimage
-これで、Dockerコンテナ内に最適化されたFastAPIサーバが動作しています。使用しているサーバ (そしてCPUコア数) に沿った自動チューニングが行われています。 - -## 確認 +## 確認する -DockerコンテナのURLで確認できるはずです。例えば: http://192.168.99.100/items/5?q=somequeryhttp://127.0.0.1/items/5?q=somequery (もしくはDockerホストを使用したこれらと同等のもの)。 +Dockerコンテナのhttp://192.168.99.100/items/5?q=somequeryhttp://127.0.0.1/items/5?q=somequery (またはそれに相当するDockerホストを使用したもの)といったURLで確認できるはずです。 -以下の様なものが返されます: +アクセスすると以下のようなものが表示されます: ```JSON {"item_id": 5, "q": "somequery"} ``` -## 対話的APIドキュメント +## インタラクティブなAPIドキュメント -ここで、http://192.168.99.100/docshttp://127.0.0.1/docs (もしくはDockerホストを使用したこれらと同等のもの) を開いて下さい。 +これらのURLにもアクセスできます: http://192.168.99.100/docshttp://127.0.0.1/docs (またはそれに相当するDockerホストを使用したもの) -自動生成された対話的APIドキュメントが確認できます (Swagger UIによって提供されます): +アクセスすると、自動対話型APIドキュメント(Swagger UIが提供)が表示されます: ![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) -## その他のAPIドキュメント +## 代替のAPIドキュメント -また同様に、http://192.168.99.100/redochttp://127.0.0.1/redoc (もしくはDockerホストを使用したこれらと同等のもの) を開いて下さい。 +また、http://192.168.99.100/redochttp://127.0.0.1/redoc (またはそれに相当するDockerホストを使用したもの)にもアクセスできます。 -他の自動生成された対話的なAPIドキュメントが確認できます (ReDocによって提供されます): +代替の自動ドキュメント(ReDocによって提供される)が表示されます: ![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) -## Traefik +## 単一ファイルのFastAPIでDockerイメージをビルドする + +FastAPI が単一のファイル、例えば `./app` ディレクトリのない `main.py` の場合、ファイル構造は次のようになります: +``` +. +├── Dockerfile +├── main.py +└── requirements.txt +``` + +そうすれば、`Dockerfile`の中にファイルをコピーするために、対応するパスを変更するだけでよいです: + +```{ .dockerfile .annotate hl_lines="10 13" } +FROM python:3.9 + +WORKDIR /code + +COPY ./requirements.txt /code/requirements.txt + +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt + +# (1) +COPY ./main.py /code/ + +# (2) +CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] +``` + +1. main.py`ファイルを `/code` ディレクトリに直接コピーします。 + +2. Uvicornを実行し、`main`から`app`オブジェクトをインポートするように指示します(`app.main`からインポートするのではなく)。 + +次にUvicornコマンドを調整して、`app.main` の代わりに新しいモジュール `main` を使用し、FastAPIオブジェクトである `app` をインポートします。 + +## デプロイメントのコンセプト + +コンテナという観点から、[デプロイのコンセプト](./concepts.md){.internal-link target=_blank}に共通するいくつかについて、もう一度説明しましょう。 + +コンテナは主に、アプリケーションの**ビルドとデプロイ**のプロセスを簡素化するためのツールですが、これらの**デプロイのコンセプト**を扱うための特定のアプローチを強制するものではないです。 -Traefikは、高性能なリバースプロキシ/ロードバランサーです。「TLSターミネーションプロキシ」ジョブを実行できます(他の機能と切り離して)。 +**良いニュース**は、それぞれの異なる戦略には、すべてのデプロイメントのコンセプトをカバーする方法があるということです。🎉 -Let's Encryptと統合されています。そのため、証明書の取得と更新を含むHTTPSに関するすべての処理を実行できます。 +これらの**デプロイメントのコンセプト**をコンテナの観点から見直してみましょう: -また、Dockerとも統合されています。したがって、各アプリケーション構成でドメインを宣言し、それらの構成を読み取って、HTTPS証明書を生成し、構成に変更を加えることなく、アプリケーションにHTTPSを自動的に提供できます。 +* セキュリティ - HTTPS +* 起動時の実行 +* 再起動 +* **レプリケーション(実行中のプロセス数)** +* メモリ +* 開始前の事前ステップ + +## HTTPS + +FastAPI アプリケーションの **コンテナ・イメージ**(および後で実行中の **コンテナ**)だけに焦点を当てると、通常、HTTPSは別のツールを用いて**外部で**処理されます。 + +例えばTraefikのように、**HTTPS**と**証明書**の**自動**取得を扱う別のコンテナである可能性もあります。 + +!!! tip + TraefikはDockerやKubernetesなどと統合されているので、コンテナ用のHTTPSの設定や構成はとても簡単です。 + +あるいは、(コンテナ内でアプリケーションを実行しながら)クラウド・プロバイダーがサービスの1つとしてHTTPSを処理することもできます。 + +## 起動時および再起動時の実行 + +通常、コンテナの**起動と実行**を担当する別のツールがあります。 + +それは直接**Docker**であったり、**Docker Compose**であったり、**Kubernetes**であったり、**クラウドサービス**であったりします。 + +ほとんどの場合(またはすべての場合)、起動時にコンテナを実行し、失敗時に再起動を有効にする簡単なオプションがあります。例えばDockerでは、コマンドラインオプションの`--restart`が該当します。 + +コンテナを使わなければ、アプリケーションを起動時や再起動時に実行させるのは面倒で難しいかもしれません。しかし、**コンテナ**で作業する場合、ほとんどのケースでその機能はデフォルトで含まれています。✨ + +## レプリケーション - プロセス数 + +**Kubernetes** や Docker Swarm モード、Nomad、あるいは複数のマシン上で分散コンテナを管理するための同様の複雑なシステムを使ってマシンのクラスターを構成している場合、 各コンテナで(Workerを持つGunicornのような)**プロセスマネージャ**を使用する代わりに、**クラスター・レベル**で**レプリケーション**を処理したいと思うでしょう。 + +Kubernetesのような分散コンテナ管理システムの1つは通常、入ってくるリクエストの**ロードバランシング**をサポートしながら、**コンテナのレプリケーション**を処理する統合された方法を持っています。このことはすべて**クラスタレベル**にてです。 + +そのような場合、UvicornワーカーでGunicornのようなものを実行するのではなく、[上記の説明](#dockerfile)のように**Dockerイメージをゼロから**ビルドし、依存関係をインストールして、**単一のUvicornプロセス**を実行したいでしょう。 + +### ロードバランサー + +コンテナを使用する場合、通常はメイン・ポート**でリスニング**しているコンポーネントがあるはずです。それはおそらく、**HTTPS**を処理するための**TLS Termination Proxy**でもある別のコンテナであったり、同様のツールであったりするでしょう。 + +このコンポーネントはリクエストの **負荷** を受け、 (うまくいけば) その負荷を**バランスよく** ワーカーに分配するので、一般に **ロードバランサ** とも呼ばれます。 + +!!! tip +  HTTPSに使われるものと同じ**TLS Termination Proxy**コンポーネントは、おそらく**ロードバランサー**にもなるでしょう。 + +そしてコンテナで作業する場合、コンテナの起動と管理に使用する同じシステムには、**ロードバランサー**(**TLS Termination Proxy**の可能性もある)から**ネットワーク通信**(HTTPリクエストなど)をアプリのあるコンテナ(複数可)に送信するための内部ツールが既にあるはずです。 + +### 1つのロードバランサー - 複数のワーカーコンテナー + +**Kubernetes**や同様の分散コンテナ管理システムで作業する場合、その内部のネットワーキングのメカニズムを使用することで、メインの**ポート**でリッスンしている単一の**ロードバランサー**が、アプリを実行している可能性のある**複数のコンテナ**に通信(リクエスト)を送信できるようになります。 + +アプリを実行するこれらのコンテナには、通常**1つのプロセス**(たとえば、FastAPIアプリケーションを実行するUvicornプロセス)があります。これらはすべて**同一のコンテナ**であり同じものを実行しますが、それぞれが独自のプロセスやメモリなどを持ちます。そうすることで、CPUの**異なるコア**、あるいは**異なるマシン**での**並列化**を利用できます。 + +そして、**ロードバランサー**を備えた分散コンテナシステムは、**順番に**あなたのアプリを含む各コンテナに**リクエストを分配**します。つまり、各リクエストは、あなたのアプリを実行している複数の**レプリケートされたコンテナ**の1つによって処理されます。 + +そして通常、この**ロードバランサー**は、クラスタ内の*他の*アプリケーション(例えば、異なるドメインや異なるURLパスのプレフィックスの配下)へのリクエストを処理することができ、その通信をクラスタ内で実行されている*他の*アプリケーションのための適切なコンテナに送信します。 + +### 1コンテナにつき1プロセス + +この種のシナリオでは、すでにクラスタ・レベルでレプリケーションを処理しているため、おそらくコンテナごとに**単一の(Uvicorn)プロセス**を持ちたいでしょう。 + +この場合、Uvicornワーカーを持つGunicornのようなプロセスマネージャーや、Uvicornワーカーを使うUvicornは**避けたい**でしょう。**コンテナごとにUvicornのプロセスは1つだけ**にしたいでしょう(おそらく複数のコンテナが必要でしょう)。 + +(GunicornやUvicornがUvicornワーカーを管理するように)コンテナ内に別のプロセスマネージャーを持つことは、クラスターシステムですでに対処しているであろう**不要な複雑さ**を追加するだけです。 + +### Containers with Multiple Processes and Special Cases + +もちろん、**特殊なケース**として、**Gunicornプロセスマネージャ**を持つ**コンテナ**内で複数の**Uvicornワーカープロセス**を起動させたい場合があります。 + +このような場合、**公式のDockerイメージ**を使用することができます。このイメージには、複数の**Uvicornワーカープロセス**を実行するプロセスマネージャとして**Gunicorn**が含まれており、現在のCPUコアに基づいてワーカーの数を自動的に調整するためのデフォルト設定がいくつか含まれています。詳しくは後述の[Gunicornによる公式Dockerイメージ - Uvicorn](#gunicornによる公式dockerイメージ---Uvicorn)で説明します。 + +以下は、それが理にかなっている場合の例です: + +#### シンプルなアプリケーション + +アプリケーションを**シンプル**な形で実行する場合、プロセス数の細かい調整が必要ない場合、自動化されたデフォルトを使用するだけで、コンテナ内にプロセスマネージャが必要かもしれません。例えば、公式Dockerイメージでシンプルな設定が可能です。 + +#### Docker Compose + +Docker Composeで**シングルサーバ**(クラスタではない)にデプロイすることもできますので、共有ネットワークと**ロードバランシング**を維持しながら(Docker Composeで)コンテナのレプリケーションを管理する簡単な方法はないでしょう。 + +その場合、**単一のコンテナ**で、**プロセスマネージャ**が内部で**複数のワーカープロセス**を起動するようにします。 + +#### Prometheusとその他の理由 + +また、**1つのコンテナ**に**1つのプロセス**を持たせるのではなく、**1つのコンテナ**に**複数のプロセス**を持たせる方が簡単だという**他の理由**もあるでしょう。 + +例えば、(セットアップにもよりますが)Prometheusエクスポーターのようなツールを同じコンテナ内に持つことができます。 + +この場合、**複数のコンテナ**があると、デフォルトでは、Prometheusが**メトリクスを**読みに来たとき、すべてのレプリケートされたコンテナの**蓄積されたメトリクス**を取得するのではなく、毎回**単一のコンテナ**(その特定のリクエストを処理したコンテナ)のものを取得することになります。 + +その場合、**複数のプロセス**を持つ**1つのコンテナ**を用意し、同じコンテナ上のローカルツール(例えばPrometheusエクスポーター)がすべての内部プロセスのPrometheusメトリクスを収集し、その1つのコンテナ上でそれらのメトリクスを公開する方がシンプルかもしれません。 --- -次のセクションに進み、この情報とツールを使用して、すべてを組み合わせます。 +重要なのは、盲目的に従わなければならない普遍のルールはないということです。 + +これらのアイデアは、**あなた自身のユースケース**を評価し、あなたのシステムに最適なアプローチを決定するために使用することができます: + +* セキュリティ - HTTPS +* 起動時の実行 +* 再起動 +* **レプリケーション(実行中のプロセス数)** +* メモリ +* 開始前の事前ステップ + +## メモリー + +コンテナごとに**単一のプロセスを実行する**と、それらのコンテナ(レプリケートされている場合は1つ以上)によって消費される多かれ少なかれ明確に定義された、安定し制限された量のメモリを持つことになります。 + +そして、コンテナ管理システム(**Kubernetes**など)の設定で、同じメモリ制限と要件を設定することができます。 + +そうすれば、コンテナが必要とするメモリ量とクラスタ内のマシンで利用可能なメモリ量を考慮して、**利用可能なマシン**に**コンテナ**をレプリケートできるようになります。 + +アプリケーションが**シンプル**なものであれば、これはおそらく**問題にはならない**でしょうし、ハードなメモリ制限を指定する必要はないかもしれないです。 + +しかし、**多くのメモリを使用**している場合(たとえば**機械学習**モデルなど)、どれだけのメモリを消費しているかを確認し、**各マシンで実行するコンテナの数**を調整する必要があります(そしておそらくクラスタにマシンを追加します)。 + +**コンテナごとに複数のプロセス**を実行する場合(たとえば公式のDockerイメージで)、起動するプロセスの数が**利用可能なメモリ以上に消費しない**ようにする必要があります。 + +## 開始前の事前ステップとコンテナ + +コンテナ(DockerやKubernetesなど)を使っている場合、主に2つのアプローチがあります。 + +### 複数のコンテナ + +複数の**コンテナ**があり、おそらくそれぞれが**単一のプロセス**を実行している場合(**Kubernetes**クラスタなど)、レプリケートされたワーカーコンテナを実行する**前に**、単一のコンテナで**事前のステップ**の作業を行う**別のコンテナ**を持ちたいと思うでしょう。 + +!!! info + もしKubernetesを使用している場合, これはおそらくInit コンテナでしょう。 + +ユースケースが事前のステップを**並列で複数回**実行するのに問題がない場合(例:データベースの準備チェック)、メインプロセスを開始する前に、それらのステップを各コンテナに入れることが可能です。 + +### 単一コンテナ + +単純なセットアップで、**単一のコンテナ**で複数の**ワーカー・プロセス**(または1つのプロセスのみ)を起動する場合、アプリでプロセスを開始する直前に、同じコンテナで事前のステップを実行できます。公式Dockerイメージは、内部的にこれをサポートしています。 + +## Gunicornによる公式Dockerイメージ - Uvicorn + +前の章で詳しく説明したように、Uvicornワーカーで動作するGunicornを含む公式のDockerイメージがあります: [Server Workers - Gunicorn と Uvicorn](./server-workers.md){.internal-link target=_blank}で詳しく説明しています。 + +このイメージは、主に上記で説明した状況で役に立つでしょう: [複数のプロセスと特殊なケースを持つコンテナ(Containers with Multiple Processes and Special Cases)](#containers-with-multiple-processes-and-special-cases) + +* tiangolo/uvicorn-gunicorn-fastapi. + +!!! warning + このベースイメージや類似のイメージは**必要ない**可能性が高いので、[上記の: FastAPI用のDockerイメージをビルドする(Build a Docker Image for FastAPI)](#build-a-docker-image-for-fastapi)のようにゼロからイメージをビルドする方が良いでしょう。 + +このイメージには、利用可能なCPUコアに基づいて**ワーカー・プロセスの数**を設定する**オートチューニング**メカニズムが含まれています。 + +これは**賢明なデフォルト**を備えていますが、**環境変数**や設定ファイルを使ってすべての設定を変更したり更新したりすることができます。 -## TraefikとHTTPSを使用したDocker Swarmモードのクラスタ +また、スクリプトで**開始前の事前ステップ**を実行することもサポートしている。 -HTTPSを処理する(証明書の取得と更新を含む)Traefikを使用して、Docker Swarmモードのクラスタを数分(20分程度)でセットアップできます。 +!!! tip + すべての設定とオプションを見るには、Dockerイメージのページをご覧ください: tiangolo/uvicorn-gunicorn-fastapi -Docker Swarmモードを使用することで、1台のマシンの「クラスタ」から開始でき(1か月あたり5ドルのサーバーでもできます)、後から必要なだけサーバーを拡張できます。 +### 公式Dockerイメージのプロセス数 -TraefikおよびHTTPS処理を備えたDocker Swarm Modeクラスターをセットアップするには、次のガイドに従います: +このイメージの**プロセス数**は、利用可能なCPU**コア**から**自動的に計算**されます。 + +つまり、CPUから可能な限り**パフォーマンス**を**引き出そう**とします。 + +また、**環境変数**などを使った設定で調整することもできます。 + +しかし、プロセスの数はコンテナが実行しているCPUに依存するため、**消費されるメモリの量**もそれに依存することになります。 + +そのため、(機械学習モデルなどで)大量のメモリを消費するアプリケーションで、サーバーのCPUコアが多いが**メモリが少ない**場合、コンテナは利用可能なメモリよりも多くのメモリを使おうとすることになります。 + +その結果、パフォーマンスが大幅に低下する(あるいはクラッシュする)可能性があります。🚨 + +### Dockerfileを作成する + +この画像に基づいて`Dockerfile`を作成する方法を以下に示します: + +```Dockerfile +FROM tiangolo/uvicorn-gunicorn-fastapi:python3.9 + +COPY ./requirements.txt /app/requirements.txt + +RUN pip install --no-cache-dir --upgrade -r /app/requirements.txt + +COPY ./app /app +``` + +### より大きなアプリケーション + +[複数のファイルを持つ大きなアプリケーション](../tutorial/bigger-applications.md){.internal-link target=_blank}を作成するセクションに従った場合、`Dockerfile`は次のようになります: + +```Dockerfile hl_lines="7" +FROM tiangolo/uvicorn-gunicorn-fastapi:python3.9 + +COPY ./requirements.txt /app/requirements.txt + +RUN pip install --no-cache-dir --upgrade -r /app/requirements.txt + +COPY ./app /app/app +``` + +### いつ使うのか + +おそらく、**Kubernetes**(または他のもの)を使用していて、すでにクラスタレベルで複数の**コンテナ**で**レプリケーション**を設定している場合は、この公式ベースイメージ(または他の類似のもの)は**使用すべきではありません**。 + +そのような場合は、上記のように**ゼロから**イメージを構築する方がよいでしょう: [FastAPI用のDockerイメージをビルドする(Build a Docker Image for FastAPI)](#build-a-docker-image-for-fastapi) を参照してください。 + +このイメージは、主に上記の[複数のプロセスと特殊なケースを持つコンテナ(Containers with Multiple Processes and Special Cases)](#containers-with-multiple-processes-and-special-cases)で説明したような特殊なケースで役に立ちます。 + +例えば、アプリケーションが**シンプル**で、CPUに応じたデフォルトのプロセス数を設定すればうまくいく場合や、クラスタレベルでレプリケーションを手動で設定する手間を省きたい場合、アプリで複数のコンテナを実行しない場合などです。 + +または、**Docker Compose**でデプロイし、単一のサーバで実行している場合などです。 + +## コンテナ・イメージのデプロイ + +コンテナ(Docker)イメージを手に入れた後、それをデプロイするにはいくつかの方法があります。 + +例えば以下のリストの方法です: + +* 単一サーバーの**Docker Compose** +* **Kubernetes**クラスタ +* Docker Swarmモードのクラスター +* Nomadのような別のツール +* コンテナ・イメージをデプロイするクラウド・サービス + +## Poetryを利用したDockerイメージ + +もしプロジェクトの依存関係を管理するためにPoetryを利用する場合、マルチステージビルドを使うと良いでしょう。 + +```{ .dockerfile .annotate } +# (1) +FROM python:3.9 as requirements-stage + +# (2) +WORKDIR /tmp + +# (3) +RUN pip install poetry + +# (4) +COPY ./pyproject.toml ./poetry.lock* /tmp/ + +# (5) +RUN poetry export -f requirements.txt --output requirements.txt --without-hashes + +# (6) +FROM python:3.9 + +# (7) +WORKDIR /code + +# (8) +COPY --from=requirements-stage /tmp/requirements.txt /code/requirements.txt + +# (9) +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt + +# (10) +COPY ./app /code/app + +# (11) +CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] +``` + +1. これは最初のステージで、`requirements-stage`と名付けられます +2. `/tmp` を現在の作業ディレクトリに設定します + ここで `requirements.txt` というファイルを生成します。 + +3. このDockerステージにPoetryをインストールします + +4. pyproject.toml`と`poetry.lock`ファイルを`/tmp` ディレクトリにコピーします + + `./poetry.lock*`(末尾に`*`)を使用するため、そのファイルがまだ利用できない場合でもクラッシュすることはないです。 +5. requirements.txt`ファイルを生成します + +6. これは最後のステージであり、ここにあるものはすべて最終的なコンテナ・イメージに保存されます +7. 現在の作業ディレクトリを `/code` に設定します +8. `requirements.txt`ファイルを `/code` ディレクトリにコピーします + このファイルは前のDockerステージにしか存在しないため、`--from-requirements-stage`を使ってコピーします。 +9. 生成された `requirements.txt` ファイルにあるパッケージの依存関係をインストールします +10. app` ディレクトリを `/code` ディレクトリにコピーします +11. uvicorn` コマンドを実行して、`app.main` からインポートした `app` オブジェクトを使用するように指示します +!!! tip + "+"の吹き出しをクリックすると、それぞれの行が何をするのかを見ることができます + +**Dockerステージ**は`Dockerfile`の一部で、**一時的なコンテナイメージ**として動作します。 + +最初のステージは **Poetryのインストール**と Poetry の `pyproject.toml` ファイルからプロジェクトの依存関係を含む**`requirements.txt`を生成**するためだけに使用されます。 + +この `requirements.txt` ファイルは後半の **次のステージ**で `pip` と共に使用されます。 + +最終的なコンテナイメージでは、**最終ステージ**のみが保存されます。前のステージは破棄されます。 + +Poetryを使用する場合、**Dockerマルチステージビルド**を使用することは理にかなっています。 + +なぜなら、最終的なコンテナイメージにPoetryとその依存関係がインストールされている必要はなく、**必要なのは**プロジェクトの依存関係をインストールするために生成された `requirements.txt` ファイルだけだからです。 + +そして次の(そして最終的な)ステージでは、前述とほぼ同じ方法でイメージをビルドします。 + +### TLS Termination Proxyの裏側 - Poetry + +繰り返しになりますが、NginxやTraefikのようなTLS Termination Proxy(ロードバランサー)の後ろでコンテナを動かしている場合は、`--proxy-headers`オプションをコマンドに追加します: + +```Dockerfile +CMD ["uvicorn", "app.main:app", "--proxy-headers", "--host", "0.0.0.0", "--port", "80"] +``` -### Docker Swarm Mode and Traefik for an HTTPS cluster +## まとめ -### FastAPIアプリケーションのデプロイ +コンテナ・システム(例えば**Docker**や**Kubernetes**など)を使えば、すべての**デプロイメントのコンセプト**を扱うのがかなり簡単になります: -すべてを設定するための最も簡単な方法は、[**FastAPI** Project Generators](../project-generation.md){.internal-link target=_blank}を使用することでしょう。 +* セキュリティ - HTTPS +* 起動時の実行 +* 再起動 +* **レプリケーション(実行中のプロセス数)** +* メモリ +* 開始前の事前ステップ -上述したTraefikとHTTPSを備えたDocker Swarm クラスタが統合されるように設計されています。 +ほとんどの場合、ベースとなるイメージは使用せず、公式のPython Dockerイメージをベースにした**コンテナイメージをゼロからビルド**します。 -2分程度でプロジェクトが生成されます。 +`Dockerfile`と**Dockerキャッシュ**内の命令の**順番**に注意することで、**ビルド時間を最小化**することができ、生産性を最大化することができます(そして退屈を避けることができます)。😎 -生成されたプロジェクトはデプロイの指示がありますが、それを実行するとさらに2分かかります。 +特別なケースでは、FastAPI用の公式Dockerイメージを使いたいかもしれません。🤓 diff --git a/docs/ja/docs/deployment/https.md b/docs/ja/docs/deployment/https.md new file mode 100644 index 0000000000000..a291f870fddc6 --- /dev/null +++ b/docs/ja/docs/deployment/https.md @@ -0,0 +1,200 @@ +# HTTPS について + +HTTPSは単に「有効」か「無効」かで決まるものだと思いがちです。 + +しかし、それよりもはるかに複雑です。 + +!!! tip + もし急いでいたり、HTTPSの仕組みについて気にしないのであれば、次のセクションに進み、さまざまなテクニックを使ってすべてをセットアップするステップ・バイ・ステップの手順をご覧ください。 + +利用者の視点から **HTTPS の基本を学ぶ**に当たっては、次のリソースをオススメします: https://howhttps.works/. + +さて、**開発者の視点**から、HTTPSについて考える際に念頭に置くべきことをいくつかみていきましょう: + +* HTTPSの場合、**サーバ**は**第三者**によって生成された**「証明書」を持つ**必要があります。 + * これらの証明書は「生成」されたものではなく、実際には第三者から**取得**されたものです。 +* 証明書には**有効期限**があります。 + * つまりいずれ失効します。 + * そのため**更新**をし、第三者から**再度取得**する必要があります。 +* 接続の暗号化は**TCPレベル**で行われます。 + * それは**HTTPの1つ下**のレイヤーです。 + * つまり、**証明書と暗号化**の処理は、**HTTPの前**に行われます。 +* **TCPは "ドメイン "について知りません**。IPアドレスについてのみ知っています。 + * 要求された**特定のドメイン**に関する情報は、**HTTPデータ**に入ります。 +* **HTTPS証明書**は、**特定のドメイン**を「証明」しますが、プロトコルと暗号化はTCPレベルで行われ、どのドメインが扱われているかを**知る前**に行われます。 +* **デフォルトでは**、**IPアドレスごとに1つのHTTPS証明書**しか持てないことになります。 + * これは、サーバーの規模やアプリケーションの規模に寄りません。 + * しかし、これには**解決策**があります。 +* **TLS**プロトコル(HTTPの前に、TCPレベルで暗号化を処理するもの)には、**SNI**と呼ばれる**拡張**があります。 + * このSNI拡張機能により、1つのサーバー(**単一のIPアドレス**を持つ)が**複数のHTTPS証明書**を持ち、**複数のHTTPSドメイン/アプリケーション**にサービスを提供できるようになります。 + * これが機能するためには、**パブリックIPアドレス**でリッスンしている、サーバー上で動作している**単一の**コンポーネント(プログラム)が、サーバー内の**すべてのHTTPS証明書**を持っている必要があります。 + +* セキュアな接続を取得した**後**でも、通信プロトコルは**HTTPのまま**です。 + * コンテンツは**HTTPプロトコル**で送信されているにもかかわらず、**暗号化**されています。 + + +サーバー(マシン、ホストなど)上で**1つのプログラム/HTTPサーバー**を実行させ、**HTTPSに関する全てのこと**を管理するのが一般的です。 + +**暗号化された HTTPS リクエスト** を受信し、**復号化された HTTP リクエスト** を同じサーバーで実行されている実際の HTTP アプリケーション(この場合は **FastAPI** アプリケーション)に送信し、アプリケーションから **HTTP レスポンス** を受け取り、適切な **HTTPS 証明書** を使用して **暗号化** し、そして**HTTPS** を使用してクライアントに送り返します。 + +このサーバーはしばしば **TLS Termination Proxy**と呼ばれます。 + +TLS Termination Proxyとして使えるオプションには、以下のようなものがあります: + +* Traefik(証明書の更新も対応) +* Caddy (証明書の更新も対応) +* Nginx +* HAProxy + + +## Let's Encrypt + +Let's Encrypt以前は、これらの**HTTPS証明書**は信頼できる第三者によって販売されていました。 + +これらの証明書を取得するための手続きは面倒で、かなりの書類を必要とし、証明書はかなり高価なものでした。 + +しかしその後、**Let's Encrypt** が作られました。 + +これはLinux Foundationのプロジェクトから生まれたものです。 自動化された方法で、**HTTPS証明書を無料で**提供します。これらの証明書は、すべての標準的な暗号化セキュリティを使用し、また短命(約3ヶ月)ですが、こういった寿命の短さによって、**セキュリティは実際に優れています**。 + +ドメインは安全に検証され、証明書は自動的に生成されます。また、証明書の更新も自動化されます。 + +このアイデアは、これらの証明書の取得と更新を自動化することで、**安全なHTTPSを、無料で、永遠に**利用できるようにすることです。 + +## 開発者のための HTTPS + +ここでは、HTTPS APIがどのように見えるかの例を、主に開発者にとって重要なアイデアに注意を払いながら、ステップ・バイ・ステップで説明します。 + +### ドメイン名 + +ステップの初めは、**ドメイン名**を**取得すること**から始まるでしょう。その後、DNSサーバー(おそらく同じクラウドプロバイダー)に設定します。 + +おそらくクラウドサーバー(仮想マシン)かそれに類するものを手に入れ、固定の **パブリックIPアドレス**を持つことになるでしょう。 + +DNSサーバーでは、**取得したドメイン**をあなたのサーバーのパプリック**IPアドレス**に向けるレコード(「`Aレコード`」)を設定します。 + +これはおそらく、最初の1回だけあり、すべてをセットアップするときに行うでしょう。 + +!!! tip + ドメイン名の話はHTTPSに関する話のはるか前にありますが、すべてがドメインとIPアドレスに依存するため、ここで言及する価値があります。 + +### DNS + +では、実際のHTTPSの部分に注目してみよう。 + +まず、ブラウザは**DNSサーバー**に**ドメインに対するIP**が何であるかを確認します。今回は、`someapp.example.com`とします。 + +DNSサーバーは、ブラウザに特定の**IPアドレス**を使用するように指示します。このIPアドレスは、DNSサーバーで設定した、あなたのサーバーが使用するパブリックIPアドレスになります。 + + + +### TLS Handshake の開始 + +ブラウザはIPアドレスと**ポート443**(HTTPSポート)で通信します。 + +通信の最初の部分は、クライアントとサーバー間の接続を確立し、使用する暗号鍵などを決めるだけです。 + + + +TLS接続を確立するためのクライアントとサーバー間のこのやりとりは、**TLSハンドシェイク**と呼ばれます。 + +### SNI拡張機能付きのTLS + +サーバー内の**1つのプロセス**だけが、特定 の**IPアドレス**の特定の**ポート** で待ち受けることができます。 + +同じIPアドレスの他のポートで他のプロセスがリッスンしている可能性もありますが、IPアドレスとポートの組み合わせごとに1つだけです。 + +TLS(HTTPS)はデフォルトで`443`という特定のポートを使用する。つまり、これが必要なポートです。 + +このポートをリッスンできるのは1つのプロセスだけなので、これを実行するプロセスは**TLS Termination Proxy**となります。 + +TLS Termination Proxyは、1つ以上の**TLS証明書**(HTTPS証明書)にアクセスできます。 + +前述した**SNI拡張機能**を使用して、TLS Termination Proxy は、利用可能なTLS (HTTPS)証明書のどれを接続先として使用すべきかをチェックし、クライアントが期待するドメインに一致するものを使用します。 + +今回は、`someapp.example.com`の証明書を使うことになります。 + + + +クライアントは、そのTLS証明書を生成したエンティティ(この場合はLet's Encryptですが、これについては後述します)をすでに**信頼**しているため、その証明書が有効であることを**検証**することができます。 + +次に証明書を使用して、クライアントとTLS Termination Proxy は、 **TCP通信**の残りを**どのように暗号化するかを決定**します。これで**TLSハンドシェイク**の部分が完了します。 + +この後、クライアントとサーバーは**暗号化されたTCP接続**を持ちます。そして、その接続を使って実際の**HTTP通信**を開始することができます。 + +これが**HTTPS**であり、純粋な(暗号化されていない)TCP接続ではなく、**セキュアなTLS接続**の中に**HTTP**があるだけです。 + +!!! tip + 通信の暗号化は、HTTPレベルではなく、**TCPレベル**で行われることに注意してください。 + +### HTTPS リクエスト + +これでクライアントとサーバー(具体的にはブラウザとTLS Termination Proxy)は**暗号化されたTCP接続**を持つことになり、**HTTP通信**を開始することができます。 + +そこで、クライアントは**HTTPSリクエスト**を送信します。これは、暗号化されたTLSコネクションを介した単なるHTTPリクエストです。 + + + +### リクエストの復号化 + +TLS Termination Proxy は、合意が取れている暗号化を使用して、**リクエストを復号化**し、**プレーン (復号化された) HTTP リクエスト** をアプリケーションを実行しているプロセス (例えば、FastAPI アプリケーションを実行している Uvicorn を持つプロセス) に送信します。 + + + +### HTTP レスポンス + +アプリケーションはリクエストを処理し、**プレーン(暗号化されていない)HTTPレスポンス** をTLS Termination Proxyに送信します。 + + + +### HTTPS レスポンス + +TLS Termination Proxyは次に、事前に合意が取れている暗号(`someapp.example.com`の証明書から始まる)を使って**レスポンスを暗号化し**、ブラウザに送り返す。 + +その後ブラウザでは、レスポンスが有効で正しい暗号キーで暗号化されていることなどを検証します。そして、ブラウザはレスポンスを**復号化**して処理します。 + + + +クライアント(ブラウザ)は、レスポンスが正しいサーバーから来たことを知ることができます。 なぜなら、そのサーバーは、以前に**HTTPS証明書**を使って合意した暗号を使っているからです。 + +### 複数のアプリケーション + +同じサーバー(または複数のサーバー)に、例えば他のAPIプログラムやデータベースなど、**複数のアプリケーション**が存在する可能性があります。 + +特定のIPとポート(この例ではTLS Termination Proxy)を扱うことができるのは1つのプロセスだけですが、他のアプリケーション/プロセスも、同じ**パブリックIPとポート**の組み合わせを使用しようとしない限り、サーバー上で実行することができます。 + + + +そうすれば、TLS Termination Proxy は、**複数のドメイン**や複数のアプリケーションのHTTPSと証明書を処理し、それぞれのケースで適切なアプリケーションにリクエストを送信することができます。 + +### 証明書の更新 + +将来のある時点で、各証明書は(取得後約3ヶ月で)**失効**します。 + +その後、Let's Encryptと通信する別のプログラム(別のプログラムである場合もあれば、同じTLS Termination Proxyである場合もある)によって、証明書を更新します。 + + + +**TLS証明書**は、IPアドレスではなく、**ドメイン名に関連付けられて**います。 + +したがって、証明書を更新するために、更新プログラムは、認証局(Let's Encrypt)に対して、**そのドメインが本当に「所有」し、管理している**ことを**証明**する必要があります。 + +そのために、またさまざまなアプリケーションのニーズに対応するために、いくつかの方法があります。よく使われる方法としては: + +* **いくつかのDNSレコードを修正します。** + * これをするためには、更新プログラムはDNSプロバイダーのAPIをサポートする必要があります。したがって、使用しているDNSプロバイダーによっては、このオプションが使える場合もあれば、使えない場合もあります。 +* ドメインに関連付けられたパブリックIPアドレス上で、(少なくとも証明書取得プロセス中は)**サーバー**として実行します。 + * 上で述べたように、特定のIPとポートでリッスンできるプロセスは1つだけです。 + * これは、同じTLS Termination Proxyが証明書の更新処理も行う場合に非常に便利な理由の1つです。 + * そうでなければ、TLS Termination Proxyを一時的に停止し、証明書を取得するために更新プログラムを起動し、TLS Termination Proxyで証明書を設定し、TLS Termination Proxyを再起動しなければならないかもしれません。TLS Termination Proxyが停止している間はアプリが利用できなくなるため、これは理想的ではありません。 + + +アプリを提供しながらこのような更新処理を行うことは、アプリケーション・サーバー(Uvicornなど)でTLS証明書を直接使用するのではなく、TLS Termination Proxyを使用して**HTTPSを処理する別のシステム**を用意したくなる主な理由の1つです。 + +## まとめ + +**HTTPS**を持つことは非常に重要であり、ほとんどの場合、かなり**クリティカル**です。開発者として HTTPS に関わる労力のほとんどは、これらの**概念とその仕組みを理解する**ことです。 + +しかし、ひとたび**開発者向けHTTPS**の基本的な情報を知れば、簡単な方法ですべてを管理するために、さまざまなツールを組み合わせて設定することができます。 + +次の章では、**FastAPI** アプリケーションのために **HTTPS** をセットアップする方法について、いくつかの具体例を紹介します。🔒 diff --git a/docs/ja/docs/deployment/server-workers.md b/docs/ja/docs/deployment/server-workers.md new file mode 100644 index 0000000000000..e1ea165a2c95d --- /dev/null +++ b/docs/ja/docs/deployment/server-workers.md @@ -0,0 +1,182 @@ +# Server Workers - Gunicorn と Uvicorn + +前回のデプロイメントのコンセプトを振り返ってみましょう: + +* セキュリティ - HTTPS +* 起動時の実行 +* 再起動 +* **レプリケーション(実行中のプロセス数)** +* メモリ +* 開始前の事前ステップ + +ここまでのドキュメントのチュートリアルでは、おそらくUvicornのような**サーバープログラム**を**単一のプロセス**で実行しています。 + +アプリケーションをデプロイする際には、**複数のコア**を利用し、そしてより多くのリクエストを処理できるようにするために、プロセスの**レプリケーション**を持つことを望むでしょう。 + +前のチャプターである[デプロイメントのコンセプト](./concepts.md){.internal-link target=_blank}にて見てきたように、有効な戦略がいくつかあります。 + +ここでは**Gunicorn**が**Uvicornのワーカー・プロセス**を管理する場合の使い方について紹介していきます。 + +!!! info + + DockerやKubernetesなどのコンテナを使用している場合は、次の章で詳しく説明します: [コンテナ内のFastAPI - Docker](./docker.md){.internal-link target=_blank} + + 特に**Kubernetes**上で実行する場合は、おそらく**Gunicornを使用せず**、**コンテナごとに単一のUvicornプロセス**を実行することになりますが、それについてはこの章の後半で説明します。 + +## GunicornによるUvicornのワーカー・プロセスの管理 + +**Gunicorn**は**WSGI標準**のアプリケーションサーバーです。このことは、GunicornはFlaskやDjangoのようなアプリケーションにサービスを提供できることを意味します。Gunicornそれ自体は**FastAPI**と互換性がないですが、というのもFastAPIは最新の**ASGI 標準**を使用しているためです。 + +しかし、Gunicornは**プロセスマネージャー**として動作し、ユーザーが特定の**ワーカー・プロセスクラス**を使用するように指示することができます。するとGunicornはそのクラスを使い1つ以上の**ワーカー・プロセス**を開始します。 + +そして**Uvicorn**には**Gunicorn互換のワーカークラス**があります。 + +この組み合わせで、Gunicornは**プロセスマネージャー**として動作し、**ポート**と**IP**をリッスンします。そして、**Uvicornクラス**を実行しているワーカー・プロセスに通信を**転送**します。 + +そして、Gunicorn互換の**Uvicornワーカー**クラスが、FastAPIが使えるように、Gunicornから送られてきたデータをASGI標準に変換する役割を担います。 + +## GunicornとUvicornをインストールする + +
+ +```console +$ pip install "uvicorn[standard]" gunicorn + +---> 100% +``` + +
+ +これによりUvicornと(高性能を得るための)標準(`standard`)の追加パッケージとGunicornの両方がインストールされます。 + +## UvicornのワーカーとともにGunicornを実行する + +Gunicornを以下のように起動させることができます: + +
+ +```console +$ gunicorn main:app --workers 4 --worker-class uvicorn.workers.UvicornWorker --bind 0.0.0.0:80 + +[19499] [INFO] Starting gunicorn 20.1.0 +[19499] [INFO] Listening at: http://0.0.0.0:80 (19499) +[19499] [INFO] Using worker: uvicorn.workers.UvicornWorker +[19511] [INFO] Booting worker with pid: 19511 +[19513] [INFO] Booting worker with pid: 19513 +[19514] [INFO] Booting worker with pid: 19514 +[19515] [INFO] Booting worker with pid: 19515 +[19511] [INFO] Started server process [19511] +[19511] [INFO] Waiting for application startup. +[19511] [INFO] Application startup complete. +[19513] [INFO] Started server process [19513] +[19513] [INFO] Waiting for application startup. +[19513] [INFO] Application startup complete. +[19514] [INFO] Started server process [19514] +[19514] [INFO] Waiting for application startup. +[19514] [INFO] Application startup complete. +[19515] [INFO] Started server process [19515] +[19515] [INFO] Waiting for application startup. +[19515] [INFO] Application startup complete. +``` + +
+ +それぞれのオプションの意味を見てみましょう: + +* `main:app`: `main`は"`main`"という名前のPythonモジュール、つまりファイル`main.py`を意味します。そして `app` は **FastAPI** アプリケーションの変数名です。 + * main:app`はPythonの`import`文と同じようなものだと想像できます: + + ```Python + from main import app + ``` + + * つまり、`main:app`のコロンは、`from main import app`のPythonの`import`の部分と同じになります。 + +* `--workers`: 使用するワーカー・プロセスの数で、それぞれがUvicornのワーカーを実行します。 + +* `--worker-class`: ワーカー・プロセスで使用するGunicorn互換のワーカークラスです。 + * ここではGunicornがインポートして使用できるクラスを渡します: + + ```Python + import uvicorn.workers.UvicornWorker + ``` + +* `--bind`: GunicornにリッスンするIPとポートを伝えます。コロン(`:`)でIPとポートを区切ります。 + * Uvicornを直接実行している場合は、`--bind 0.0.0.0:80` (Gunicornのオプション)の代わりに、`--host 0.0.0.0`と `--port 80`を使います。 + +出力では、各プロセスの**PID**(プロセスID)が表示されているのがわかります(単なる数字です)。 + +以下の通りです: + +* Gunicornの**プロセス・マネージャー**はPID `19499`(あなたの場合は違う番号でしょう)で始まります。 +* 次に、`Listening at: http://0.0.0.0:80`を開始します。 +* それから `uvicorn.workers.UvicornWorker` でワーカークラスを使用することを検出します。 +* そして、**4つのワーカー**を起動します。それぞれのワーカーのPIDは、`19511`、`19513`、`19514`、`19515`です。 + +Gunicornはまた、ワーカーの数を維持するために必要であれば、**ダウンしたプロセス**を管理し、**新しいプロセスを**再起動**させます。そのため、上記のリストにある**再起動**の概念に一部役立ちます。 + +しかしながら、必要であればGunicornを**再起動**させ、**起動時に実行**させるなど、外部のコンポーネントを持たせることも必要かもしれません。 + +## Uvicornとワーカー + +Uvicornには複数の**ワーカー・プロセス**を起動し実行するオプションもあります。 + +とはいうものの、今のところUvicornのワーカー・プロセスを扱う機能はGunicornよりも制限されています。そのため、このレベル(Pythonレベル)でプロセスマネージャーを持ちたいのであれば、Gunicornをプロセスマネージャーとして使ってみた方が賢明かもしれないです。 + +どんな場合であれ、以下のように実行します: + +
+ +```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. +``` + +
+ +ここで唯一の新しいオプションは `--workers` で、Uvicornに4つのワーカー・プロセスを起動するように指示しています。 + +各プロセスの **PID** が表示され、親プロセスの `27365` (これは **プロセスマネージャ**) と、各ワーカー・プロセスの **PID** が表示されます: `27368`、`27369`、`27370`、`27367`になります。 + +## デプロイメントのコンセプト + +ここでは、アプリケーションの実行を**並列化**し、CPUの**マルチコア**を活用し、**より多くのリクエスト**に対応できるようにするために、**Gunicorn**(またはUvicorn)を使用して**Uvicornワーカー・プロセス**を管理する方法を見ていきました。 + +上記のデプロイのコンセプトのリストから、ワーカーを使うことは主に**レプリケーション**の部分と、**再起動**を少し助けてくれます: + +* セキュリティ - HTTPS +* 起動時の実行 +* 再起動 +* レプリケーション(実行中のプロセス数) +* メモリー +* 開始前の事前のステップ + + +## コンテナとDocker + +次章の[コンテナ内のFastAPI - Docker](./docker.md){.internal-link target=_blank}では、その他の**デプロイのコンセプト**を扱うために実施するであろう戦略をいくつか紹介します。 + +また、**GunicornとUvicornワーカー**を含む**公式Dockerイメージ**と、簡単なケースに役立ついくつかのデフォルト設定も紹介します。 + +また、(Gunicornを使わずに)Uvicornプロセスを1つだけ実行するために、**ゼロから独自のイメージを**構築する方法も紹介します。これは簡単なプロセスで、おそらく**Kubernetes**のような分散コンテナ管理システムを使うときにやりたいことでしょう。 + +## まとめ + +Uvicornワーカーを使ったプロセスマネージャとして**Gunicorn**(またはUvicorn)を使えば、**マルチコアCPU**を活用して**複数のプロセスを並列実行**できます。 + +これらのツールやアイデアは、**あなた自身のデプロイシステム**をセットアップしながら、他のデプロイコンセプトを自分で行う場合にも使えます。 + +次の章では、コンテナ(DockerやKubernetesなど)を使った**FastAPI**について学んでいきましょう。これらのツールには、他の**デプロイのコンセプト**も解決する簡単な方法があることがわかるでしょう。✨ diff --git a/docs/ja/docs/external-links.md b/docs/ja/docs/external-links.md index 6703f5fc26b3d..aca5d5b34beb2 100644 --- a/docs/ja/docs/external-links.md +++ b/docs/ja/docs/external-links.md @@ -9,70 +9,21 @@ !!! tip "豆知識" ここにまだ載っていない**FastAPI**に関連する記事、プロジェクト、ツールなどがある場合は、 プルリクエストして下さい。 -## 記事 +{% for section_name, section_content in external_links.items() %} -### 英語 +## {{ section_name }} -{% if external_links %} -{% for article in external_links.articles.english %} +{% for lang_name, lang_content in section_content.items() %} -* {{ article.title }} by {{ article.author }}. -{% endfor %} -{% endif %} - -### 日本語 - -{% if external_links %} -{% for article in external_links.articles.japanese %} - -* {{ article.title }} by {{ article.author }}. -{% endfor %} -{% endif %} +### {{ lang_name }} -### ベトナム語 +{% for item in lang_content %} -{% if external_links %} -{% for article in external_links.articles.vietnamese %} +* {{ item.title }} by {{ item.author }}. -* {{ article.title }} by {{ article.author }}. {% endfor %} -{% endif %} - -### ロシア語 - -{% if external_links %} -{% for article in external_links.articles.russian %} - -* {{ article.title }} by {{ article.author }}. {% endfor %} -{% endif %} - -### ドイツ語 - -{% if external_links %} -{% for article in external_links.articles.german %} - -* {{ article.title }} by {{ article.author }}. -{% endfor %} -{% endif %} - -## ポッドキャスト - -{% if external_links %} -{% for article in external_links.podcasts.english %} - -* {{ article.title }} by {{ article.author }}. -{% endfor %} -{% endif %} - -## トーク - -{% if external_links %} -{% for article in external_links.talks.english %} - -* {{ article.title }} by {{ article.author }}. {% endfor %} -{% endif %} ## プロジェクト diff --git a/docs/ja/docs/fastapi-people.md b/docs/ja/docs/fastapi-people.md index 11dd656eaf31b..ff75dcbce65b2 100644 --- a/docs/ja/docs/fastapi-people.md +++ b/docs/ja/docs/fastapi-people.md @@ -41,7 +41,7 @@ FastAPIには、様々なバックグラウンドの人々を歓迎する素晴 {% if people %}
-{% for user in people.last_month_active %} +{% for user in people.last_month_experts[:10] %}
@{{ user.login }}
Issues replied: {{ user.count }}
{% endfor %} @@ -59,7 +59,7 @@ FastAPIには、様々なバックグラウンドの人々を歓迎する素晴 {% if people %}
-{% for user in people.experts %} +{% for user in people.experts[:50] %}
@{{ user.login }}
Issues replied: {{ user.count }}
{% endfor %} @@ -77,7 +77,7 @@ FastAPIには、様々なバックグラウンドの人々を歓迎する素晴 {% if people %}
-{% for user in people.top_contributors %} +{% for user in people.top_contributors[:50] %}
@{{ user.login }}
Pull Requests: {{ user.count }}
{% endfor %} @@ -101,7 +101,7 @@ FastAPIには、様々なバックグラウンドの人々を歓迎する素晴 {% if people %}
-{% for user in people.top_reviewers %} +{% for user in people.top_translations_reviewers[:50] %}
@{{ user.login }}
Reviews: {{ user.count }}
{% endfor %} diff --git a/docs/ja/docs/features.md b/docs/ja/docs/features.md index a40b48cf0ed8f..98c59e7c49588 100644 --- a/docs/ja/docs/features.md +++ b/docs/ja/docs/features.md @@ -24,7 +24,7 @@ ### 現代的なPython -FastAPIの機能はすべて、標準のPython 3.6型宣言に基づいています(Pydanticの功績)。新しい構文はありません。ただの現代的な標準のPythonです。 +FastAPIの機能はすべて、標準のPython 3.8型宣言に基づいています(Pydanticの功績)。新しい構文はありません。ただの現代的な標準のPythonです。 (FastAPIを使用しない場合でも)Pythonの型の使用方法について簡単な復習が必要な場合は、短いチュートリアル([Python Types](python-types.md){.internal-link target=_blank})を参照してください。 @@ -177,7 +177,7 @@ FastAPIには非常に使いやすく、非常に強力なIDE/リンター/思考 とうまく連携します**: * Pydanticのデータ構造は、ユーザーが定義するクラスの単なるインスタンスであるため、オートコンプリート、リンティング、mypy、およびユーザーの直感はすべて、検証済みのデータで適切に機能するはずです。 -* **高速**: - * ベンチマークでは、Pydanticは他のすべてのテスト済みライブラリよりも高速です。 * **複雑な構造**を検証: * 階層的なPydanticモデルや、Pythonの「`typing`」の「`list`」と「`dict`」などの利用。 * バリデーターにより、複雑なデータスキーマを明確かつ簡単に定義、チェックし、JSONスキーマとして文書化できます。 diff --git a/docs/ja/docs/help-fastapi.md b/docs/ja/docs/help-fastapi.md index 166acb5869d04..e753b7ce3756e 100644 --- a/docs/ja/docs/help-fastapi.md +++ b/docs/ja/docs/help-fastapi.md @@ -82,20 +82,6 @@ GitHubレポジトリでhttps://gitter.im/tiangolo/fastapi. - -そこで、他の人と手早く会話したり、手助けやアイデアの共有などができます。 - -しかし、「自由な会話」が許容されているので一般的すぎて回答が難しい質問もしやすくなります。そのせいで回答を得られないかもしれません。 - -GitHub issuesでは良い回答を得やすい質問ができるように、もしくは、質問する前に自身で解決できるようにテンプレートがガイドしてくれます。そして、GitHubではたとえ時間がかかっても全てに答えているか確認できます。個人的にはGitterチャットでは同じことはできないです。😅 - -Gitterでの会話はGitHubほど簡単に検索できないので、質問と回答が会話の中に埋もれてしまいます。 - -一方、チャットには1000人以上いるので、いつでも話し相手が見つかる可能性が高いです。😄 - ## 開発者のスポンサーになる GitHub sponsorsを通して開発者を経済的にサポートできます。 diff --git a/docs/ja/docs/history-design-future.md b/docs/ja/docs/history-design-future.md index d0d1230c4b9d0..5d53cf77a61b9 100644 --- a/docs/ja/docs/history-design-future.md +++ b/docs/ja/docs/history-design-future.md @@ -55,7 +55,7 @@ ## 要件 -いくつかの代替手法を試したあと、私は**Pydantic**の強みを利用することを決めました。 +いくつかの代替手法を試したあと、私は**Pydantic**の強みを利用することを決めました。 そして、JSON Schemaに完全に準拠するようにしたり、制約宣言を定義するさまざまな方法をサポートしたり、いくつかのエディターでのテストに基づいてエディターのサポート (型チェック、自動補完) を改善するために貢献しました。 diff --git a/docs/ja/docs/advanced/conditional-openapi.md b/docs/ja/docs/how-to/conditional-openapi.md similarity index 100% rename from docs/ja/docs/advanced/conditional-openapi.md rename to docs/ja/docs/how-to/conditional-openapi.md diff --git a/docs/ja/docs/index.md b/docs/ja/docs/index.md index a9c381a23c7e5..4f66b1a40ea77 100644 --- a/docs/ja/docs/index.md +++ b/docs/ja/docs/index.md @@ -24,7 +24,7 @@ --- -FastAPI は、Pythonの標準である型ヒントに基づいてPython 3.6 以降でAPI を構築するための、モダンで、高速(高パフォーマンス)な、Web フレームワークです。 +FastAPI は、Pythonの標準である型ヒントに基づいてPython 3.8 以降でAPI を構築するための、モダンで、高速(高パフォーマンス)な、Web フレームワークです。 主な特徴: @@ -107,12 +107,12 @@ FastAPI は、Pythonの標準である型ヒントに基づいてPython 3.6 以 ## 必要条件 -Python 3.7+ +Python 3.8+ FastAPI は巨人の肩の上に立っています。 - Web の部分はStarlette -- データの部分はPydantic +- データの部分はPydantic ## インストール @@ -317,7 +317,7 @@ def update_item(item_id: int, item: Item): 新しい構文や特定のライブラリのメソッドやクラスなどを覚える必要はありません。 -単なる標準的な**3.6 以降の Python**です。 +単なる標準的な**3.8 以降の Python**です。 例えば、`int`の場合: @@ -437,7 +437,7 @@ Starlette によって使用されるもの: - httpx - `TestClient`を使用するために必要です。 - jinja2 - デフォルトのテンプレート設定を使用する場合は必要です。 -- python-multipart - "parsing"`request.form()`からの変換をサポートしたい場合は必要です。 +- python-multipart - "parsing"`request.form()`からの変換をサポートしたい場合は必要です。 - itsdangerous - `SessionMiddleware` サポートのためには必要です。 - pyyaml - Starlette の `SchemaGenerator` サポートのために必要です。 (FastAPI では必要ないでしょう。) - graphene - `GraphQLApp` サポートのためには必要です。 diff --git a/docs/ja/docs/python-types.md b/docs/ja/docs/python-types.md new file mode 100644 index 0000000000000..f8e02fdc3e657 --- /dev/null +++ b/docs/ja/docs/python-types.md @@ -0,0 +1,315 @@ +# Pythonの型の紹介 + +**Python 3.6以降** では「型ヒント」オプションがサポートされています。 + +これらの **"型ヒント"** は変数のを宣言することができる新しい構文です。(Python 3.6以降) + +変数に型を宣言することでエディターやツールがより良いサポートを提供することができます。 + +ここではPythonの型ヒントについての **クイックチュートリアル/リフレッシュ** で、**FastAPI**でそれらを使用するために必要な最低限のことだけをカバーしています。...実際には本当に少ないです。 + +**FastAPI** はすべてこれらの型ヒントに基づいており、多くの強みと利点を与えてくれます。 + +しかしたとえまったく **FastAPI** を使用しない場合でも、それらについて少し学ぶことで利点を得ることができるでしょう。 + +!!! note "備考" + もしあなたがPythonの専門家で、すでに型ヒントについてすべて知っているのであれば、次の章まで読み飛ばしてください。 + +## 動機 + +簡単な例から始めてみましょう: + +```Python +{!../../../docs_src/python_types/tutorial001.py!} +``` + +このプログラムを実行すると以下が出力されます: + +``` +John Doe +``` + +この関数は以下のようなことを行います: + +* `first_name`と`last_name`を取得します。 +* `title()`を用いて、それぞれの最初の文字を大文字に変換します。 +* 真ん中にスペースを入れて連結します。 + +```Python hl_lines="2" +{!../../../docs_src/python_types/tutorial001.py!} +``` + +### 編集 + +これはとても簡単なプログラムです。 + +しかし、今、あなたがそれを一から書いていたと想像してみてください。 + +パラメータの準備ができていたら、そのとき、関数の定義を始めていたことでしょう... + +しかし、そうすると「最初の文字を大文字に変換するあのメソッド」を呼び出す必要があります。 + +それは`upper`でしたか?`uppercase`でしたか?それとも`first_uppercase`?または`capitalize`? + +そして、古くからプログラマーの友人であるエディタで自動補完を試してみます。 + +関数の最初のパラメータ`first_name`を入力し、ドット(`.`)を入力してから、`Ctrl+Space`を押すと補完が実行されます。 + +しかし、悲しいことに、これはなんの役にも立ちません: + + + +### 型の追加 + +先ほどのコードから一行変更してみましょう。 + +以下の関数のパラメータ部分を: + +```Python + first_name, last_name +``` + +以下へ変更します: + +```Python + first_name: str, last_name: str +``` + +これだけです。 + +それが「型ヒント」です: + +```Python hl_lines="1" +{!../../../docs_src/python_types/tutorial002.py!} +``` + +これは、以下のようにデフォルト値を宣言するのと同じではありません: + +```Python + first_name="john", last_name="doe" +``` + +それとは別物です。 + +イコール(`=`)ではなく、コロン(`:`)を使用します。 + +そして、通常、型ヒントを追加しても、それらがない状態と起こることは何も変わりません。 + +しかし今、あなたが再びその関数を作成している最中に、型ヒントを使っていると想像してみて下さい。 + +同じタイミングで`Ctrl+Space`で自動補完を実行すると、以下のようになります: + + + +これであれば、あなたは「ベルを鳴らす」一つを見つけるまで、オプションを見て、スクロールすることができます: + + + +## より強い動機 + +この関数を見てください。すでに型ヒントを持っています: + +```Python hl_lines="1" +{!../../../docs_src/python_types/tutorial003.py!} +``` + +エディタは変数の型を知っているので、補完だけでなく、エラーチェックをすることもできます。 + + + +これで`age`を`str(age)`で文字列に変換して修正する必要があることがわかります: + +```Python hl_lines="2" +{!../../../docs_src/python_types/tutorial004.py!} +``` + +## 型の宣言 + +関数のパラメータとして、型ヒントを宣言している主な場所を確認しました。 + +これは **FastAPI** で使用する主な場所でもあります。 + +### 単純な型 + +`str`だけでなく、Pythonの標準的な型すべてを宣言することができます。 + +例えば、以下を使用可能です: + +* `int` +* `float` +* `bool` +* `bytes` + +```Python hl_lines="1" +{!../../../docs_src/python_types/tutorial005.py!} +``` + +### 型パラメータを持つジェネリック型 + +データ構造の中には、`dict`、`list`、`set`、そして`tuple`のように他の値を含むことができるものがあります。また内部の値も独自の型を持つことができます。 + +これらの型や内部の型を宣言するには、Pythonの標準モジュール`typing`を使用します。 + +これらの型ヒントをサポートするために特別に存在しています。 + +#### `List` + +例えば、`str`の`list`の変数を定義してみましょう。 + +`typing`から`List`をインポートします(大文字の`L`を含む): + +```Python hl_lines="1" +{!../../../docs_src/python_types/tutorial006.py!} +``` + +同じようにコロン(`:`)の構文で変数を宣言します。 + +型として、`List`を入力します。 + +リストはいくつかの内部の型を含む型なので、それらを角括弧で囲んでいます。 + +```Python hl_lines="4" +{!../../../docs_src/python_types/tutorial006.py!} +``` + +!!! tip "豆知識" + 角括弧内の内部の型は「型パラメータ」と呼ばれています。 + + この場合、`str`は`List`に渡される型パラメータです。 + +つまり: 変数`items`は`list`であり、このリストの各項目は`str`です。 + +そうすることで、エディタはリストの項目を処理している間にもサポートを提供できます。 + + + +タイプがなければ、それはほぼ不可能です。 + +変数`item`はリスト`items`の要素の一つであることに注意してください。 + +それでも、エディタはそれが`str`であることを知っていて、そのためのサポートを提供しています。 + +#### `Tuple` と `Set` + +`tuple`と`set`の宣言も同様です: + +```Python hl_lines="1 4" +{!../../../docs_src/python_types/tutorial007.py!} +``` + +つまり: + +* 変数`items_t`は`int`、`int`、`str`の3つの項目を持つ`tuple`です + +* 変数`items_s`はそれぞれの項目が`bytes`型である`set`です。 + +#### `Dict` + +`dict`を宣言するためには、カンマ区切りで2つの型パラメータを渡します。 + +最初の型パラメータは`dict`のキーです。 + +2番目の型パラメータは`dict`の値です。 + +```Python hl_lines="1 4" +{!../../../docs_src/python_types/tutorial008.py!} +``` + +つまり: + +* 変数`prices`は`dict`であり: + * この`dict`のキーは`str`型です。(つまり、各項目の名前) + * この`dict`の値は`float`型です。(つまり、各項目の価格) + +#### `Optional` + +また、`Optional`を使用して、変数が`str`のような型を持つことを宣言することもできますが、それは「オプション」であり、`None`にすることもできます。 + +```Python hl_lines="1 4" +{!../../../docs_src/python_types/tutorial009.py!} +``` + +ただの`str`の代わりに`Optional[str]`を使用することで、エディタは値が常に`str`であると仮定している場合に実際には`None`である可能性があるエラーを検出するのに役立ちます。 + +#### ジェネリック型 + +以下のように角括弧で型パラメータを取る型を: + +* `List` +* `Tuple` +* `Set` +* `Dict` +* `Optional` +* ...など + +**ジェネリック型** または **ジェネリクス** と呼びます。 + +### 型としてのクラス + +変数の型としてクラスを宣言することもできます。 + +例えば、`Person`クラスという名前のクラスがあるとしましょう: + +```Python hl_lines="1 2 3" +{!../../../docs_src/python_types/tutorial010.py!} +``` + +変数の型を`Person`として宣言することができます: + +```Python hl_lines="6" +{!../../../docs_src/python_types/tutorial010.py!} +``` + +そして、再び、すべてのエディタのサポートを得ることができます: + + + +## Pydanticのモデル + +Pydantic はデータ検証を行うためのPythonライブラリです。 + +データの「形」を属性付きのクラスとして宣言します。 + +そして、それぞれの属性は型を持ちます。 + +さらに、いくつかの値を持つクラスのインスタンスを作成すると、その値を検証し、適切な型に変換して(もしそうであれば)全てのデータを持つオブジェクトを提供してくれます。 + +また、その結果のオブジェクトですべてのエディタのサポートを受けることができます。 + +Pydanticの公式ドキュメントから引用: + +```Python +{!../../../docs_src/python_types/tutorial011.py!} +``` + +!!! info "情報" + Pydanticについてより学びたい方はドキュメントを参照してください. + +**FastAPI** はすべてPydanticをベースにしています。 + +すべてのことは[チュートリアル - ユーザーガイド](tutorial/index.md){.internal-link target=_blank}で実際に見ることができます。 + +## **FastAPI**での型ヒント + +**FastAPI** はこれらの型ヒントを利用していくつかのことを行います。 + +**FastAPI** では型ヒントを使って型パラメータを宣言すると以下のものが得られます: + +* **エディタサポート**. +* **型チェック**. + +...そして **FastAPI** は同じように宣言をすると、以下のことを行います: + +* **要件の定義**: リクエストパスパラメータ、クエリパラメータ、ヘッダー、ボディ、依存関係などから要件を定義します。 +* **データの変換**: リクエストのデータを必要な型に変換します。 +* **データの検証**: リクエストごとに: + * データが無効な場合にクライアントに返される **自動エラー** を生成します。 +* **ドキュメント** OpenAPIを使用したAPI: + * 自動的に対話型ドキュメントのユーザーインターフェイスで使用されます。 + +すべてが抽象的に聞こえるかもしれません。心配しないでください。 この全ての動作は [チュートリアル - ユーザーガイド](tutorial/index.md){.internal-link target=_blank}で見ることができます。 + +重要なのは、Pythonの標準的な型を使うことで、(クラスやデコレータなどを追加するのではなく)1つの場所で **FastAPI** が多くの作業を代わりにやってくれているということです。 + +!!! info "情報" + すでにすべてのチュートリアルを終えて、型についての詳細を見るためにこのページに戻ってきた場合は、`mypy`のチートシートを参照してください diff --git a/docs/ja/docs/tutorial/background-tasks.md b/docs/ja/docs/tutorial/background-tasks.md new file mode 100644 index 0000000000000..6094c370fde65 --- /dev/null +++ b/docs/ja/docs/tutorial/background-tasks.md @@ -0,0 +1,94 @@ +# バックグラウンドタスク + +レスポンスを返した *後に* 実行されるバックグラウンドタスクを定義できます。 + +これは、リクエスト後に処理を開始する必要があるが、クライアントがレスポンスを受け取る前に処理を終える必要のない操作に役立ちます。 + +これには、たとえば次のものが含まれます。 + +* 作業実行後のメール通知: + * メールサーバーへの接続とメールの送信は「遅い」(数秒) 傾向があるため、すぐにレスポンスを返し、バックグラウンドでメール通知ができます。 +* データ処理: + * たとえば、時間のかかる処理を必要とするファイル受信時には、「受信済み」(HTTP 202) のレスポンスを返し、バックグラウンドで処理できます。 + +## `BackgroundTasks` の使用 + +まず初めに、`BackgroundTasks` をインポートし、` BackgroundTasks` の型宣言と共に、*path operation 関数* のパラメーターを定義します: + +```Python hl_lines="1 13" +{!../../../docs_src/background_tasks/tutorial001.py!} +``` + +**FastAPI** は、`BackgroundTasks` 型のオブジェクトを作成し、そのパラメーターに渡します。 + +## タスク関数の作成 + +バックグラウンドタスクとして実行される関数を作成します。 + +これは、パラメーターを受け取ることができる単なる標準的な関数です。 + +これは `async def` または通常の `def` 関数であり、**FastAPI** はこれを正しく処理します。 + +ここで、タスク関数はファイル書き込みを実行します (メール送信のシミュレーション)。 + +また、書き込み操作では `async` と `await` を使用しないため、通常の `def` で関数を定義します。 + +```Python hl_lines="6-9" +{!../../../docs_src/background_tasks/tutorial001.py!} +``` + +## バックグラウンドタスクの追加 + +*path operations 関数* 内で、`.add_task()` メソッドを使用してタスク関数を *background tasks* オブジェクトに渡します。 + +```Python hl_lines="14" +{!../../../docs_src/background_tasks/tutorial001.py!} +``` + +`.add_task()` は以下の引数を受け取ります: + +* バックグラウンドで実行されるタスク関数 (`write_notification`)。 +* タスク関数に順番に渡す必要のある引数の列 (`email`)。 +* タスク関数に渡す必要のあるキーワード引数 (`message="some notification"`)。 + +## 依存性注入 + +`BackgroundTasks` の使用は依存性注入システムでも機能し、様々な階層 (*path operations 関数*、依存性 (依存可能性)、サブ依存性など) で `BackgroundTasks` 型のパラメーターを宣言できます。 + +**FastAPI** は、それぞれの場合の処理​​方法と同じオブジェクトの再利用方法を知っているため、すべてのバックグラウンドタスクがマージされ、バックグラウンドで後で実行されます。 + +```Python hl_lines="13 15 22 25" +{!../../../docs_src/background_tasks/tutorial002.py!} +``` + +この例では、レスポンスが送信された *後* にメッセージが `log.txt` ファイルに書き込まれます。 + +リクエストにクエリがあった場合、バックグラウンドタスクでログに書き込まれます。 + +そして、*path operations 関数* で生成された別のバックグラウンドタスクは、`email` パスパラメータを使用してメッセージを書き込みます。 + +## 技術的な詳細 + +`BackgroundTasks` クラスは、`starlette.background`から直接取得されます。 + +これは、FastAPI に直接インポート/インクルードされるため、`fastapi` からインポートできる上に、`starlette.background`から別の `BackgroundTask` (末尾に `s` がない) を誤ってインポートすることを回避できます。 + +`BackgroundTasks`のみを使用することで (`BackgroundTask` ではなく)、`Request` オブジェクトを直接使用する場合と同様に、それを *path operations 関数* パラメーターとして使用し、**FastAPI** に残りの処理を任せることができます。 + +それでも、FastAPI で `BackgroundTask` を単独で使用することは可能ですが、コード内でオブジェクトを作成し、それを含むStarlette `Response` を返す必要があります。 + +詳細については、バックグラウンドタスクに関する Starlette の公式ドキュメントを参照して下さい。 + +## 警告 + +大量のバックグラウンド計算が必要であり、必ずしも同じプロセスで実行する必要がない場合 (たとえば、メモリや変数などを共有する必要がない場合)、Celery のようなより大きな他のツールを使用するとメリットがあるかもしれません。 + +これらは、より複雑な構成、RabbitMQ や Redis などのメッセージ/ジョブキューマネージャーを必要とする傾向がありますが、複数のプロセス、特に複数のサーバーでバックグラウンドタスクを実行できます。 + +例を確認するには、[Project Generators](../project-generation.md){.internal-link target=_blank} を参照してください。これらにはすべて、Celery が構築済みです。 + +ただし、同じ **FastAPI** アプリから変数とオブジェクトにアクセスする必要がある場合、または小さなバックグラウンドタスク (電子メール通知の送信など) を実行する必要がある場合は、単に `BackgroundTasks` を使用できます。 + +## まとめ + +`BackgroundTasks` をインポートして、*path operations 関数* や依存関係のパラメータに `BackgroundTasks`を使用し、バックグラウンドタスクを追加して下さい。 diff --git a/docs/ja/docs/tutorial/body-fields.md b/docs/ja/docs/tutorial/body-fields.md new file mode 100644 index 0000000000000..8f01e821624d0 --- /dev/null +++ b/docs/ja/docs/tutorial/body-fields.md @@ -0,0 +1,48 @@ +# ボディ - フィールド + +`Query`や`Path`、`Body`を使って *path operation関数* のパラメータに追加のバリデーションやメタデータを宣言するのと同じように、Pydanticの`Field`を使ってPydanticモデルの内部でバリデーションやメタデータを宣言することができます。 + +## `Field`のインポート + +まず、以下のようにインポートします: + +```Python hl_lines="4" +{!../../../docs_src/body_fields/tutorial001.py!} +``` + +!!! warning "注意" + `Field`は他の全てのもの(`Query`、`Path`、`Body`など)とは違い、`fastapi`からではなく、`pydantic`から直接インポートされていることに注意してください。 + +## モデルの属性の宣言 + +以下のように`Field`をモデルの属性として使用することができます: + +```Python hl_lines="11 12 13 14" +{!../../../docs_src/body_fields/tutorial001.py!} +``` + +`Field`は`Query`や`Path`、`Body`と同じように動作し、全く同様のパラメータなどを持ちます。 + +!!! note "技術詳細" + 実際には次に見る`Query`や`Path`などは、共通の`Param`クラスのサブクラスのオブジェクトを作成しますが、それ自体はPydanticの`FieldInfo`クラスのサブクラスです。 + + また、Pydanticの`Field`は`FieldInfo`のインスタンスも返します。 + + `Body`は`FieldInfo`のサブクラスのオブジェクトを直接返すこともできます。そして、他にも`Body`クラスのサブクラスであるものがあります。 + + `fastapi`から`Query`や`Path`などをインポートする場合、これらは実際には特殊なクラスを返す関数であることに注意してください。 + +!!! tip "豆知識" + 型、デフォルト値、`Field`を持つ各モデルの属性が、`Path`や`Query`、`Body`の代わりに`Field`を持つ、*path operation 関数の*パラメータと同じ構造になっていることに注目してください。 + +## 追加情報の追加 + +追加情報は`Field`や`Query`、`Body`などで宣言することができます。そしてそれは生成されたJSONスキーマに含まれます。 + +後に例を用いて宣言を学ぶ際に、追加情報を句悪方法を学べます。 + +## まとめ + +Pydanticの`Field`を使用して、モデルの属性に追加のバリデーションやメタデータを宣言することができます。 + +追加のキーワード引数を使用して、追加のJSONスキーマのメタデータを渡すこともできます。 diff --git a/docs/ja/docs/tutorial/body-multiple-params.md b/docs/ja/docs/tutorial/body-multiple-params.md new file mode 100644 index 0000000000000..2ba10c583e1b7 --- /dev/null +++ b/docs/ja/docs/tutorial/body-multiple-params.md @@ -0,0 +1,169 @@ +# ボディ - 複数のパラメータ + +これまで`Path`と`Query`をどう使うかを見てきましたが、リクエストボディの宣言のより高度な使い方を見てみましょう。 + +## `Path`、`Query`とボディパラメータを混ぜる + +まず、もちろん、`Path`と`Query`とリクエストボディのパラメータの宣言は自由に混ぜることができ、 **FastAPI** は何をするべきかを知っています。 + +また、デフォルトの`None`を設定することで、ボディパラメータをオプションとして宣言することもできます: + +```Python hl_lines="19 20 21" +{!../../../docs_src/body_multiple_params/tutorial001.py!} +``` + +!!! note "備考" + この場合、ボディから取得する`item`はオプションであることに注意してください。デフォルト値は`None`です。 + +## 複数のボディパラメータ + +上述の例では、*path operations*は`item`の属性を持つ以下のようなJSONボディを期待していました: + +```JSON +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 +} +``` + +しかし、`item`と`user`のように複数のボディパラメータを宣言することもできます: + +```Python hl_lines="22" +{!../../../docs_src/body_multiple_params/tutorial002.py!} +``` + +この場合、**FastAPI**は関数内に複数のボディパラメータ(Pydanticモデルである2つのパラメータ)があることに気付きます。 + +そのため、パラメータ名をボディのキー(フィールド名)として使用し、以下のようなボディを期待しています: + +```JSON +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + }, + "user": { + "username": "dave", + "full_name": "Dave Grohl" + } +} +``` + +!!! note "備考" + 以前と同じように`item`が宣言されていたにもかかわらず、`item`はキー`item`を持つボディの内部にあることが期待されていることに注意してください。 + +**FastAPI** はリクエストから自動で変換を行い、パラメータ`item`が特定の内容を受け取り、`user`も同じように特定の内容を受け取ります。 + +複合データの検証を行い、OpenAPIスキーマや自動ドキュメントのように文書化してくれます。 + +## ボディ内の単数値 + +クエリとパスパラメータの追加データを定義するための `Query` と `Path` があるのと同じように、 **FastAPI** は同等の `Body` を提供します。 + +例えば、前のモデルを拡張して、同じボディに `item` と `user` の他にもう一つのキー `importance` を入れたいと決めることができます。 + +単数値なのでそのまま宣言すると、**FastAPI** はそれがクエリパラメータであるとみなします。 + +しかし、`Body`を使用して、**FastAPI** に別のボディキーとして扱うように指示することができます: + + +```Python hl_lines="23" +{!../../../docs_src/body_multiple_params/tutorial003.py!} +``` + +この場合、**FastAPI** は以下のようなボディを期待します: + + +```JSON +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + }, + "user": { + "username": "dave", + "full_name": "Dave Grohl" + }, + "importance": 5 +} +``` + +繰り返しになりますが、データ型の変換、検証、文書化などを行います。 + +## 複数のボディパラメータとクエリ + +もちろん、ボディパラメータに加えて、必要に応じて追加のクエリパラメータを宣言することもできます。 + +デフォルトでは、単数値はクエリパラメータとして解釈されるので、明示的に `Query` を追加する必要はありません。 + +```Python +q: str = None +``` + +以下において: + +```Python hl_lines="27" +{!../../../docs_src/body_multiple_params/tutorial004.py!} +``` + +!!! info "情報" + `Body`もまた、後述する `Query` や `Path` などと同様に、すべての検証パラメータとメタデータパラメータを持っています。 + + +## 単一のボディパラメータの埋め込み + +Pydanticモデル`Item`のボディパラメータ`item`を1つだけ持っているとしましょう。 + +デフォルトでは、**FastAPI**はそのボディを直接期待します。 + +しかし、追加のボディパラメータを宣言したときのように、キー `item` を持つ JSON とその中のモデルの内容を期待したい場合は、特別な `Body` パラメータ `embed` を使うことができます: + +```Python +item: Item = Body(..., embed=True) +``` + +以下において: + +```Python hl_lines="17" +{!../../../docs_src/body_multiple_params/tutorial005.py!} +``` + +この場合、**FastAPI** は以下のようなボディを期待します: + +```JSON hl_lines="2" +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + } +} +``` + +以下の代わりに: + +```JSON +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 +} +``` + +## まとめ + +リクエストが単一のボディしか持てない場合でも、*path operation関数*に複数のボディパラメータを追加することができます。 + +しかし、**FastAPI** はそれを処理し、関数内の正しいデータを与え、*path operation*内の正しいスキーマを検証し、文書化します。 + +また、ボディの一部として受け取る単数値を宣言することもできます。 + +また、単一のパラメータしか宣言されていない場合でも、ボディをキーに埋め込むように **FastAPI** に指示することができます。 diff --git a/docs/ja/docs/tutorial/body-nested-models.md b/docs/ja/docs/tutorial/body-nested-models.md new file mode 100644 index 0000000000000..092e257986065 --- /dev/null +++ b/docs/ja/docs/tutorial/body-nested-models.md @@ -0,0 +1,244 @@ +# ボディ - ネストされたモデル + +**FastAPI** を使用すると、深くネストされた任意のモデルを定義、検証、文書化、使用することができます(Pydanticのおかげです)。 + +## リストのフィールド + +属性をサブタイプとして定義することができます。例えば、Pythonの`list`は以下のように定義できます: + +```Python hl_lines="12" +{!../../../docs_src/body_nested_models/tutorial001.py!} +``` + +これにより、各項目の型は宣言されていませんが、`tags`はある項目のリストになります。 + +## タイプパラメータを持つリストのフィールド + +しかし、Pythonには型や「タイプパラメータ」を使ってリストを宣言する方法があります: + +### typingの`List`をインポート + +まず、Pythonの標準の`typing`モジュールから`List`をインポートします: + +```Python hl_lines="1" +{!../../../docs_src/body_nested_models/tutorial002.py!} +``` + +### タイプパラメータを持つ`List`の宣言 + +`list`や`dict`、`tuple`のようなタイプパラメータ(内部の型)を持つ型を宣言するには: + +* `typing`モジュールからそれらをインストールします。 +* 角括弧(`[`と`]`)を使って「タイプパラメータ」として内部の型を渡します: + +```Python +from typing import List + +my_list: List[str] +``` + +型宣言の標準的なPythonの構文はこれだけです。 + +内部の型を持つモデルの属性にも同じ標準の構文を使用してください。 + +そのため、以下の例では`tags`を具体的な「文字列のリスト」にすることができます: + +```Python hl_lines="14" +{!../../../docs_src/body_nested_models/tutorial002.py!} +``` + +## セット型 + +しかし、よく考えてみると、タグは繰り返すべきではなく、おそらくユニークな文字列になるのではないかと気付いたとします。 + +そして、Pythonにはユニークな項目のセットのための特別なデータ型`set`があります。 + +そのため、以下のように、`Set`をインポートして`str`の`set`として`tags`を宣言することができます: + +```Python hl_lines="1 14" +{!../../../docs_src/body_nested_models/tutorial003.py!} +``` + +これを使えば、データが重複しているリクエストを受けた場合でも、ユニークな項目のセットに変換されます。 + +そして、そのデータを出力すると、たとえソースに重複があったとしても、固有の項目のセットとして出力されます。 + +また、それに応じて注釈をつけたり、文書化したりします。 + +## ネストされたモデル + +Pydanticモデルの各属性には型があります。 + +しかし、その型はそれ自体が別のPydanticモデルである可能性があります。 + +そのため、特定の属性名、型、バリデーションを指定して、深くネストしたJSON`object`を宣言することができます。 + +すべては、任意のネストにされています。 + +### サブモデルの定義 + +例えば、`Image`モデルを定義することができます: + +```Python hl_lines="9 10 11" +{!../../../docs_src/body_nested_models/tutorial004.py!} +``` + +### サブモデルを型として使用 + +そして、それを属性の型として使用することができます: + +```Python hl_lines="20" +{!../../../docs_src/body_nested_models/tutorial004.py!} +``` + +これは **FastAPI** が以下のようなボディを期待することを意味します: + +```JSON +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2, + "tags": ["rock", "metal", "bar"], + "image": { + "url": "http://example.com/baz.jpg", + "name": "The Foo live" + } +} +``` + +繰り返しになりますが、**FastAPI** を使用して、その宣言を行うだけで以下のような恩恵を受けられます: + +* ネストされたモデルでも対応可能なエディタのサポート(補完など) +* データ変換 +* データの検証 +* 自動文書化 + +## 特殊な型とバリデーション + +`str`や`int`、`float`のような通常の単数型の他にも、`str`を継承したより複雑な単数型を使うこともできます。 + +すべてのオプションをみるには、Pydanticのエキゾチック な型のドキュメントを確認してください。次の章でいくつかの例をみることができます。 + +例えば、`Image`モデルのように`url`フィールドがある場合、`str`の代わりにPydanticの`HttpUrl`を指定することができます: + +```Python hl_lines="4 10" +{!../../../docs_src/body_nested_models/tutorial005.py!} +``` + +文字列は有効なURLであることが確認され、そのようにJSONスキーマ・OpenAPIで文書化されます。 + +## サブモデルのリストを持つ属性 + +Pydanticモデルを`list`や`set`などのサブタイプとして使用することもできます: + +```Python hl_lines="20" +{!../../../docs_src/body_nested_models/tutorial006.py!} +``` + +これは、次のようなJSONボディを期待します(変換、検証、ドキュメントなど): + +```JSON hl_lines="11" +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2, + "tags": [ + "rock", + "metal", + "bar" + ], + "images": [ + { + "url": "http://example.com/baz.jpg", + "name": "The Foo live" + }, + { + "url": "http://example.com/dave.jpg", + "name": "The Baz" + } + ] +} +``` + +!!! info "情報" + `images`キーが画像オブジェクトのリストを持つようになったことに注目してください。 + +## 深くネストされたモデル + +深くネストされた任意のモデルを定義することができます: + +```Python hl_lines="9 14 20 23 27" +{!../../../docs_src/body_nested_models/tutorial007.py!} +``` + +!!! info "情報" + `Offer`は`Item`のリストであり、オプションの`Image`のリストを持っていることに注目してください。 + +## 純粋なリストのボディ + +期待するJSONボディのトップレベルの値がJSON`array`(Pythonの`list`)であれば、Pydanticモデルと同じように、関数のパラメータで型を宣言することができます: + +```Python +images: List[Image] +``` + +以下のように: + +```Python hl_lines="15" +{!../../../docs_src/body_nested_models/tutorial008.py!} +``` + +## あらゆる場所でのエディタサポート + +エディタのサポートもどこでも受けることができます。 + +以下のようにリストの中の項目でも: + + + +Pydanticモデルではなく、`dict`を直接使用している場合はこのようなエディタのサポートは得られません。 + +しかし、それらについて心配する必要はありません。入力された辞書は自動的に変換され、出力も自動的にJSONに変換されます。 + +## 任意の`dict`のボディ + +また、ある型のキーと別の型の値を持つ`dict`としてボディを宣言することもできます。 + +有効なフィールド・属性名を事前に知る必要がありません(Pydanticモデルの場合のように)。 + +これは、まだ知らないキーを受け取りたいときに便利だと思います。 + +--- + +他にも、`int`のように他の型のキーを持ちたい場合などに便利です。 + +それをここで見ていきましょう。 + +この場合、`int`のキーと`float`の値を持つものであれば、どんな`dict`でも受け入れることができます: + +```Python hl_lines="15" +{!../../../docs_src/body_nested_models/tutorial009.py!} +``` + +!!! tip "豆知識" + JSONはキーとして`str`しかサポートしていないことに注意してください。 + + しかしPydanticには自動データ変換機能があります。 + + これは、APIクライアントがキーとして文字列しか送信できなくても、それらの文字列に純粋な整数が含まれている限り、Pydanticが変換して検証することを意味します。 + + そして、`weights`として受け取る`dict`は、実際には`int`のキーと`float`の値を持つことになります。 + +## まとめ + +**FastAPI** を使用すると、Pydanticモデルが提供する最大限の柔軟性を持ちながら、コードをシンプルに短く、エレガントに保つことができます。 + +以下のような利点があります: + +* エディタのサポート(どこでも補完!) +* データ変換(別名:構文解析・シリアライズ) +* データの検証 +* スキーマ文書 +* 自動文書化 diff --git a/docs/ja/docs/tutorial/body.md b/docs/ja/docs/tutorial/body.md index d2559205bd576..12332991d063d 100644 --- a/docs/ja/docs/tutorial/body.md +++ b/docs/ja/docs/tutorial/body.md @@ -6,7 +6,7 @@ APIはほとんどの場合 **レスポンス** ボディを送らなければなりません。しかし、クライアントは必ずしも **リクエスト** ボディを送らなければいけないわけではありません。 -**リクエスト** ボディを宣言するために Pydantic モデルを使用します。そして、その全てのパワーとメリットを利用します。 +**リクエスト** ボディを宣言するために Pydantic モデルを使用します。そして、その全てのパワーとメリットを利用します。 !!! info "情報" データを送るには、`POST` (もっともよく使われる)、`PUT`、`DELETE` または `PATCH` を使うべきです。 diff --git a/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md new file mode 100644 index 0000000000000..5c150d00c50b7 --- /dev/null +++ b/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md @@ -0,0 +1,191 @@ +# 依存関係としてのクラス + +**依存性注入** システムを深く掘り下げる前に、先ほどの例をアップグレードしてみましょう。 + +## 前の例の`dict` + +前の例では、依存関係("dependable")から`dict`を返していました: + +```Python hl_lines="9" +{!../../../docs_src/dependencies/tutorial001.py!} +``` + +しかし、*path operation関数*のパラメータ`commons`に`dict`が含まれています。 + +また、エディタは`dict`のキーと値の型を知ることができないため、多くのサポート(補完のような)を提供することができません。 + +もっとうまくやれるはずです...。 + +## 依存関係を作るもの + +これまでは、依存関係が関数として宣言されているのを見てきました。 + +しかし、依存関係を定義する方法はそれだけではありません(その方が一般的かもしれませんが)。 + +重要なのは、依存関係が「呼び出し可能」なものであることです。 + +Pythonにおける「**呼び出し可能**」とは、Pythonが関数のように「呼び出す」ことができるものを指します。 + +そのため、`something`オブジェクト(関数ではないかもしれませんが)を持っていて、それを次のように「呼び出す」(実行する)ことができるとします: + +```Python +something() +``` + +または + +```Python +something(some_argument, some_keyword_argument="foo") +``` + +これを「呼び出し可能」なものと呼びます。 + +## 依存関係としてのクラス + +Pythonのクラスのインスタンスを作成する際に、同じ構文を使用していることに気づくかもしれません。 + +例えば: + +```Python +class Cat: + def __init__(self, name: str): + self.name = name + + +fluffy = Cat(name="Mr Fluffy") +``` + +この場合、`fluffy`は`Cat`クラスのインスタンスです。 + +そして`fluffy`を作成するために、`Cat`を「呼び出している」ことになります。 + +そのため、Pythonのクラスもまた「呼び出し可能」です。 + +そして、**FastAPI** では、Pythonのクラスを依存関係として使用することができます。 + +FastAPIが実際にチェックしているのは、それが「呼び出し可能」(関数、クラス、その他なんでも)であり、パラメータが定義されているかどうかということです。 + +**FastAPI** の依存関係として「呼び出し可能なもの」を渡すと、その「呼び出し可能なもの」のパラメータを解析し、サブ依存関係も含めて、*path operation関数*のパラメータと同じように処理します。 + +それは、パラメータが全くない呼び出し可能なものにも適用されます。パラメータのない*path operation関数*と同じように。 + +そこで、上で紹介した依存関係の`common_parameters`を`CommonQueryParams`クラスに変更します: + +```Python hl_lines="11 12 13 14 15" +{!../../../docs_src/dependencies/tutorial002.py!} +``` + +クラスのインスタンスを作成するために使用される`__init__`メソッドに注目してください: + +```Python hl_lines="12" +{!../../../docs_src/dependencies/tutorial002.py!} +``` + +...以前の`common_parameters`と同じパラメータを持っています: + +```Python hl_lines="8" +{!../../../docs_src/dependencies/tutorial001.py!} +``` + +これらのパラメータは **FastAPI** が依存関係を「解決」するために使用するものです。 + +どちらの場合も以下を持っています: + +* オプショナルの`q`クエリパラメータ。 +* `skip`クエリパラメータ、デフォルトは`0`。 +* `limit`クエリパラメータ、デフォルトは`100`。 + +どちらの場合も、データは変換され、検証され、OpenAPIスキーマなどで文書化されます。 + +## 使用 + +これで、このクラスを使用して依存関係を宣言することができます。 + +```Python hl_lines="19" +{!../../../docs_src/dependencies/tutorial002.py!} +``` + +**FastAPI** は`CommonQueryParams`クラスを呼び出します。これにより、そのクラスの「インスタンス」が作成され、インスタンスはパラメータ`commons`として関数に渡されます。 + +## 型注釈と`Depends` + +上のコードでは`CommonQueryParams`を2回書いていることに注目してください: + +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` + +以下にある最後の`CommonQueryParams`: + +```Python +... = Depends(CommonQueryParams) +``` + +...は、**FastAPI** が依存関係を知るために実際に使用するものです。 + +そこからFastAPIが宣言されたパラメータを抽出し、それが実際にFastAPIが呼び出すものです。 + +--- + +この場合、以下にある最初の`CommonQueryParams`: + +```Python +commons: CommonQueryParams ... +``` + +...は **FastAPI** に対して特別な意味をもちません。FastAPIはデータ変換や検証などには使用しません(それらのためには`= Depends(CommonQueryParams)`を使用しています)。 + +実際には以下のように書けばいいだけです: + +```Python +commons = Depends(CommonQueryParams) +``` + +以下にあるように: + +```Python hl_lines="19" +{!../../../docs_src/dependencies/tutorial003.py!} +``` + +しかし、型を宣言することは推奨されています。そうすれば、エディタは`commons`のパラメータとして何が渡されるかを知ることができ、コードの補完や型チェックなどを行うのに役立ちます: + + + +## ショートカット + +しかし、ここでは`CommonQueryParams`を2回書くというコードの繰り返しが発生していることがわかります: + +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` + +依存関係が、クラス自体のインスタンスを作成するために**FastAPI**が「呼び出す」*特定の*クラスである場合、**FastAPI** はこれらのケースのショートカットを提供しています。 + +それらの具体的なケースについては以下のようにします: + +以下のように書く代わりに: + +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` + +...以下のように書きます: + +```Python +commons: CommonQueryParams = Depends() +``` + +パラメータの型として依存関係を宣言し、`Depends()`の中でパラメータを指定せず、`Depends()`をその関数のパラメータの「デフォルト」値(`=`のあとの値)として使用することで、`Depends(CommonQueryParams)`の中でクラス全体を*もう一度*書かなくてもよくなります。 + +同じ例では以下のようになります: + +```Python hl_lines="19" +{!../../../docs_src/dependencies/tutorial004.py!} +``` + +...そして **FastAPI** は何をすべきか知っています。 + +!!! tip "豆知識" + 役に立つというよりも、混乱するようであれば無視してください。それをする*必要*はありません。 + + それは単なるショートカットです。なぜなら **FastAPI** はコードの繰り返しを最小限に抑えることに気を使っているからです。 diff --git a/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md new file mode 100644 index 0000000000000..1684d9ca1e5fc --- /dev/null +++ b/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -0,0 +1,62 @@ +# path operationデコレータの依存関係 + +場合によっては*path operation関数*の中で依存関係の戻り値を本当に必要としないこともあります。 + +もしくは、依存関係が値を返さない場合もあります。 + +しかし、それでも実行・解決する必要があります。 + +このような場合、*path operation関数*のパラメータを`Depends`で宣言する代わりに、*path operation decorator*に`dependencies`の`list`を追加することができます。 + +## *path operationデコレータ*への`dependencies`の追加 + +*path operationデコレータ*はオプショナルの引数`dependencies`を受け取ります。 + +それは`Depends()`の`list`であるべきです: + +```Python hl_lines="17" +{!../../../docs_src/dependencies/tutorial006.py!} +``` + +これらの依存関係は、通常の依存関係と同様に実行・解決されます。しかし、それらの値(何かを返す場合)は*path operation関数*には渡されません。 + +!!! tip "豆知識" + エディタによっては、未使用の関数パラメータをチェックしてエラーとして表示するものもあります。 + + `dependencies`を`path operationデコレータ`で使用することで、エディタやツールのエラーを回避しながら確実に実行することができます。 + + また、コードの未使用のパラメータがあるのを見て、それが不要だと思ってしまうような新しい開発者の混乱を避けるのにも役立つかもしれません。 + +## 依存関係のエラーと戻り値 + +通常使用している依存関係の*関数*と同じものを使用することができます。 + +### 依存関係の要件 + +これらはリクエストの要件(ヘッダのようなもの)やその他のサブ依存関係を宣言することができます: + +```Python hl_lines="6 11" +{!../../../docs_src/dependencies/tutorial006.py!} +``` + +### 例外の発生 + +これらの依存関係は通常の依存関係と同じように、例外を`raise`発生させることができます: + +```Python hl_lines="8 13" +{!../../../docs_src/dependencies/tutorial006.py!} +``` + +### 戻り値 + +そして、値を返すことも返さないこともできますが、値は使われません。 + +つまり、すでにどこかで使っている通常の依存関係(値を返すもの)を再利用することができ、値は使われなくても依存関係は実行されます: + +```Python hl_lines="9 14" +{!../../../docs_src/dependencies/tutorial006.py!} +``` + +## *path operations*のグループに対する依存関係 + +後で、より大きなアプリケーションの構造([Bigger Applications - Multiple Files](../../tutorial/bigger-applications.md){.internal-link target=_blank})について読む時に、おそらく複数のファイルを使用して、*path operations*のグループに対して単一の`dependencies`パラメータを宣言する方法を学ぶでしょう。 diff --git a/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md new file mode 100644 index 0000000000000..2a89e51d2b27d --- /dev/null +++ b/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md @@ -0,0 +1,225 @@ +# yieldを持つ依存関係 + +FastAPIは、いくつかの終了後の追加のステップを行う依存関係をサポートしています。 + +これを行うには、`return`の代わりに`yield`を使い、その後に追加のステップを書きます。 + +!!! tip "豆知識" + `yield`は必ず一度だけ使用するようにしてください。 + +!!! info "情報" + これを動作させるには、**Python 3.7** 以上を使用するか、**Python 3.6** では"backports"をインストールする必要があります: + + ``` + pip install async-exit-stack async-generator + ``` + + これによりasync-exit-stackasync-generatorがインストールされます。 + +!!! note "技術詳細" + 以下と一緒に使用できる関数なら何でも有効です: + + * `@contextlib.contextmanager`または + * `@contextlib.asynccontextmanager` + + これらは **FastAPI** の依存関係として使用するのに有効です。 + + 実際、FastAPIは内部的にこれら2つのデコレータを使用しています。 + +## `yield`を持つデータベースの依存関係 + +例えば、これを使ってデータベースセッションを作成し、終了後にそれを閉じることができます。 + +レスポンスを送信する前に`yield`文を含む前のコードのみが実行されます。 + +```Python hl_lines="2 3 4" +{!../../../docs_src/dependencies/tutorial007.py!} +``` + +生成された値は、*path operations*や他の依存関係に注入されるものです: + +```Python hl_lines="4" +{!../../../docs_src/dependencies/tutorial007.py!} +``` + +`yield`文に続くコードは、レスポンスが送信された後に実行されます: + +```Python hl_lines="5 6" +{!../../../docs_src/dependencies/tutorial007.py!} +``` + +!!! tip "豆知識" + `async`や通常の関数を使用することができます。 + + **FastAPI** は、通常の依存関係と同じように、それぞれで正しいことを行います。 + +## `yield`と`try`を持つ依存関係 + +`yield`を持つ依存関係で`try`ブロックを使用した場合、その依存関係を使用した際に発生した例外を受け取ることになります。 + +例えば、途中のどこかの時点で、別の依存関係や*path operation*の中で、データベーストランザクションを「ロールバック」したり、その他のエラーを作成したりするコードがあった場合、依存関係の中で例外を受け取ることになります。 + +そのため、依存関係の中にある特定の例外を`except SomeException`で探すことができます。 + +同様に、`finally`を用いて例外があったかどうかにかかわらず、終了ステップを確実に実行することができます。 + +```Python hl_lines="3 5" +{!../../../docs_src/dependencies/tutorial007.py!} +``` + +## `yield`を持つサブ依存関係 + +任意の大きさや形のサブ依存関係やサブ依存関係の「ツリー」を持つことができ、その中で`yield`を使用することができます。 + +**FastAPI** は、`yield`を持つ各依存関係の「終了コード」が正しい順番で実行されていることを確認します。 + +例えば、`dependency_c`は`dependency_b`と`dependency_b`に依存する`dependency_a`に、依存することができます: + +```Python hl_lines="4 12 20" +{!../../../docs_src/dependencies/tutorial008.py!} +``` + +そして、それらはすべて`yield`を使用することができます。 + +この場合、`dependency_c`は終了コードを実行するために、`dependency_b`(ここでは`dep_b`という名前)の値がまだ利用可能である必要があります。 + +そして、`dependency_b`は`dependency_a`(ここでは`dep_a`という名前)の値を終了コードで利用できるようにする必要があります。 + +```Python hl_lines="16 17 24 25" +{!../../../docs_src/dependencies/tutorial008.py!} +``` + +同様に、`yield`と`return`が混在した依存関係を持つこともできます。 + +また、単一の依存関係を持っていて、`yield`などの他の依存関係をいくつか必要とすることもできます。 + +依存関係の組み合わせは自由です。 + +**FastAPI** は、全てが正しい順序で実行されていることを確認します。 + +!!! note "技術詳細" + これはPythonのContext Managersのおかげで動作します。 + + **FastAPI** はこれを実現するために内部的に使用しています。 + +## `yield`と`HTTPException`を持つ依存関係 + +`yield`と例外をキャッチする`try`ブロックを持つことができる依存関係を使用することができることがわかりました。 + +`yield`の後の終了コードで`HTTPException`などを発生させたくなるかもしれません。しかし**それはうまくいきません** + +`yield`を持つ依存関係の終了コードは[例外ハンドラ](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}の*後に*実行されます。依存関係によって投げられた例外を終了コード(`yield`の後)でキャッチするものはなにもありません。 + +つまり、`yield`の後に`HTTPException`を発生させた場合、`HTTTPException`をキャッチしてHTTP 400のレスポンスを返すデフォルトの(あるいは任意のカスタムの)例外ハンドラは、その例外をキャッチすることができなくなります。 + +これは、依存関係に設定されているもの(例えば、DBセッション)を、例えば、バックグラウンドタスクで使用できるようにするものです。 + +バックグラウンドタスクはレスポンスが送信された*後*に実行されます。そのため、*すでに送信されている*レスポンスを変更する方法すらないので、`HTTPException`を発生させる方法はありません。 + +しかし、バックグラウンドタスクがDBエラーを発生させた場合、少なくとも`yield`で依存関係のセッションをロールバックしたり、きれいに閉じたりすることができ、エラーをログに記録したり、リモートのトラッキングシステムに報告したりすることができます。 + +例外が発生する可能性があるコードがある場合は、最も普通の「Python流」なことをして、コードのその部分に`try`ブロックを追加してください。 + +レスポンスを返したり、レスポンスを変更したり、`HTTPException`を発生させたりする*前に*処理したいカスタム例外がある場合は、[カスタム例外ハンドラ](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}を作成してください。 + +!!! tip "豆知識" + `HTTPException`を含む例外は、`yield`の*前*でも発生させることができます。ただし、後ではできません。 + +実行の順序は多かれ少なかれ以下の図のようになります。時間は上から下へと流れていきます。そして、各列はコードを相互作用させたり、実行したりしている部分の一つです。 + +```mermaid +sequenceDiagram + +participant client as Client +participant handler as Exception handler +participant dep as Dep with yield +participant operation as Path Operation +participant tasks as Background tasks + + Note over client,tasks: Can raise exception for dependency, handled after response is sent + Note over client,operation: Can raise HTTPException and can change the response + client ->> dep: Start request + Note over dep: Run code up to yield + opt raise + dep -->> handler: Raise HTTPException + handler -->> client: HTTP error response + dep -->> dep: Raise other exception + end + dep ->> operation: Run dependency, e.g. DB session + opt raise + operation -->> handler: Raise HTTPException + handler -->> client: HTTP error response + operation -->> dep: Raise other exception + end + operation ->> client: Return response to client + Note over client,operation: Response is already sent, can't change it anymore + opt Tasks + operation -->> tasks: Send background tasks + end + opt Raise other exception + tasks -->> dep: Raise other exception + end + Note over dep: After yield + opt Handle other exception + dep -->> dep: Handle exception, can't change response. E.g. close DB session. + end +``` + +!!! info "情報" + **1つのレスポンス** だけがクライアントに送信されます。それはエラーレスポンスの一つかもしれませんし、*path operation*からのレスポンスかもしれません。 + + いずれかのレスポンスが送信された後、他のレスポンスを送信することはできません。 + +!!! tip "豆知識" + この図は`HTTPException`を示していますが、[カスタム例外ハンドラ](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}を作成することで、他の例外を発生させることもできます。そして、その例外は依存関係の終了コードではなく、そのカスタム例外ハンドラによって処理されます。 + + しかし例外ハンドラで処理されない例外を発生させた場合は、依存関係の終了コードで処理されます。 + +## コンテキストマネージャ + +### 「コンテキストマネージャ」とは + +「コンテキストマネージャ」とは、`with`文の中で使用できるPythonオブジェクトのことです。 + +例えば、ファイルを読み込むには`with`を使用することができます: + +```Python +with open("./somefile.txt") as f: + contents = f.read() + print(contents) +``` + +その後の`open("./somefile.txt")`は「コンテキストマネージャ」と呼ばれるオブジェクトを作成します。 + +`with`ブロックが終了すると、例外があったとしてもファイルを確かに閉じます。 + +`yield`を依存関係を作成すると、**FastAPI** は内部的にそれをコンテキストマネージャに変換し、他の関連ツールと組み合わせます。 + +### `yield`を持つ依存関係でのコンテキストマネージャの使用 + +!!! warning "注意" + これは多かれ少なかれ、「高度な」発想です。 + + **FastAPI** を使い始めたばかりの方は、とりあえずスキップした方がよいかもしれません。 + +Pythonでは、以下の2つのメソッドを持つクラスを作成する: `__enter__()`と`__exit__()`ことでコンテキストマネージャを作成することができます。 + +また、依存関数の中で`with`や`async with`文を使用することによって`yield`を持つ **FastAPI** の依存関係の中でそれらを使用することができます: + +```Python hl_lines="1 2 3 4 5 6 7 8 9 13" +{!../../../docs_src/dependencies/tutorial010.py!} +``` + +!!! tip "豆知識" + コンテキストマネージャを作成するもう一つの方法はwithです: + + * `@contextlib.contextmanager` または + * `@contextlib.asynccontextmanager` + + これらを使って、関数を単一の`yield`でデコレートすることができます。 + + これは **FastAPI** が内部的に`yield`を持つ依存関係のために使用しているものです。 + + しかし、FastAPIの依存関係にデコレータを使う必要はありません(そして使うべきではありません)。 + + FastAPIが内部的にやってくれます。 diff --git a/docs/ja/docs/tutorial/dependencies/index.md b/docs/ja/docs/tutorial/dependencies/index.md new file mode 100644 index 0000000000000..ec563a16d7219 --- /dev/null +++ b/docs/ja/docs/tutorial/dependencies/index.md @@ -0,0 +1,209 @@ +# 依存関係 - 最初のステップ + +** FastAPI** は非常に強力でありながら直感的な **依存性注入** システムを持っています。 + +それは非常にシンプルに使用できるように設計されており、開発者が他のコンポーネント **FastAPI** と統合するのが非常に簡単になるように設計されています。 + +## 「依存性注入」とは + +**「依存性注入」** とは、プログラミングにおいて、コード(この場合は、*path operation関数*)が動作したり使用したりするために必要なもの(「依存関係」)を宣言する方法があることを意味します: + +そして、そのシステム(この場合は、**FastAPI**)は、必要な依存関係をコードに提供するために必要なことは何でも行います(依存関係を「注入」します)。 + +これは以下のようなことが必要な時にとても便利です: + +* ロジックを共有している。(同じコードロジックを何度も繰り返している)。 +* データベース接続を共有する。 +* セキュリティ、認証、ロール要件などを強制する。 +* そのほかにも多くのこと... + +これらすべてを、コードの繰り返しを最小限に抑えながら行います。 + +## 最初のステップ + +非常にシンプルな例を見てみましょう。あまりにもシンプルなので、今のところはあまり参考にならないでしょう。 + +しかし、この方法では **依存性注入** システムがどのように機能するかに焦点を当てることができます。 + +### 依存関係の作成 + +まずは依存関係に注目してみましょう。 + +以下のように、*path operation関数*と同じパラメータを全て取ることができる関数にすぎません: + +```Python hl_lines="8 9" +{!../../../docs_src/dependencies/tutorial001.py!} +``` + +これだけです。 + +**2行**。 + +そして、それはすべての*path operation関数*が持っているのと同じ形と構造を持っています。 + +「デコレータ」を含まない(`@app.get("/some-path")`を含まない)*path operation関数*と考えることもできます。 + +そして何でも返すことができます。 + +この場合、この依存関係は以下を期待しています: + +* オプショナルのクエリパラメータ`q`は`str`です。 +* オプショナルのクエリパラメータ`skip`は`int`で、デフォルトは`0`です。 +* オプショナルのクエリパラメータ`limit`は`int`で、デフォルトは`100`です。 + +そして、これらの値を含む`dict`を返します。 + +### `Depends`のインポート + +```Python hl_lines="3" +{!../../../docs_src/dependencies/tutorial001.py!} +``` + +### "dependant"での依存関係の宣言 + +*path operation関数*のパラメータに`Body`や`Query`などを使用するのと同じように、新しいパラメータに`Depends`を使用することができます: + +```Python hl_lines="13 18" +{!../../../docs_src/dependencies/tutorial001.py!} +``` + +関数のパラメータに`Depends`を使用するのは`Body`や`Query`などと同じですが、`Depends`の動作は少し異なります。 + +`Depends`は1つのパラメータしか与えられません。 + +このパラメータは関数のようなものである必要があります。 + +そして、その関数は、*path operation関数*が行うのと同じ方法でパラメータを取ります。 + +!!! tip "豆知識" + 次の章では、関数以外の「もの」が依存関係として使用できるものを見ていきます。 + +新しいリクエストが到着するたびに、**FastAPI** が以下のような処理を行います: + +* 依存関係("dependable")関数を正しいパラメータで呼び出します。 +* 関数の結果を取得します。 +* *path operation関数*のパラメータにその結果を代入してください。 + +```mermaid +graph TB + +common_parameters(["common_parameters"]) +read_items["/items/"] +read_users["/users/"] + +common_parameters --> read_items +common_parameters --> read_users +``` + +この方法では、共有されるコードを一度書き、**FastAPI** が*path operations*のための呼び出しを行います。 + +!!! check "確認" + 特別なクラスを作成してどこかで **FastAPI** に渡して「登録」する必要はないことに注意してください。 + + `Depends`を渡すだけで、**FastAPI** が残りの処理をしてくれます。 + +## `async`にするかどうか + +依存関係は **FastAPI**(*path operation関数*と同じ)からも呼び出されるため、関数を定義する際にも同じルールが適用されます。 + +`async def`や通常の`def`を使用することができます。 + +また、通常の`def`*path operation関数*の中に`async def`を入れて依存関係を宣言したり、`async def`*path operation関数*の中に`def`を入れて依存関係を宣言したりすることなどができます。 + +それは重要ではありません。**FastAPI** は何をすべきかを知っています。 + +!!! note "備考" + わからない場合は、ドキュメントの[Async: *"In a hurry?"*](../../async.md){.internal-link target=_blank}の中の`async`と`await`についてのセクションを確認してください。 + +## OpenAPIとの統合 + +依存関係(およびサブ依存関係)のすべてのリクエスト宣言、検証、および要件は、同じOpenAPIスキーマに統合されます。 + +つまり、対話型ドキュメントにはこれらの依存関係から得られる全ての情報も含まれているということです: + + + +## 簡単な使い方 + +見てみると、*path*と*operation*が一致した時に*path operation関数*が宣言されていて、**FastAPI** が正しいパラメータで関数を呼び出してリクエストからデータを抽出する処理をしています。 + +実は、すべての(あるいはほとんどの)Webフレームワークは、このように動作します。 + +これらの関数を直接呼び出すことはありません。これらの関数はフレームワーク(この場合は、**FastAPI**)によって呼び出されます。 + +依存性注入システムでは、**FastAPI** に*path operation*もまた、*path operation関数*の前に実行されるべき他の何かに「依存」していることを伝えることができ、**FastAPI** がそれを実行し、結果を「注入」することを引き受けます。 + +他にも、「依存性注入」と同じような考えの一般的な用語があります: + +* リソース +* プロバイダ +* サービス +* インジェクタブル +* コンポーネント + +## **FastAPI** プラグイン + +統合や「プラグイン」は **依存性注入** システムを使って構築することができます。しかし、実際には、**「プラグイン」を作成する必要はありません**。依存関係を使用することで、無限の数の統合やインタラクションを宣言することができ、それが**path operation関数*で利用可能になるからです。 + +依存関係は非常にシンプルで直感的な方法で作成することができ、必要なPythonパッケージをインポートするだけで、*文字通り*数行のコードでAPI関数と統合することができます。 + +次の章では、リレーショナルデータベースやNoSQLデータベース、セキュリティなどについて、その例を見ていきます。 + +## **FastAPI** 互換性 + +依存性注入システムがシンプルなので、**FastAPI** は以下のようなものと互換性があります: + +* すべてのリレーショナルデータベース +* NoSQLデータベース +* 外部パッケージ +* 外部API +* 認証・認可システム +* API利用状況監視システム +* レスポンスデータ注入システム +* など。 + +## シンプルでパワフル + +階層依存性注入システムは、定義や使用方法が非常にシンプルであるにもかかわらず、非常に強力なものとなっています。 + +依存関係事態を定義する依存関係を定義することができます。 + +最終的には、依存関係の階層ツリーが構築され、**依存性注入**システムが、これらの依存関係(およびそのサブ依存関係)をすべて解決し、各ステップで結果を提供(注入)します。 + +例えば、4つのAPIエンドポイント(*path operations*)があるとします: + +* `/items/public/` +* `/items/private/` +* `/users/{user_id}/activate` +* `/items/pro/` + +そして、依存関係とサブ依存関係だけで、それぞれに異なるパーミッション要件を追加することができます: + +```mermaid +graph TB + +current_user(["current_user"]) +active_user(["active_user"]) +admin_user(["admin_user"]) +paying_user(["paying_user"]) + +public["/items/public/"] +private["/items/private/"] +activate_user["/users/{user_id}/activate"] +pro_items["/items/pro/"] + +current_user --> active_user +active_user --> admin_user +active_user --> paying_user + +current_user --> public +active_user --> private +admin_user --> activate_user +paying_user --> pro_items +``` + +## **OpenAPI** との統合 + +これら全ての依存関係は、要件を宣言すると同時に、*path operations*にパラメータやバリデーションを追加します。 + +**FastAPI** はそれをすべてOpenAPIスキーマに追加して、対話型のドキュメントシステムに表示されるようにします。 diff --git a/docs/ja/docs/tutorial/dependencies/sub-dependencies.md b/docs/ja/docs/tutorial/dependencies/sub-dependencies.md new file mode 100644 index 0000000000000..8848ac79ea2b1 --- /dev/null +++ b/docs/ja/docs/tutorial/dependencies/sub-dependencies.md @@ -0,0 +1,86 @@ +# サブ依存関係 + +**サブ依存関係** を持つ依存関係を作成することができます。 + +それらは必要なだけ **深く** することができます。 + +**FastAPI** はそれらを解決してくれます。 + +### 最初の依存関係「依存可能なもの」 + +以下のような最初の依存関係(「依存可能なもの」)を作成することができます: + +```Python hl_lines="8 9" +{!../../../docs_src/dependencies/tutorial005.py!} +``` + +これはオプショナルのクエリパラメータ`q`を`str`として宣言し、それを返すだけです。 + +これは非常にシンプルです(あまり便利ではありません)が、サブ依存関係がどのように機能するかに焦点を当てるのに役立ちます。 + +### 第二の依存関係 「依存可能なもの」と「依存」 + +そして、別の依存関数(「依存可能なもの」)を作成して、同時にそれ自身の依存関係を宣言することができます(つまりそれ自身も「依存」です): + +```Python hl_lines="13" +{!../../../docs_src/dependencies/tutorial005.py!} +``` + +宣言されたパラメータに注目してみましょう: + +* この関数は依存関係(「依存可能なもの」)そのものであるにもかかわらず、別の依存関係を宣言しています(何か他のものに「依存」しています)。 + * これは`query_extractor`に依存しており、それが返す値をパラメータ`q`に代入します。 +* また、オプショナルの`last_query`クッキーを`str`として宣言します。 + * ユーザーがクエリ`q`を提供しなかった場合、クッキーに保存していた最後に使用したクエリを使用します。 + +### 依存関係の使用 + +以下のように依存関係を使用することができます: + +```Python hl_lines="21" +{!../../../docs_src/dependencies/tutorial005.py!} +``` + +!!! info "情報" + *path operation関数*の中で宣言している依存関係は`query_or_cookie_extractor`の1つだけであることに注意してください。 + + しかし、**FastAPI** は`query_extractor`を最初に解決し、その結果を`query_or_cookie_extractor`を呼び出す時に渡す必要があることを知っています。 + +```mermaid +graph TB + +query_extractor(["query_extractor"]) +query_or_cookie_extractor(["query_or_cookie_extractor"]) + +read_query["/items/"] + +query_extractor --> query_or_cookie_extractor --> read_query +``` + +## 同じ依存関係の複数回の使用 + +依存関係の1つが同じ*path operation*に対して複数回宣言されている場合、例えば、複数の依存関係が共通のサブ依存関係を持っている場合、**FastAPI** はリクエストごとに1回だけそのサブ依存関係を呼び出します。 + +そして、返された値を「キャッシュ」に保存し、同じリクエストに対して依存関係を何度も呼び出す代わりに、特定のリクエストでそれを必要とする全ての「依存関係」に渡すことになります。 + +高度なシナリオでは、「キャッシュされた」値を使うのではなく、同じリクエストの各ステップ(おそらく複数回)で依存関係を呼び出す必要があることがわかっている場合、`Depens`を使用する際に、`use_cache=False`というパラメータを設定することができます。 + +```Python hl_lines="1" +async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)): + return {"fresh_value": fresh_value} +``` + +## まとめ + +ここで使われている派手な言葉は別にして、**依存性注入** システムは非常にシンプルです。 + +*path operation関数*と同じように見えるただの関数です。 + +しかし、それでも非常に強力で、任意の深くネストされた依存関係「グラフ」(ツリー)を宣言することができます。 + +!!! tip "豆知識" + これらの単純な例では、全てが役に立つとは言えないかもしれません。 + + しかし、**security** についての章で、それがどれほど有用であるかがわかるでしょう。 + + そして、あなたを救うコードの量もみることになるでしょう。 diff --git a/docs/ja/docs/tutorial/encoder.md b/docs/ja/docs/tutorial/encoder.md new file mode 100644 index 0000000000000..305867ab7b4ba --- /dev/null +++ b/docs/ja/docs/tutorial/encoder.md @@ -0,0 +1,34 @@ +# JSON互換エンコーダ + +データ型(Pydanticモデルのような)をJSONと互換性のあるもの(`dict`や`list`など)に変更する必要がある場合があります。 + +例えば、データベースに保存する必要がある場合です。 + +そのために、**FastAPI** は`jsonable_encoder()`関数を提供しています。 + +## `jsonable_encoder`の使用 + +JSON互換のデータのみを受信するデータベース`fase_db`があるとしましょう。 + +例えば、`datetime`オブジェクトはJSONと互換性がないので、このデーターベースには受け取られません。 + +そのため、`datetime`オブジェクトはISO形式のデータを含む`str`に変換されなければなりません。 + +同様に、このデータベースはPydanticモデル(属性を持つオブジェクト)を受け取らず、`dict`だけを受け取ります。 + +そのために`jsonable_encoder`を使用することができます。 + +Pydanticモデルのようなオブジェクトを受け取り、JSON互換版を返します: + +```Python hl_lines="5 22" +{!../../../docs_src/encoder/tutorial001.py!} +``` + +この例では、Pydanticモデルを`dict`に、`datetime`を`str`に変換します。 + +呼び出した結果は、Pythonの標準の`json.dumps()`でエンコードできるものです。 + +これはJSON形式のデータを含む大きな`str`を(文字列として)返しません。JSONと互換性のある値とサブの値を持つPython標準のデータ構造(例:`dict`)を返します。 + +!!! note "備考" + `jsonable_encoder`は実際には **FastAPI** が内部的にデータを変換するために使用します。しかしこれは他の多くのシナリオで有用です。 diff --git a/docs/ja/docs/tutorial/extra-data-types.md b/docs/ja/docs/tutorial/extra-data-types.md new file mode 100644 index 0000000000000..c0fdbd58c9638 --- /dev/null +++ b/docs/ja/docs/tutorial/extra-data-types.md @@ -0,0 +1,66 @@ +# 追加データ型 + +今までは、以下のような一般的なデータ型を使用してきました: + +* `int` +* `float` +* `str` +* `bool` + +しかし、より複雑なデータ型を使用することもできます。 + +そして、今まで見てきたのと同じ機能を持つことになります: + +* 素晴らしいエディタのサポート +* 受信したリクエストからのデータ変換 +* レスポンスデータのデータ変換 +* データの検証 +* 自動注釈と文書化 + +## 他のデータ型 + +ここでは、使用できる追加のデータ型のいくつかを紹介します: + +* `UUID`: + * 多くのデータベースやシステムで共通のIDとして使用される、標準的な「ユニバーサルにユニークな識別子」です。 + * リクエストとレスポンスでは`str`として表現されます。 +* `datetime.datetime`: + * Pythonの`datetime.datetime`です。 + * リクエストとレスポンスはISO 8601形式の`str`で表現されます: `2008-09-15T15:53:00+05:00` +* `datetime.date`: + * Pythonの`datetime.date`です。 + * リクエストとレスポンスはISO 8601形式の`str`で表現されます: `2008-09-15` +* `datetime.time`: + * Pythonの`datetime.time`. + * リクエストとレスポンスはISO 8601形式の`str`で表現されます: `14:23:55.003` +* `datetime.timedelta`: + * Pythonの`datetime.timedelta`です。 + * リクエストとレスポンスでは合計秒数の`float`で表現されます。 + * Pydanticでは「ISO 8601 time diff encoding」として表現することも可能です。詳細はドキュメントを参照してください。 +* `frozenset`: + * リクエストとレスポンスでは`set`と同じように扱われます: + * リクエストでは、リストが読み込まれ、重複を排除して`set`に変換されます。 + * レスポンスでは`set`が`list`に変換されます。 + * 生成されたスキーマは`set`の値が一意であることを指定します(JSON Schemaの`uniqueItems`を使用します)。 +* `bytes`: + * Pythonの標準的な`bytes`です。 + * リクエストとレスポンスでは`str`として扱われます。 + * 生成されたスキーマは`str`で`binary`の「フォーマット」持つことを指定します。 +* `Decimal`: + * Pythonの標準的な`Decimal`です。 + * リクエストやレスポンスでは`float`と同じように扱います。 + +* Pydanticの全ての有効な型はこちらで確認できます: Pydantic data types。 +## 例 + +ここでは、上記の型のいくつかを使用したパラメータを持つ*path operation*の例を示します。 + +```Python hl_lines="1 2 12-16" +{!../../../docs_src/extra_data_types/tutorial001.py!} +``` + +関数内のパラメータは自然なデータ型を持っていることに注意してください。そして、以下のように通常の日付操作を行うことができます: + +```Python hl_lines="18 19" +{!../../../docs_src/extra_data_types/tutorial001.py!} +``` diff --git a/docs/ja/docs/tutorial/extra-models.md b/docs/ja/docs/tutorial/extra-models.md new file mode 100644 index 0000000000000..aa2e5ffdcbe61 --- /dev/null +++ b/docs/ja/docs/tutorial/extra-models.md @@ -0,0 +1,195 @@ +# モデル - より詳しく + +先ほどの例に続き、複数の関連モデルを持つことが一般的です。 + +これはユーザーモデルの場合は特にそうです。なぜなら: + +* **入力モデル** にはパスワードが必要です。 +* **出力モデル**はパスワードをもつべきではありません。 +* **データベースモデル**はおそらくハッシュ化されたパスワードが必要になるでしょう。 + +!!! danger "危険" + ユーザーの平文のパスワードは絶対に保存しないでください。常に認証に利用可能な「安全なハッシュ」を保存してください。 + + 知らない方は、[セキュリティの章](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}で「パスワードハッシュ」とは何かを学ぶことができます。 + +## 複数のモデル + +ここでは、パスワードフィールドをもつモデルがどのように見えるのか、また、どこで使われるのか、大まかなイメージを紹介します: + +```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" +{!../../../docs_src/extra_models/tutorial001.py!} +``` + +### `**user_in.dict()`について + +#### Pydanticの`.dict()` + +`user_in`は`UserIn`クラスのPydanticモデルです。 + +Pydanticモデルには、モデルのデータを含む`dict`を返す`.dict()`メソッドがあります。 + +そこで、以下のようなPydanticオブジェクト`user_in`を作成すると: + +```Python +user_in = UserIn(username="john", password="secret", email="john.doe@example.com") +``` + +そして呼び出すと: + +```Python +user_dict = user_in.dict() +``` + +これで変数`user_dict`のデータを持つ`dict`ができました。(これはPydanticモデルのオブジェクトの代わりに`dict`です)。 + +そして呼び出すと: + +```Python +print(user_dict) +``` + +以下のようなPythonの`dict`を得ることができます: + +```Python +{ + 'username': 'john', + 'password': 'secret', + 'email': 'john.doe@example.com', + 'full_name': None, +} +``` + +#### `dict`の展開 + +`user_dict`のような`dict`を受け取り、それを`**user_dict`を持つ関数(またはクラス)に渡すと、Pythonはそれを「展開」します。これは`user_dict`のキーと値を直接キー・バリューの引数として渡します。 + +そこで上述の`user_dict`の続きを以下のように書くと: + +```Python +UserInDB(**user_dict) +``` + +以下と同等の結果になります: + +```Python +UserInDB( + username="john", + password="secret", + email="john.doe@example.com", + full_name=None, +) +``` + +もっと正確に言えば、`user_dict`を将来的にどんな内容であっても直接使用することになります: + +```Python +UserInDB( + username = user_dict["username"], + password = user_dict["password"], + email = user_dict["email"], + full_name = user_dict["full_name"], +) +``` + +#### 別のモデルからつくるPydanticモデル + +上述の例では`user_in.dict()`から`user_dict`をこのコードのように取得していますが: + +```Python +user_dict = user_in.dict() +UserInDB(**user_dict) +``` + +これは以下と同等です: + +```Python +UserInDB(**user_in.dict()) +``` + +...なぜなら`user_in.dict()`は`dict`であり、`**`を付与して`UserInDB`を渡してPythonに「展開」させているからです。 + +そこで、別のPydanticモデルのデータからPydanticモデルを取得します。 + +#### `dict`の展開と追加引数 + +そして、追加のキーワード引数`hashed_password=hashed_password`を以下のように追加すると: + +```Python +UserInDB(**user_in.dict(), hashed_password=hashed_password) +``` + +...以下のようになります: + +```Python +UserInDB( + username = user_dict["username"], + password = user_dict["password"], + email = user_dict["email"], + full_name = user_dict["full_name"], + hashed_password = hashed_password, +) +``` + +!!! warning "注意" + サポートしている追加機能は、データの可能な流れをデモするだけであり、もちろん本当のセキュリティを提供しているわけではありません。 + +## 重複の削減 + +コードの重複を減らすことは、**FastAPI**の中核的なアイデアの1つです。 + +コードの重複が増えると、バグやセキュリティの問題、コードの非同期化問題(ある場所では更新しても他の場所では更新されない場合)などが発生する可能性が高くなります。 + +そして、これらのモデルは全てのデータを共有し、属性名や型を重複させています。 + +もっと良い方法があります。 + +他のモデルのベースとなる`UserBase`モデルを宣言することができます。そして、そのモデルの属性(型宣言、検証など)を継承するサブクラスを作ることができます。 + +データの変換、検証、文書化などはすべて通常通りに動作します。 + +このようにして、モデル間の違いだけを宣言することができます: + +```Python hl_lines="9 15 16 19 20 23 24" +{!../../../docs_src/extra_models/tutorial002.py!} +``` + +## `Union`または`anyOf` + +レスポンスを2つの型の`Union`として宣言することができます。 + +OpenAPIでは`anyOf`で定義されます。 + +そのためには、標準的なPythonの型ヒント`typing.Union`を使用します: + +```Python hl_lines="1 14 15 18 19 20 33" +{!../../../docs_src/extra_models/tutorial003.py!} +``` + +## モデルのリスト + +同じように、オブジェクトのリストのレスポンスを宣言することができます。 + +そのためには、標準のPythonの`typing.List`を使用する: + +```Python hl_lines="1 20" +{!../../../docs_src/extra_models/tutorial004.py!} +``` + +## 任意の`dict`を持つレスポンス + +また、Pydanticモデルを使用せずに、キーと値の型だけを定義した任意の`dict`を使ってレスポンスを宣言することもできます。 + +これは、有効なフィールド・属性名(Pydanticモデルに必要なもの)を事前に知らない場合に便利です。 + +この場合、`typing.Dict`を使用することができます: + +```Python hl_lines="1 8" +{!../../../docs_src/extra_models/tutorial005.py!} +``` + +## まとめ + +複数のPydanticモデルを使用し、ケースごとに自由に継承します。 + +エンティティが異なる「状態」を持たなければならない場合は、エンティティごとに単一のデータモデルを持つ必要はありません。`password` や `password_hash` やパスワードなしなどのいくつかの「状態」をもつユーザー「エンティティ」の場合の様にすれば良いです。 diff --git a/docs/ja/docs/tutorial/handling-errors.md b/docs/ja/docs/tutorial/handling-errors.md new file mode 100644 index 0000000000000..0b95cae0f1278 --- /dev/null +++ b/docs/ja/docs/tutorial/handling-errors.md @@ -0,0 +1,265 @@ +# エラーハンドリング + +APIを使用しているクライアントにエラーを通知する必要がある状況はたくさんあります。 + +このクライアントは、フロントエンドを持つブラウザ、誰かのコード、IoTデバイスなどが考えられます。 + +クライアントに以下のようなことを伝える必要があるかもしれません: + +* クライアントにはその操作のための十分な権限がありません。 +* クライアントはそのリソースにアクセスできません。 +* クライアントがアクセスしようとしていた項目が存在しません。 +* など + +これらの場合、通常は **400**(400から499)の範囲内の **HTTPステータスコード** を返すことになります。 + +これは200のHTTPステータスコード(200から299)に似ています。これらの「200」ステータスコードは、何らかの形でリクエスト「成功」であったことを意味します。 + +400の範囲にあるステータスコードは、クライアントからのエラーがあったことを意味します。 + +**"404 Not Found"** のエラー(およびジョーク)を覚えていますか? + +## `HTTPException`の使用 + +HTTPレスポンスをエラーでクライアントに返すには、`HTTPException`を使用します。 + +### `HTTPException`のインポート + +```Python hl_lines="1" +{!../../../docs_src/handling_errors/tutorial001.py!} +``` + +### コード内での`HTTPException`の発生 + +`HTTPException`は通常のPythonの例外であり、APIに関連するデータを追加したものです。 + +Pythonの例外なので、`return`ではなく、`raise`です。 + +これはまた、*path operation関数*の内部で呼び出しているユーティリティ関数の内部から`HTTPException`を発生させた場合、*path operation関数*の残りのコードは実行されず、そのリクエストを直ちに終了させ、`HTTPException`からのHTTPエラーをクライアントに送信することを意味します。 + +値を返す`return`よりも例外を発生させることの利点は、「依存関係とセキュリティ」のセクションでより明確になります。 + +この例では、クライアントが存在しないIDでアイテムを要求した場合、`404`のステータスコードを持つ例外を発生させます: + +```Python hl_lines="11" +{!../../../docs_src/handling_errors/tutorial001.py!} +``` + +### レスポンス結果 + +クライアントが`http://example.com/items/foo`(`item_id` `"foo"`)をリクエストすると、HTTPステータスコードが200で、以下のJSONレスポンスが返されます: + +```JSON +{ + "item": "The Foo Wrestlers" +} +``` + +しかし、クライアントが`http://example.com/items/bar`(存在しない`item_id` `"bar"`)をリクエストした場合、HTTPステータスコード404("not found"エラー)と以下のJSONレスポンスが返されます: + +```JSON +{ + "detail": "Item not found" +} +``` + +!!! tip "豆知識" + `HTTPException`を発生させる際には、`str`だけでなく、JSONに変換できる任意の値を`detail`パラメータとして渡すことができます。 + + `dist`や`list`などを渡すことができます。 + + これらは **FastAPI** によって自動的に処理され、JSONに変換されます。 + +## カスタムヘッダーの追加 + +例えば、いくつかのタイプのセキュリティのために、HTTPエラーにカスタムヘッダを追加できると便利な状況がいくつかあります。 + +おそらくコードの中で直接使用する必要はないでしょう。 + +しかし、高度なシナリオのために必要な場合には、カスタムヘッダーを追加することができます: + +```Python hl_lines="14" +{!../../../docs_src/handling_errors/tutorial002.py!} +``` + +## カスタム例外ハンドラのインストール + +カスタム例外ハンドラはStarletteと同じ例外ユーティリティを使用して追加することができます。 + +あなた(または使用しているライブラリ)が`raise`するかもしれないカスタム例外`UnicornException`があるとしましょう。 + +そして、この例外をFastAPIでグローバルに処理したいと思います。 + +カスタム例外ハンドラを`@app.exception_handler()`で追加することができます: + +```Python hl_lines="5 6 7 13 14 15 16 17 18 24" +{!../../../docs_src/handling_errors/tutorial003.py!} +``` + +ここで、`/unicorns/yolo`をリクエストすると、*path operation*は`UnicornException`を`raise`します。 + +しかし、これは`unicorn_exception_handler`で処理されます。 + +そのため、HTTPステータスコードが`418`で、JSONの内容が以下のような明確なエラーを受け取ることになります: + +```JSON +{"message": "Oops! yolo did something. There goes a rainbow..."} +``` + +!!! note "技術詳細" + また、`from starlette.requests import Request`と`from starlette.responses import JSONResponse`を使用することもできます。 + + **FastAPI** は開発者の利便性を考慮して、`fastapi.responses`と同じ`starlette.responses`を提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。これは`Request`と同じです。 + +## デフォルトの例外ハンドラのオーバーライド + +**FastAPI** にはいくつかのデフォルトの例外ハンドラがあります。 + +これらのハンドラは、`HTTPException`を`raise`させた場合や、リクエストに無効なデータが含まれている場合にデフォルトのJSONレスポンスを返す役割を担っています。 + +これらの例外ハンドラを独自のものでオーバーライドすることができます。 + +### リクエスト検証の例外のオーバーライド + +リクエストに無効なデータが含まれている場合、**FastAPI** は内部的に`RequestValidationError`を発生させます。 + +また、そのためのデフォルトの例外ハンドラも含まれています。 + +これをオーバーライドするには`RequestValidationError`をインポートして`@app.exception_handler(RequestValidationError)`と一緒に使用して例外ハンドラをデコレートします。 + +この例外ハンドラは`Requset`と例外を受け取ります。 + +```Python hl_lines="2 14 15 16" +{!../../../docs_src/handling_errors/tutorial004.py!} +``` + +これで、`/items/foo`にアクセスすると、デフォルトのJSONエラーの代わりに以下が返されます: + +```JSON +{ + "detail": [ + { + "loc": [ + "path", + "item_id" + ], + "msg": "value is not a valid integer", + "type": "type_error.integer" + } + ] +} +``` + +以下のようなテキスト版を取得します: + +``` +1 validation error +path -> item_id + value is not a valid integer (type=type_error.integer) +``` + +#### `RequestValidationError`と`ValidationError` + +!!! warning "注意" + これらは今のあなたにとって重要でない場合は省略しても良い技術的な詳細です。 + +`RequestValidationError`はPydanticの`ValidationError`のサブクラスです。 + +**FastAPI** は`response_model`でPydanticモデルを使用していて、データにエラーがあった場合、ログにエラーが表示されるようにこれを使用しています。 + +しかし、クライアントやユーザーはそれを見ることはありません。その代わりに、クライアントはHTTPステータスコード`500`の「Internal Server Error」を受け取ります。 + +*レスポンス*やコードのどこか(クライアントの*リクエスト*ではなく)にPydanticの`ValidationError`がある場合、それは実際にはコードのバグなのでこのようにすべきです。 + +また、あなたがそれを修正している間は、セキュリティの脆弱性が露呈する場合があるため、クライアントやユーザーがエラーに関する内部情報にアクセスできないようにしてください。 + +### エラーハンドラ`HTTPException`のオーバーライド + +同様に、`HTTPException`ハンドラをオーバーライドすることもできます。 + +例えば、これらのエラーに対しては、JSONではなくプレーンテキストを返すようにすることができます: + +```Python hl_lines="3 4 9 10 11 22" +{!../../../docs_src/handling_errors/tutorial004.py!} +``` + +!!! note "技術詳細" + また、`from starlette.responses import PlainTextResponse`を使用することもできます。 + + **FastAPI** は開発者の利便性を考慮して、`fastapi.responses`と同じ`starlette.responses`を提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。 + +### `RequestValidationError`のボディの使用 + +`RequestValidationError`には無効なデータを含む`body`が含まれています。 + +アプリ開発中に本体のログを取ってデバッグしたり、ユーザーに返したりなどに使用することができます。 + +```Python hl_lines="14" +{!../../../docs_src/handling_errors/tutorial005.py!} +``` + +ここで、以下のような無効な項目を送信してみてください: + +```JSON +{ + "title": "towel", + "size": "XL" +} +``` + +受信したボディを含むデータが無効であることを示すレスポンスが表示されます: + +```JSON hl_lines="12 13 14 15" +{ + "detail": [ + { + "loc": [ + "body", + "size" + ], + "msg": "value is not a valid integer", + "type": "type_error.integer" + } + ], + "body": { + "title": "towel", + "size": "XL" + } +} +``` + +#### FastAPIの`HTTPException`とStarletteの`HTTPException` + +**FastAPI**は独自の`HTTPException`を持っています。 + +また、 **FastAPI**のエラークラス`HTTPException`はStarletteのエラークラス`HTTPException`を継承しています。 + +唯一の違いは、**FastAPI** の`HTTPException`はレスポンスに含まれるヘッダを追加できることです。 + +これはOAuth 2.0といくつかのセキュリティユーティリティのために内部的に必要とされ、使用されています。 + +そのため、コード内では通常通り **FastAPI** の`HTTPException`を発生させ続けることができます。 + +しかし、例外ハンドラを登録する際には、Starletteの`HTTPException`を登録しておく必要があります。 + +これにより、Starletteの内部コードやStarletteの拡張機能やプラグインの一部が`HTTPException`を発生させた場合、ハンドラがそれをキャッチして処理することができるようになります。 + +以下の例では、同じコード内で両方の`HTTPException`を使用できるようにするために、Starletteの例外の名前を`StarletteHTTPException`に変更しています: + +```Python +from starlette.exceptions import HTTPException as StarletteHTTPException +``` + +### **FastAPI** の例外ハンドラの再利用 + +また、何らかの方法で例外を使用することもできますが、**FastAPI** から同じデフォルトの例外ハンドラを使用することもできます。 + +デフォルトの例外ハンドラを`fastapi.exception_handlers`からインポートして再利用することができます: + +```Python hl_lines="2 3 4 5 15 21" +{!../../../docs_src/handling_errors/tutorial006.py!} +``` + +この例では、非常に表現力のあるメッセージでエラーを`print`しています。 + +しかし、例外を使用して、デフォルトの例外ハンドラを再利用することができるということが理解できます。 diff --git a/docs/ja/docs/tutorial/path-params-numeric-validations.md b/docs/ja/docs/tutorial/path-params-numeric-validations.md new file mode 100644 index 0000000000000..551aeabb3afa9 --- /dev/null +++ b/docs/ja/docs/tutorial/path-params-numeric-validations.md @@ -0,0 +1,122 @@ +# パスパラメータと数値の検証 + +クエリパラメータに対して`Query`でより多くのバリデーションとメタデータを宣言できるのと同じように、パスパラメータに対しても`Path`で同じ種類のバリデーションとメタデータを宣言することができます。 + +## Pathのインポート + +まず初めに、`fastapi`から`Path`をインポートします: + +```Python hl_lines="1" +{!../../../docs_src/path_params_numeric_validations/tutorial001.py!} +``` + +## メタデータの宣言 + +パラメータは`Query`と同じものを宣言することができます。 + +例えば、パスパラメータ`item_id`に対して`title`のメタデータを宣言するには以下のようにします: + +```Python hl_lines="8" +{!../../../docs_src/path_params_numeric_validations/tutorial001.py!} +``` + +!!! note "備考" + パスの一部でなければならないので、パスパラメータは常に必須です。 + + そのため、`...`を使用して必須と示す必要があります。 + + それでも、`None`で宣言しても、デフォルト値を設定しても、何の影響もなく、常に必要とされていることに変わりはありません。 + +## 必要に応じてパラメータを並び替える + +クエリパラメータ`q`を必須の`str`として宣言したいとしましょう。 + +また、このパラメータには何も宣言する必要がないので、`Query`を使う必要はありません。 + +しかし、パスパラメータ`item_id`のために`Path`を使用する必要があります。 + +Pythonは「デフォルト」を持たない値の前に「デフォルト」を持つ値を置くことができません。 + +しかし、それらを並び替えることができ、デフォルト値を持たない値(クエリパラメータ`q`)を最初に持つことができます。 + +**FastAPI**では関係ありません。パラメータは名前、型、デフォルトの宣言(`Query`、`Path`など)で検出され、順番は気にしません。 + +そのため、以下のように関数を宣言することができます: + +```Python hl_lines="8" +{!../../../docs_src/path_params_numeric_validations/tutorial002.py!} +``` + +## 必要に応じてパラメータを並び替えるトリック + +クエリパラメータ`q`を`Query`やデフォルト値なしで宣言し、パスパラメータ`item_id`を`Path`を用いて宣言し、それらを別の順番に並びたい場合、Pythonには少し特殊な構文が用意されています。 + +関数の最初のパラメータとして`*`を渡します。 + +Pythonはその`*`で何かをすることはありませんが、それ以降のすべてのパラメータがキーワード引数(キーと値のペア)として呼ばれるべきものであると知っているでしょう。それはkwargsとしても知られています。たとえデフォルト値がなくても。 + +```Python hl_lines="8" +{!../../../docs_src/path_params_numeric_validations/tutorial003.py!} +``` + +## 数値の検証: 以上 + +`Query`と`Path`(、そして後述する他のもの)を用いて、文字列の制約を宣言することができますが、数値の制約も同様に宣言できます。 + +ここで、`ge=1`の場合、`item_id`は`1`「より大きい`g`か、同じ`e`」整数でなれけばなりません。 + +```Python hl_lines="8" +{!../../../docs_src/path_params_numeric_validations/tutorial004.py!} +``` + +## 数値の検証: より大きいと小なりイコール + +以下も同様です: + +* `gt`: より大きい(`g`reater `t`han) +* `le`: 小なりイコール(`l`ess than or `e`qual) + +```Python hl_lines="9" +{!../../../docs_src/path_params_numeric_validations/tutorial005.py!} +``` + +## 数値の検証: 浮動小数点、 大なり小なり + +数値のバリデーションは`float`の値に対しても有効です。 + +ここで重要になってくるのはgtだけでなくgeも宣言できることです。これと同様に、例えば、値が`1`より小さくても`0`より大きくなければならないことを要求することができます。 + +したがって、`0.5`は有効な値ですが、`0.0`や`0`はそうではありません。 + +これはltも同じです。 + +```Python hl_lines="11" +{!../../../docs_src/path_params_numeric_validations/tutorial006.py!} +``` + +## まとめ + +`Query`と`Path`(そしてまだ見たことない他のもの)では、[クエリパラメータと文字列の検証](query-params-str-validations.md){.internal-link target=_blank}と同じようにメタデータと文字列の検証を宣言することができます。 + +また、数値のバリデーションを宣言することもできます: + +* `gt`: より大きい(`g`reater `t`han) +* `ge`: 以上(`g`reater than or `e`qual) +* `lt`: より小さい(`l`ess `t`han) +* `le`: 以下(`l`ess than or `e`qual) + +!!! info "情報" + `Query`、`Path`などは後に共通の`Param`クラスのサブクラスを見ることになります。(使う必要はありません) + + そして、それらすべては、これまで見てきた追加のバリデーションとメタデータと同じパラメータを共有しています。 + +!!! note "技術詳細" + `fastapi`から`Query`、`Path`などをインポートすると、これらは実際には関数です。 + + 呼び出されると、同じ名前のクラスのインスタンスを返します。 + + そのため、関数である`Query`をインポートし、それを呼び出すと、`Query`という名前のクラスのインスタンスが返されます。 + + これらの関数は(クラスを直接使うのではなく)エディタが型についてエラーとしないようにするために存在します。 + + この方法によって、これらのエラーを無視するための設定を追加することなく、通常のエディタやコーディングツールを使用することができます。 diff --git a/docs/ja/docs/tutorial/path-params.md b/docs/ja/docs/tutorial/path-params.md index 66de05afb1339..b395dc41d9048 100644 --- a/docs/ja/docs/tutorial/path-params.md +++ b/docs/ja/docs/tutorial/path-params.md @@ -93,7 +93,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー ## Pydantic -すべてのデータバリデーションは Pydantic によって内部で実行されるため、Pydanticの全てのメリットが得られます。そして、安心して利用することができます。 +すべてのデータバリデーションは Pydantic によって内部で実行されるため、Pydanticの全てのメリットが得られます。そして、安心して利用することができます。 `str`、 `float` 、 `bool` および他の多くの複雑なデータ型を型宣言に使用できます。 diff --git a/docs/ja/docs/tutorial/request-forms.md b/docs/ja/docs/tutorial/request-forms.md index bce6e8d9a60f6..f90c4974677dc 100644 --- a/docs/ja/docs/tutorial/request-forms.md +++ b/docs/ja/docs/tutorial/request-forms.md @@ -3,7 +3,7 @@ JSONの代わりにフィールドを受け取る場合は、`Form`を使用します。 !!! info "情報" - フォームを使うためには、まず`python-multipart`をインストールします。 + フォームを使うためには、まず`python-multipart`をインストールします。 たとえば、`pip install python-multipart`のように。 diff --git a/docs/ja/docs/tutorial/response-model.md b/docs/ja/docs/tutorial/response-model.md new file mode 100644 index 0000000000000..b8b6978d45626 --- /dev/null +++ b/docs/ja/docs/tutorial/response-model.md @@ -0,0 +1,208 @@ +# レスポンスモデル + +*path operations* のいずれにおいても、`response_model`パラメータを使用して、レスポンスのモデルを宣言することができます: + +* `@app.get()` +* `@app.post()` +* `@app.put()` +* `@app.delete()` +* など。 + +```Python hl_lines="17" +{!../../../docs_src/response_model/tutorial001.py!} +``` + +!!! note "備考" + `response_model`は「デコレータ」メソッド(`get`、`post`など)のパラメータであることに注意してください。すべてのパラメータやボディのように、*path operation関数* のパラメータではありません。 + +Pydanticモデルの属性に対して宣言するのと同じ型を受け取るので、Pydanticモデルになることもできますが、例えば、`List[Item]`のようなPydanticモデルの`list`になることもできます。 + +FastAPIは`response_model`を使って以下のことをします: + +* 出力データを型宣言に変換します。 +* データを検証します。 +* OpenAPIの *path operation* で、レスポンス用のJSON Schemaを追加します。 +* 自動ドキュメントシステムで使用されます。 + +しかし、最も重要なのは: + +* 出力データをモデルのデータに限定します。これがどのように重要なのか以下で見ていきましょう。 + +!!! note "技術詳細" + レスポンスモデルは、関数の戻り値のアノテーションではなく、このパラメータで宣言されています。なぜなら、パス関数は実際にはそのレスポンスモデルを返すのではなく、`dict`やデータベースオブジェクト、あるいは他のモデルを返し、`response_model`を使用してフィールドの制限やシリアライズを行うからです。 + +## 同じ入力データの返却 + +ここでは`UserIn`モデルを宣言しています。それには平文のパスワードが含まれています: + +```Python hl_lines="9 11" +{!../../../docs_src/response_model/tutorial002.py!} +``` + +そして、このモデルを使用して入力を宣言し、同じモデルを使って出力を宣言しています: + +```Python hl_lines="17 18" +{!../../../docs_src/response_model/tutorial002.py!} +``` + +これで、ブラウザがパスワードを使ってユーザーを作成する際に、APIがレスポンスで同じパスワードを返すようになりました。 + +この場合、ユーザー自身がパスワードを送信しているので問題ないかもしれません。 + +しかし、同じモデルを別の*path operation*に使用すると、すべてのクライアントにユーザーのパスワードを送信してしまうことになります。 + +!!! danger "危険" + ユーザーの平文のパスワードを保存したり、レスポンスで送信したりすることは絶対にしないでください。 + +## 出力モデルの追加 + +代わりに、平文のパスワードを持つ入力モデルと、パスワードを持たない出力モデルを作成することができます: + +```Python hl_lines="9 11 16" +{!../../../docs_src/response_model/tutorial003.py!} +``` + +ここでは、*path operation関数*がパスワードを含む同じ入力ユーザーを返しているにもかかわらず: + +```Python hl_lines="24" +{!../../../docs_src/response_model/tutorial003.py!} +``` + +...`response_model`を`UserOut`と宣言したことで、パスワードが含まれていません: + +```Python hl_lines="22" +{!../../../docs_src/response_model/tutorial003.py!} +``` + +そのため、**FastAPI** は出力モデルで宣言されていない全てのデータをフィルタリングしてくれます(Pydanticを使用)。 + +## ドキュメントを見る + +自動ドキュメントを見ると、入力モデルと出力モデルがそれぞれ独自のJSON Schemaを持っていることが確認できます。 + + + +そして、両方のモデルは、対話型のAPIドキュメントに使用されます: + + + +## レスポンスモデルのエンコーディングパラメータ + +レスポンスモデルにはデフォルト値を設定することができます: + +```Python hl_lines="11 13 14" +{!../../../docs_src/response_model/tutorial004.py!} +``` + +* `description: str = None`は`None`がデフォルト値です。 +* `tax: float = 10.5`は`10.5`がデフォルト値です。 +* `tags: List[str] = []` は空のリスト(`[]`)がデフォルト値です。 + +しかし、実際に保存されていない場合には結果からそれらを省略した方が良いかもしれません。 + +例えば、NoSQLデータベースに多くのオプション属性を持つモデルがあるが、デフォルト値でいっぱいの非常に長いJSONレスポンスを送信したくない場合です。 + +### `response_model_exclude_unset`パラメータの使用 + +*path operation デコレータ*に`response_model_exclude_unset=True`パラメータを設定することができます: + +```Python hl_lines="24" +{!../../../docs_src/response_model/tutorial004.py!} +``` + +そして、これらのデフォルト値はレスポンスに含まれず、実際に設定された値のみが含まれます。 + +そのため、*path operation*にID`foo`が設定されたitemのリクエストを送ると、レスポンスは以下のようになります(デフォルト値を含まない): + +```JSON +{ + "name": "Foo", + "price": 50.2 +} +``` + +!!! info "情報" + FastAPIはこれをするために、Pydanticモデルの`.dict()`をその`exclude_unset`パラメータで使用しています。 + +!!! info "情報" + 以下も使用することができます: + + * `response_model_exclude_defaults=True` + * `response_model_exclude_none=True` + + `exclude_defaults`と`exclude_none`については、Pydanticのドキュメントで説明されている通りです。 + +#### デフォルト値を持つフィールドの値を持つデータ + +しかし、ID`bar`のitemのように、デフォルト値が設定されているモデルのフィールドに値が設定されている場合: + +```Python hl_lines="3 5" +{ + "name": "Bar", + "description": "The bartenders", + "price": 62, + "tax": 20.2 +} +``` + +それらはレスポンスに含まれます。 + +#### デフォルト値と同じ値を持つデータ + +ID`baz`のitemのようにデフォルト値と同じ値を持つデータの場合: + +```Python hl_lines="3 5 6" +{ + "name": "Baz", + "description": None, + "price": 50.2, + "tax": 10.5, + "tags": [] +} +``` + +FastAPIは十分に賢いので(実際には、Pydanticが十分に賢い)`description`や`tax`、`tags`はデフォルト値と同じ値を持っているにもかかわらず、明示的に設定されていることを理解しています。(デフォルトから取得するのではなく) + +そのため、それらはJSONレスポンスに含まれることになります。 + +!!! tip "豆知識" + デフォルト値は`None`だけでなく、なんでも良いことに注意してください。 + 例えば、リスト(`[]`)や`10.5`の`float`などです。 + +### `response_model_include`と`response_model_exclude` + +*path operationデコレータ*として`response_model_include`と`response_model_exclude`も使用することができます。 + +属性名を持つ`str`の`set`を受け取り、含める(残りを省略する)か、除外(残りを含む)します。 + +これは、Pydanticモデルが1つしかなく、出力からいくつかのデータを削除したい場合のクイックショートカットとして使用することができます。 + +!!! tip "豆知識" + それでも、これらのパラメータではなく、複数のクラスを使用して、上記のようなアイデアを使うことをおすすめします。 + + これは`response_model_include`や`response_mode_exclude`を使用していくつかの属性を省略しても、アプリケーションのOpenAPI(とドキュメント)で生成されたJSON Schemaが完全なモデルになるからです。 + + 同様に動作する`response_model_by_alias`にも当てはまります。 + +```Python hl_lines="31 37" +{!../../../docs_src/response_model/tutorial005.py!} +``` + +!!! tip "豆知識" + `{"name", "description"}`の構文はこれら2つの値をもつ`set`を作成します。 + + これは`set(["name", "description"])`と同等です。 + +#### `set`の代わりに`list`を使用する + +もし`set`を使用することを忘れて、代わりに`list`や`tuple`を使用しても、FastAPIはそれを`set`に変換して正しく動作します: + +```Python hl_lines="31 37" +{!../../../docs_src/response_model/tutorial006.py!} +``` + +## まとめ + +*path operationデコレータの*`response_model`パラメータを使用して、レスポンスモデルを定義し、特にプライベートデータがフィルタリングされていることを保証します。 + +明示的に設定された値のみを返すには、`response_model_exclude_unset`を使用します。 diff --git a/docs/ja/docs/tutorial/response-status-code.md b/docs/ja/docs/tutorial/response-status-code.md new file mode 100644 index 0000000000000..ead2adddaa60b --- /dev/null +++ b/docs/ja/docs/tutorial/response-status-code.md @@ -0,0 +1,89 @@ +# レスポンスステータスコード + +レスポンスモデルを指定するのと同じ方法で、レスポンスに使用されるHTTPステータスコードを以下の*path operations*のいずれかの`status_code`パラメータで宣言することもできます。 + +* `@app.get()` +* `@app.post()` +* `@app.put()` +* `@app.delete()` +* など。 + +```Python hl_lines="6" +{!../../../docs_src/response_status_code/tutorial001.py!} +``` + +!!! note "備考" + `status_code`は「デコレータ」メソッド(`get`、`post`など)のパラメータであることに注意してください。すべてのパラメータやボディのように、*path operation関数*のものではありません。 + +`status_code`パラメータはHTTPステータスコードを含む数値を受け取ります。 + +!!! info "情報" + `status_code`は代わりに、Pythonの`http.HTTPStatus`のように、`IntEnum`を受け取ることもできます。 + +これは: + +* レスポンスでステータスコードを返します。 +* OpenAPIスキーマ(およびユーザーインターフェース)に以下のように文書化します: + + + +!!! note "備考" + いくつかのレスポンスコード(次のセクションを参照)は、レスポンスにボディがないことを示しています。 + + FastAPIはこれを知っていて、レスポンスボディがないというOpenAPIドキュメントを生成します。 + +## HTTPステータスコードについて + +!!! note "備考" + すでにHTTPステータスコードが何であるかを知っている場合は、次のセクションにスキップしてください。 + +HTTPでは、レスポンスの一部として3桁の数字のステータスコードを送信します。 + +これらのステータスコードは、それらを認識するために関連付けられた名前を持っていますが、重要な部分は番号です。 + +つまり: + +* `100`以上は「情報」のためのものです。。直接使うことはほとんどありません。これらのステータスコードを持つレスポンスはボディを持つことができません。 +* **`200`** 以上は「成功」のレスポンスのためのものです。これらは最も利用するであろうものです。 + * `200`はデフォルトのステータスコードで、すべてが「OK」であったことを意味します。 + * 別の例としては、`201`(Created)があります。これはデータベースに新しいレコードを作成した後によく使用されます。 + * 特殊なケースとして、`204`(No Content)があります。このレスポンスはクライアントに返すコンテンツがない場合に使用されます。そしてこのレスポンスはボディを持つことはできません。 +* **`300`** 以上は「リダイレクト」のためのものです。これらのステータスコードを持つレスポンスは`304`(Not Modified)を除き、ボディを持つことも持たないこともできます。 +* **`400`** 以上は「クライアントエラー」のレスポンスのためのものです。これらは、おそらく最も多用するであろう2番目のタイプです。 + * 例えば、`404`は「Not Found」レスポンスです。 + * クライアントからの一般的なエラーについては、`400`を使用することができます。 +* `500`以上はサーバーエラーのためのものです。これらを直接使うことはほとんどありません。アプリケーションコードやサーバーのどこかで何か問題が発生した場合、これらのステータスコードのいずれかが自動的に返されます。 + +!!! tip "豆知識" + それぞれのステータスコードとどのコードが何のためのコードなのかについて詳細は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`を使うこともできます。 + + **FastAPI** は、`開発者の利便性を考慮して、fastapi.status`と同じ`starlette.status`を提供しています。しかし、これはStarletteから直接提供されています。 + +## デフォルトの変更 + +後に、[高度なユーザーガイド](../advanced/response-change-status-code.md){.internal-link target=_blank}で、ここで宣言しているデフォルトとは異なるステータスコードを返す方法を見ていきます。 diff --git a/docs/ja/docs/tutorial/schema-extra-example.md b/docs/ja/docs/tutorial/schema-extra-example.md new file mode 100644 index 0000000000000..d96163b824a65 --- /dev/null +++ b/docs/ja/docs/tutorial/schema-extra-example.md @@ -0,0 +1,58 @@ +# スキーマの追加 - 例 + +JSON Schemaに追加する情報を定義することができます。 + +一般的なユースケースはこのドキュメントで示されているように`example`を追加することです。 + +JSON Schemaの追加情報を宣言する方法はいくつかあります。 + +## Pydanticの`schema_extra` + +Pydanticのドキュメント: スキーマのカスタマイズで説明されているように、`Config`と`schema_extra`を使ってPydanticモデルの例を宣言することができます: + +```Python hl_lines="15 16 17 18 19 20 21 22 23" +{!../../../docs_src/schema_extra_example/tutorial001.py!} +``` + +その追加情報はそのまま出力され、JSON Schemaに追加されます。 + +## `Field`の追加引数 + +後述する`Field`、`Path`、`Query`、`Body`などでは、任意の引数を関数に渡すことでJSON Schemaの追加情報を宣言することもできます: + +```Python hl_lines="4 10 11 12 13" +{!../../../docs_src/schema_extra_example/tutorial002.py!} +``` + +!!! warning "注意" + これらの追加引数が渡されても、文書化のためのバリデーションは追加されず、注釈だけが追加されることを覚えておいてください。 + +## `Body`の追加引数 + +追加情報を`Field`に渡すのと同じように、`Path`、`Query`、`Body`などでも同じことができます。 + +例えば、`Body`にボディリクエストの`example`を渡すことができます: + +```Python hl_lines="21 22 23 24 25 26" +{!../../../docs_src/schema_extra_example/tutorial003.py!} +``` + +## ドキュメントのUIの例 + +上記のいずれの方法でも、`/docs`の中では以下のようになります: + + + +## 技術詳細 + +`example` と `examples`について... + +JSON Schemaの最新バージョンでは`examples`というフィールドを定義していますが、OpenAPIは`examples`を持たない古いバージョンのJSON Schemaをベースにしています。 + +そのため、OpenAPIでは同じ目的のために`example`を独自に定義しており(`examples`ではなく`example`として)、それがdocs UI(Swagger UIを使用)で使用されています。 + +つまり、`example`はJSON Schemaの一部ではありませんが、OpenAPIの一部であり、それがdocs UIで使用されることになります。 + +## その他の情報 + +同じように、フロントエンドのユーザーインターフェースなどをカスタマイズするために、各モデルのJSON Schemaに追加される独自の追加情報を追加することができます。 diff --git a/docs/ja/docs/tutorial/security/first-steps.md b/docs/ja/docs/tutorial/security/first-steps.md index f83b59cfd124b..f1c43b7b45c94 100644 --- a/docs/ja/docs/tutorial/security/first-steps.md +++ b/docs/ja/docs/tutorial/security/first-steps.md @@ -27,7 +27,7 @@ ## 実行 !!! info "情報" - まず`python-multipart`をインストールします。 + まず`python-multipart`をインストールします。 例えば、`pip install python-multipart`。 diff --git a/docs/ja/docs/tutorial/security/get-current-user.md b/docs/ja/docs/tutorial/security/get-current-user.md new file mode 100644 index 0000000000000..7f8dcaad21761 --- /dev/null +++ b/docs/ja/docs/tutorial/security/get-current-user.md @@ -0,0 +1,114 @@ +# 現在のユーザーの取得 + +一つ前の章では、(依存性注入システムに基づいた)セキュリティシステムは、 *path operation関数* に `str` として `token` を与えていました: + +```Python hl_lines="10" +{!../../../docs_src/security/tutorial001.py!} +``` + +しかし、それはまだそんなに有用ではありません。 + +現在のユーザーを取得するようにしてみましょう。 + +## ユーザーモデルの作成 + +まずは、Pydanticのユーザーモデルを作成しましょう。 + +ボディを宣言するのにPydanticを使用するのと同じやり方で、Pydanticを別のどんなところでも使うことができます: + +```Python hl_lines="5 12-16" +{!../../../docs_src/security/tutorial002.py!} +``` + +## 依存関係 `get_current_user` を作成 + +依存関係 `get_current_user` を作ってみましょう。 + +依存関係はサブ依存関係を持つことができるのを覚えていますか? + +`get_current_user` は前に作成した `oauth2_scheme` と同じ依存関係を持ちます。 + +以前直接 *path operation* の中でしていたのと同じように、新しい依存関係である `get_current_user` は `str` として `token` を受け取るようになります: + +```Python hl_lines="25" +{!../../../docs_src/security/tutorial002.py!} +``` + +## ユーザーの取得 + +`get_current_user` は作成した(偽物の)ユーティリティ関数を使って、 `str` としてトークンを受け取り、先ほどのPydanticの `User` モデルを返却します: + +```Python hl_lines="19-22 26-27" +{!../../../docs_src/security/tutorial002.py!} +``` + +## 現在のユーザーの注入 + +ですので、 `get_current_user` に対して同様に *path operation* の中で `Depends` を利用できます。 + +```Python hl_lines="31" +{!../../../docs_src/security/tutorial002.py!} +``` + +Pydanticモデルの `User` として、 `current_user` の型を宣言することに注意してください。 + +その関数の中ですべての入力補完や型チェックを行う際に役に立ちます。 + +!!! tip "豆知識" + リクエストボディはPydanticモデルでも宣言できることを覚えているかもしれません。 + + ここでは `Depends` を使っているおかげで、 **FastAPI** が混乱することはありません。 + + +!!! check "確認" + 依存関係システムがこのように設計されているおかげで、 `User` モデルを返却する別の依存関係(別の"dependables")を持つことができます。 + + 同じデータ型を返却する依存関係は一つだけしか持てない、という制約が入ることはないのです。 + + +## 別のモデル + +これで、*path operation関数* の中で現在のユーザーを直接取得し、`Depends` を使って、 **依存性注入** レベルでセキュリティメカニズムを処理できるようになりました。 + +そして、セキュリティ要件のためにどんなモデルやデータでも利用することができます。(この場合は、 Pydanticモデルの `User`) + +しかし、特定のデータモデルやクラス、型に制限されることはありません。 + +モデルを、 `id` と `email` は持つが、 `username` は全く持たないようにしたいですか? わかりました。同じ手段でこうしたこともできます。 + +ある `str` だけを持ちたい? あるいはある `dict` だけですか? それとも、データベースクラスのモデルインスタンスを直接持ちたいですか? すべて同じやり方で機能します。 + +実際には、あなたのアプリケーションにはログインするようなユーザーはおらず、単にアクセストークンを持つロボットやボット、別のシステムがありますか?ここでも、全く同じようにすべて機能します。 + +あなたのアプリケーションに必要なのがどんな種類のモデル、どんな種類のクラス、どんな種類のデータベースであったとしても、 **FastAPI** は依存性注入システムでカバーしてくれます。 + + +## コードサイズ + +この例は冗長に見えるかもしれません。セキュリティとデータモデルユーティリティ関数および *path operations* が同じファイルに混在しているということを覚えておいてください。 + +しかし、ここに重要なポイントがあります。 + +セキュリティと依存性注入に関するものは、一度だけ書きます。 + +そして、それは好きなだけ複雑にすることができます。それでも、一箇所に、一度だけ書くのです。すべての柔軟性を備えます。 + +しかし、同じセキュリティシステムを使って何千ものエンドポイント(*path operations*)を持つことができます。 + +そして、それらエンドポイントのすべて(必要な、どの部分でも)がこうした依存関係や、あなたが作成する別の依存関係を再利用する利点を享受できるのです。 + +さらに、こうした何千もの *path operations* は、たった3行で表現できるのです: + +```Python hl_lines="30-32" +{!../../../docs_src/security/tutorial002.py!} +``` + +## まとめ + +これで、 *path operation関数* の中で直接現在のユーザーを取得できるようになりました。 + +既に半分のところまで来ています。 + +あとは、 `username` と `password` を実際にそのユーザーやクライアントに送る、 *path operation* を追加する必要があるだけです。 + +次はそれを説明します。 diff --git a/docs/ja/docs/tutorial/security/index.md b/docs/ja/docs/tutorial/security/index.md new file mode 100644 index 0000000000000..390f2104772e5 --- /dev/null +++ b/docs/ja/docs/tutorial/security/index.md @@ -0,0 +1,101 @@ +# セキュリティ入門 + +セキュリティ、認証、認可を扱うには多くの方法があります。 + +そして、通常、それは複雑で「難しい」トピックです。 + +多くのフレームワークやシステムでは、セキュリティと認証を処理するだけで、膨大な労力とコードが必要になります(多くの場合、書かれた全コードの50%以上を占めることがあります)。 + +**FastAPI** は、セキュリティの仕様をすべて勉強して学ぶことなく、標準的な方法で簡単に、迅速に**セキュリティ**を扱うためのツールをいくつか提供します。 + +しかし、その前に、いくつかの小さな概念を確認しましょう。 + +## お急ぎですか? + +もし、これらの用語に興味がなく、ユーザー名とパスワードに基づく認証でセキュリティを**今すぐ**確保する必要がある場合は、次の章に進んでください。 + +## OAuth2 + +OAuth2は、認証と認可を処理するためのいくつかの方法を定義した仕様です。 + +かなり広範囲な仕様で、いくつかの複雑なユースケースをカバーしています。 + +これには「サードパーティ」を使用して認証する方法が含まれています。 + +これが、「Facebook、Google、Twitter、GitHubを使ってログイン」を使用したすべてのシステムの背後で使われている仕組みです。 + +### OAuth 1 + +OAuth 1というものもありましたが、これはOAuth2とは全く異なり、通信をどのように暗号化するかという仕様が直接的に含まれており、より複雑なものとなっています。 + +現在ではあまり普及していませんし、使われてもいません。 + +OAuth2は、通信を暗号化する方法を指定せず、アプリケーションがHTTPSで提供されることを想定しています。 + +!!! tip "豆知識" + **デプロイ**のセクションでは、TraefikとLet's Encryptを使用して、無料でHTTPSを設定する方法が紹介されています。 + + +## OpenID Connect + +OpenID Connectは、**OAuth2**をベースにした別の仕様です。 + +これはOAuth2を拡張したもので、OAuth2ではやや曖昧だった部分を明確にし、より相互運用性を高めようとしたものです。 + +例として、GoogleのログインはOpenID Connectを使用しています(これはOAuth2がベースになっています)。 + +しかし、FacebookのログインはOpenID Connectをサポートしていません。OAuth2を独自にアレンジしています。 + +### OpenID (「OpenID Connect」ではない) + +また、「OpenID」という仕様もありました。それは、**OpenID Connect**と同じことを解決しようとしたものですが、OAuth2に基づいているわけではありませんでした。 + +つまり、完全な追加システムだったのです。 + +現在ではあまり普及していませんし、使われてもいません。 + +## OpenAPI + +OpenAPI(以前はSwaggerとして知られていました)は、APIを構築するためのオープンな仕様です(現在はLinux Foundationの一部になっています)。 + +**FastAPI**は、**OpenAPI**をベースにしています。 + +それが、複数の自動対話型ドキュメント・インターフェースやコード生成などを可能にしているのです。 + +OpenAPIには、複数のセキュリティ「スキーム」を定義する方法があります。 + +それらを使用することで、これらの対話型ドキュメントシステムを含む、標準ベースのツールをすべて活用できます。 + +OpenAPIでは、以下のセキュリティスキームを定義しています: + +* `apiKey`: アプリケーション固有のキーで、これらのものから取得できます。 + * クエリパラメータ + * ヘッダー + * クッキー +* `http`: 標準的なHTTP認証システムで、これらのものを含みます。 + * `bearer`: ヘッダ `Authorization` の値が `Bearer ` で、トークンが含まれます。これはOAuth2から継承しています。 + * HTTP Basic認証 + * HTTP ダイジェスト認証など +* `oauth2`: OAuth2のセキュリティ処理方法(「フロー」と呼ばれます)のすべて。 + * これらのフローのいくつかは、OAuth 2.0認証プロバイダ(Google、Facebook、Twitter、GitHubなど)を構築するのに適しています。 + * `implicit` + * `clientCredentials` + * `authorizationCode` + * しかし、同じアプリケーション内で認証を直接処理するために完全に機能する特定の「フロー」があります。 + * `password`: 次のいくつかの章では、その例を紹介します。 +* `openIdConnect`: OAuth2認証データを自動的に発見する方法を定義できます。 + * この自動検出メカニズムは、OpenID Connectの仕様で定義されているものです。 + + +!!! tip "豆知識" + Google、Facebook、Twitter、GitHubなど、他の認証/認可プロバイダを統合することも可能で、比較的簡単です。 + + 最も複雑な問題は、それらのような認証/認可プロバイダを構築することですが、**FastAPI**は、あなたのために重い仕事をこなしながら、それを簡単に行うためのツールを提供します。 + +## **FastAPI** ユーティリティ + +FastAPIは `fastapi.security` モジュールの中で、これらのセキュリティスキームごとにいくつかのツールを提供し、これらのセキュリティメカニズムを簡単に使用できるようにします。 + +次の章では、**FastAPI** が提供するこれらのツールを使って、あなたのAPIにセキュリティを追加する方法について見ていきます。 + +また、それがどのようにインタラクティブなドキュメントシステムに自動的に統合されるかも見ていきます。 diff --git a/docs/ja/docs/tutorial/security/oauth2-jwt.md b/docs/ja/docs/tutorial/security/oauth2-jwt.md index 348ffda0163e9..d5b179aa05abf 100644 --- a/docs/ja/docs/tutorial/security/oauth2-jwt.md +++ b/docs/ja/docs/tutorial/security/oauth2-jwt.md @@ -167,7 +167,7 @@ JWTトークンの署名に使用するアルゴリズム`"HS256"`を指定し JWTアクセストークンを作成し、それを返します。 -```Python hl_lines="115-128" +```Python hl_lines="115-130" {!../../../docs_src/security/tutorial004.py!} ``` diff --git a/docs/ko/docs/about/index.md b/docs/ko/docs/about/index.md new file mode 100644 index 0000000000000..ee7804d323bfd --- /dev/null +++ b/docs/ko/docs/about/index.md @@ -0,0 +1,3 @@ +# 소개 + +FastAPI에 대한 디자인, 영감 등에 대해 🤓 diff --git a/docs/ko/docs/advanced/index.md b/docs/ko/docs/advanced/index.md new file mode 100644 index 0000000000000..5e23e2809324a --- /dev/null +++ b/docs/ko/docs/advanced/index.md @@ -0,0 +1,24 @@ +# 심화 사용자 안내서 - 도입부 + +## 추가 기능 + +메인 [자습서 - 사용자 안내서](../tutorial/){.internal-link target=_blank}는 여러분이 **FastAPI**의 모든 주요 기능을 둘러보시기에 충분할 것입니다. + +이어지는 장에서는 여러분이 다른 옵션, 구성 및 추가 기능을 보실 수 있습니다. + +!!! tip "팁" + 다음 장들이 **반드시 "심화"**인 것은 아닙니다. + + 그리고 여러분의 사용 사례에 대한 해결책이 그중 하나에 있을 수 있습니다. + +## 자습서를 먼저 읽으십시오 + +여러분은 메인 [자습서 - 사용자 안내서](../tutorial/){.internal-link target=_blank}의 지식으로 **FastAPI**의 대부분의 기능을 사용하실 수 있습니다. + +이어지는 장들은 여러분이 메인 자습서 - 사용자 안내서를 이미 읽으셨으며 주요 아이디어를 알고 계신다고 가정합니다. + +## TestDriven.io 강좌 + +여러분이 문서의 이 부분을 보완하시기 위해 심화-기초 강좌 수강을 희망하신다면 다음을 참고 하시기를 바랍니다: **TestDriven.io**의 FastAPI와 Docker를 사용한 테스트 주도 개발. + +그들은 현재 전체 수익의 10퍼센트를 **FastAPI** 개발에 기부하고 있습니다. 🎉 😄 diff --git a/docs/ko/docs/async.md b/docs/ko/docs/async.md new file mode 100644 index 0000000000000..47dbaa1b01885 --- /dev/null +++ b/docs/ko/docs/async.md @@ -0,0 +1,404 @@ +# 동시성과 async / await + +*경로 작동 함수*에서의 `async def` 문법에 대한 세부사항과 비동기 코드, 동시성 및 병렬성에 대한 배경 + +## 바쁘신 경우 + +요약 + +다음과 같이 `await`를 사용해 호출하는 제3의 라이브러리를 사용하는 경우: + +```Python +results = await some_library() +``` + +다음처럼 *경로 작동 함수*를 `async def`를 사용해 선언하십시오: + +```Python hl_lines="2" +@app.get('/') +async def read_results(): + results = await some_library() + return results +``` + +!!! note "참고" + `async def`로 생성된 함수 내부에서만 `await`를 사용할 수 있습니다. + +--- + +데이터베이스, API, 파일시스템 등과 의사소통하는 제3의 라이브러리를 사용하고, 그것이 `await`를 지원하지 않는 경우(현재 거의 모든 데이터베이스 라이브러리가 그러합니다), *경로 작동 함수*를 일반적인 `def`를 사용해 선언하십시오: + +```Python hl_lines="2" +@app.get('/') +def results(): + results = some_library() + return results +``` + +--- + +만약 당신의 응용프로그램이 (어째서인지) 다른 무엇과 의사소통하고 그것이 응답하기를 기다릴 필요가 없다면 `async def`를 사용하십시오. + +--- + +모르겠다면, 그냥 `def`를 사용하십시오. + +--- + +**참고**: *경로 작동 함수*에서 필요한만큼 `def`와 `async def`를 혼용할 수 있고, 가장 알맞은 것을 선택해서 정의할 수 있습니다. FastAPI가 자체적으로 알맞은 작업을 수행할 것입니다. + +어찌되었든, 상기 어떠한 경우라도, FastAPI는 여전히 비동기적으로 작동하고 매우 빠릅니다. + +그러나 상기 작업을 수행함으로써 어느 정도의 성능 최적화가 가능합니다. + +## 기술적 세부사항 + +최신 파이썬 버전은 `async`와 `await` 문법과 함께 **“코루틴”**이라고 하는 것을 사용하는 **“비동기 코드”**를 지원합니다. + +아래 섹션들에서 해당 문장을 부분별로 살펴보겠습니다: + +* **비동기 코드** +* **`async`와 `await`** +* **코루틴** + +## 비동기 코드 + +비동기 코드란 언어 💬 가 코드의 어느 한 부분에서, 컴퓨터 / 프로그램🤖에게 *다른 무언가*가 어딘가에서 끝날 때까지 기다려야한다고 말하는 방식입니다. *다른 무언가*가 “느린-파일" 📝 이라고 불린다고 가정해봅시다. + +따라서 “느린-파일” 📝이 끝날때까지 컴퓨터는 다른 작업을 수행할 수 있습니다. + +그 다음 컴퓨터 / 프로그램 🤖 은 다시 기다리고 있기 때문에 기회가 있을 때마다 다시 돌아오거나, 혹은 당시에 수행해야하는 작업들이 완료될 때마다 다시 돌아옵니다. 그리고 그것 🤖 은 기다리고 있던 작업 중 어느 것이 이미 완료되었는지, 그것 🤖 이 해야하는 모든 작업을 수행하면서 확인합니다. + +다음으로, 그것 🤖 은 완료할 첫번째 작업에 착수하고(우리의 "느린-파일" 📝 이라고 가정합시다) 그에 대해 수행해야하는 작업을 계속합니다. + +"다른 무언가를 기다리는 것"은 일반적으로 비교적 "느린" (프로세서와 RAM 메모리 속도에 비해) I/O 작업을 의미합니다. 예를 들면 다음의 것들을 기다리는 것입니다: + +* 네트워크를 통해 클라이언트로부터 전송되는 데이터 +* 네트워크를 통해 클라이언트가 수신할, 당신의 프로그램으로부터 전송되는 데이터 +* 시스템이 읽고 프로그램에 전달할 디스크 내의 파일 내용 +* 당신의 프로그램이 시스템에 전달하는, 디스크에 작성될 내용 +* 원격 API 작업 +* 완료될 데이터베이스 작업 +* 결과를 반환하는 데이터베이스 쿼리 +* 기타 + +수행 시간의 대부분이 I/O 작업을 기다리는데에 소요되기 때문에, "I/O에 묶인" 작업이라고 불립니다. + +이것은 "비동기"라고 불리는데 컴퓨터 / 프로그램이 작업 결과를 가지고 일을 수행할 수 있도록, 느린 작업에 "동기화"되어 아무것도 하지 않으면서 작업이 완료될 정확한 시점만을 기다릴 필요가 없기 때문입니다. + +이 대신에, "비동기" 시스템에서는, 작업은 일단 완료되면, 컴퓨터 / 프로그램이 수행하고 있는 일을 완료하고 이후 다시 돌아와서 그것의 결과를 받아 이를 사용해 작업을 지속할 때까지 잠시 (몇 마이크로초) 대기할 수 있습니다. + +"동기"("비동기"의 반대)는 컴퓨터 / 프로그램이 상이한 작업들간 전환을 하기 전에 그것이 대기를 동반하게 될지라도 모든 순서를 따르기 때문에 "순차"라는 용어로도 흔히 불립니다. + +### 동시성과 버거 + +위에서 설명한 **비동기** 코드에 대한 개념은 종종 **"동시성"**이라고도 불립니다. 이것은 **"병렬성"**과는 다릅니다. + +**동시성**과 **병렬성**은 모두 "동시에 일어나는 서로 다른 일들"과 관련이 있습니다. + +하지만 *동시성*과 *병렬성*의 세부적인 개념에는 꽤 차이가 있습니다. + +차이를 확인하기 위해, 다음의 버거에 대한 이야기를 상상해보십시오: + +### 동시 버거 + +당신은 짝사랑 상대 😍 와 패스트푸드 🍔 를 먹으러 갔습니다. 당신은 점원 💁 이 당신 앞에 있는 사람들의 주문을 받을 동안 줄을 서서 기다리고 있습니다. + +이제 당신의 순서가 되어서, 당신은 당신과 짝사랑 상대 😍 를 위한 두 개의 고급스러운 버거 🍔 를 주문합니다. + +당신이 돈을 냅니다 💸. + +점원 💁 은 주방 👨‍🍳 에 요리를 하라고 전달하고, 따라서 그들은 당신의 버거 🍔 를 준비해야한다는 사실을 알게됩니다(그들이 지금은 당신 앞 고객들의 주문을 준비하고 있을지라도 말입니다). + +점원 💁 은 당신의 순서가 적힌 번호표를 줍니다. + +기다리는 동안, 당신은 짝사랑 상대 😍 와 함께 테이블을 고르고, 자리에 앉아 오랫동안 (당신이 주문한 버거는 꽤나 고급스럽기 때문에 준비하는데 시간이 조금 걸립니다 ✨🍔✨) 대화를 나눕니다. + +짝사랑 상대 😍 와 테이블에 앉아서 버거 🍔 를 기다리는 동안, 그 사람 😍 이 얼마나 멋지고, 사랑스럽고, 똑똑한지 감탄하며 시간을 보냅니다 ✨😍✨. + +짝사랑 상대 😍 와 기다리면서 얘기하는 동안, 때때로, 당신은 당신의 차례가 되었는지 보기 위해 카운터의 번호를 확인합니다. + +그러다 어느 순간, 당신의 차례가 됩니다. 카운터에 가서, 버거 🍔 를 받고, 테이블로 다시 돌아옵니다. + +당신과 짝사랑 상대 😍 는 버거 🍔 를 먹으며 좋은 시간을 보냅니다 ✨. + +--- + +당신이 이 이야기에서 컴퓨터 / 프로그램 🤖 이라고 상상해보십시오. + +줄을 서서 기다리는 동안, 당신은 아무것도 하지 않고 😴 당신의 차례를 기다리며, 어떠한 "생산적인" 일도 하지 않습니다. 하지만 점원 💁 이 (음식을 준비하지는 않고) 주문을 받기만 하기 때문에 줄이 빨리 줄어들어서 괜찮습니다. + +그다음, 당신이 차례가 오면, 당신은 실제로 "생산적인" 일 🤓 을 합니다. 당신은 메뉴를 보고, 무엇을 먹을지 결정하고, 짝사랑 상대 😍 의 선택을 묻고, 돈을 내고 💸 , 맞는 카드를 냈는지 확인하고, 비용이 제대로 지불되었는지 확인하고, 주문이 제대로 들어갔는지 확인을 하는 작업 등등을 수행합니다. + +하지만 이후에는, 버거 🍔 를 아직 받지 못했음에도, 버거가 준비될 때까지 기다려야 🕙 하기 때문에 점원 💁 과의 작업은 "일시정지" ⏸ 상태입니다. + +하지만 번호표를 받고 카운터에서 나와 테이블에 앉으면, 당신은 짝사랑 상대 😍 와 그 "작업" ⏯ 🤓 에 번갈아가며 🔀 집중합니다. 그러면 당신은 다시 짝사랑 상대 😍 에게 작업을 거는 매우 "생산적인" 일 🤓 을 합니다. + +점원 💁 이 카운터 화면에 당신의 번호를 표시함으로써 "버거 🍔 가 준비되었습니다"라고 해도, 당신은 즉시 뛰쳐나가지는 않을 것입니다. 당신은 당신의 번호를 갖고있고, 다른 사람들은 그들의 번호를 갖고있기 때문에, 아무도 당신의 버거 🍔 를 훔쳐가지 않는다는 사실을 알기 때문입니다. + +그래서 당신은 짝사랑 상대 😍 가 이야기를 끝낼 때까지 기다린 후 (현재 작업 완료 ⏯ / 진행 중인 작업 처리 🤓 ), 정중하게 미소짓고 버거를 가지러 가겠다고 말합니다 ⏸. + +그다음 당신은 카운터에 가서 🔀 , 초기 작업을 이제 완료하고 ⏯ , 버거 🍔 를 받고, 감사하다고 말하고 테이블로 가져옵니다. 이로써 카운터와의 상호작용 단계 / 작업이 종료됩니다 ⏹. + +이전 작업인 "버거 받기"가 종료되면 ⏹ "버거 먹기"라는 새로운 작업이 생성됩니다 🔀 ⏯. + +### 병렬 버거 + +이제 "동시 버거"가 아닌 "병렬 버거"를 상상해보십시오. + +당신은 짝사랑 상대 😍 와 함께 병렬 패스트푸드 🍔 를 먹으러 갔습니다. + +당신은 여러명(8명이라고 가정합니다)의 점원이 당신 앞 사람들의 주문을 받으며 동시에 요리 👩‍🍳👨‍🍳👩‍🍳👨‍🍳👩‍🍳👨‍🍳👩‍🍳👨‍🍳 도 하는 동안 줄을 서서 기다립니다. + +당신 앞 모든 사람들이 버거가 준비될 때까지 카운터에서 떠나지 않고 기다립니다 🕙 . 왜냐하면 8명의 직원들이 다음 주문을 받기 전에 버거를 준비하러 가기 때문입니다. + +마침내 당신의 차례가 왔고, 당신은 당신과 짝사랑 상대 😍 를 위한 두 개의 고급스러운 버거 🍔 를 주문합니다. + +당신이 비용을 지불합니다 💸 . + +점원이 주방에 갑니다 👨‍🍳 . + +당신은 번호표가 없기 때문에 누구도 당신의 버거 🍔 를 대신 가져갈 수 없도록 카운터에 서서 기다립니다 🕙 . + +당신과 짝사랑 상대 😍 는 다른 사람이 새치기해서 버거를 가져가지 못하게 하느라 바쁘기 때문에 🕙 , 짝사랑 상대에게 주의를 기울일 수 없습니다 😞 . + +이것은 "동기" 작업이고, 당신은 점원/요리사 👨‍🍳 와 "동기화" 되었습니다. 당신은 기다리고 🕙 , 점원/요리사 👨‍🍳 가 버거 🍔 준비를 완료한 후 당신에게 주거나, 누군가가 그것을 가져가는 그 순간에 그 곳에 있어야합니다. + +카운터 앞에서 오랫동안 기다린 후에 🕙 , 점원/요리사 👨‍🍳 가 당신의 버거 🍔 를 가지고 돌아옵니다. + +당신은 버거를 받고 짝사랑 상대와 함께 테이블로 돌아옵니다. + +단지 먹기만 하다가, 다 먹었습니다 🍔 ⏹. + +카운터 앞에서 기다리면서 🕙 너무 많은 시간을 허비했기 때문에 대화를 하거나 작업을 걸 시간이 거의 없었습니다 😞 . + +--- + +이 병렬 버거 시나리오에서, 당신은 기다리고 🕙 , 오랜 시간동안 "카운터에서 기다리는" 🕙 데에 주의를 기울이는 ⏯ 두 개의 프로세서(당신과 짝사랑 상대😍)를 가진 컴퓨터 / 프로그램 🤖 입니다. + +패스트푸드점에는 8개의 프로세서(점원/요리사) 👩‍🍳👨‍🍳👩‍🍳👨‍🍳👩‍🍳👨‍🍳👩‍🍳👨‍🍳 가 있습니다. 동시 버거는 단 두 개(한 명의 직원과 한 명의 요리사) 💁 👨‍🍳 만을 가지고 있었습니다. + +하지만 여전히, 병렬 버거 예시가 최선은 아닙니다 😞 . + +--- + +이 예시는 버거🍔 이야기와 결이 같습니다. + +더 "현실적인" 예시로, 은행을 상상해보십시오. + +최근까지, 대다수의 은행에는 다수의 은행원들 👨‍💼👨‍💼👨‍💼👨‍💼 과 긴 줄 🕙🕙🕙🕙🕙🕙🕙🕙 이 있습니다. + +모든 은행원들은 한 명 한 명의 고객들을 차례로 상대합니다 👨‍💼⏯ . + +그리고 당신은 오랫동안 줄에서 기다려야하고 🕙 , 그렇지 않으면 당신의 차례를 잃게 됩니다. + +아마 당신은 은행 🏦 심부름에 짝사랑 상대 😍 를 데려가고 싶지는 않을 것입니다. + +### 버거 예시의 결론 + +"짝사랑 상대와의 패스트푸드점 버거" 시나리오에서, 오랜 기다림 🕙 이 있기 때문에 동시 시스템 ⏸🔀⏯ 을 사용하는 것이 더 합리적입니다. + +대다수의 웹 응용프로그램의 경우가 그러합니다. + +매우 많은 수의 유저가 있지만, 서버는 그들의 요청을 전송하기 위해 그닥-좋지-않은 연결을 기다려야 합니다 🕙 . + +그리고 응답이 돌아올 때까지 다시 기다려야 합니다 🕙 . + +이 "기다림" 🕙 은 마이크로초 단위이지만, 모두 더해지면, 결국에는 매우 긴 대기시간이 됩니다. + +따라서 웹 API를 위해 비동기 ⏸🔀⏯ 코드를 사용하는 것이 합리적입니다. + +대부분의 존재하는 유명한 파이썬 프레임워크 (Flask와 Django 등)은 새로운 비동기 기능들이 파이썬에 존재하기 전에 만들어졌습니다. 그래서, 그들의 배포 방식은 병렬 실행과 새로운 기능만큼 강력하지는 않은 예전 버전의 비동기 실행을 지원합니다. + +비동기 웹 파이썬(ASGI)에 대한 주요 명세가 웹소켓을 지원하기 위해 Django에서 개발 되었음에도 그렇습니다. + +이러한 종류의 비동기성은 (NodeJS는 병렬적이지 않음에도) NodeJS가 사랑받는 이유이고, 프로그래밍 언어로서의 Go의 강점입니다. + +그리고 **FastAPI**를 사용함으로써 동일한 성능을 낼 수 있습니다. + +또한 병렬성과 비동기성을 동시에 사용할 수 있기 때문에, 대부분의 테스트가 완료된 NodeJS 프레임워크보다 더 높은 성능을 얻고 C에 더 가까운 컴파일 언어인 Go와 동등한 성능을 얻을 수 있습니다(모두 Starlette 덕분입니다). + +### 동시성이 병렬성보다 더 나은가? + +그렇지 않습니다! 그것이 이야기의 교훈은 아닙니다. + +동시성은 병렬성과 다릅니다. 그리고 그것은 많은 대기를 필요로하는 **특정한** 시나리오에서는 더 낫습니다. 이로 인해, 웹 응용프로그램 개발에서 동시성이 병렬성보다 일반적으로 훨씬 낫습니다. 하지만 모든 경우에 그런 것은 아닙니다. + +따라서, 균형을 맞추기 위해, 다음의 짧은 이야기를 상상해보십시오: + +> 당신은 크고, 더러운 집을 청소해야합니다. + +*네, 이게 전부입니다*. + +--- + +어디에도 대기 🕙 는 없고, 집안 곳곳에서 해야하는 많은 작업들만 있습니다. + +버거 예시처럼 처음에는 거실, 그 다음은 부엌과 같은 식으로 순서를 정할 수도 있으나, 무엇도 기다리지 🕙 않고 계속해서 청소 작업만 수행하기 때문에, 순서는 아무런 영향을 미치지 않습니다. + +순서가 있든 없든 동일한 시간이 소요될 것이고(동시성) 동일한 양의 작업을 하게 될 것입니다. + +하지만 이 경우에서, 8명의 전(前)-점원/요리사이면서-현(現)-청소부 👩‍🍳👨‍🍳👩‍🍳👨‍🍳👩‍🍳👨‍🍳👩‍🍳👨‍🍳 를 고용할 수 있고, 그들 각자(그리고 당신)가 집의 한 부분씩 맡아 청소를 한다면, 당신은 **병렬적**으로 작업을 수행할 수 있고, 조금의 도움이 있다면, 훨씬 더 빨리 끝낼 수 있습니다. + +이 시나리오에서, (당신을 포함한) 각각의 청소부들은 프로세서가 될 것이고, 각자의 역할을 수행합니다. + +실행 시간의 대부분이 대기가 아닌 실제 작업에 소요되고, 컴퓨터에서 작업은 CPU에서 이루어지므로, 이러한 문제를 "CPU에 묶였"다고 합니다. + +--- + +CPU에 묶인 연산에 관한 흔한 예시는 복잡한 수학 처리를 필요로 하는 경우입니다. + +예를 들어: + +* **오디오** 또는 **이미지** 처리. +* **컴퓨터 비전**: 하나의 이미지는 수백개의 픽셀로 구성되어있고, 각 픽셀은 3개의 값 / 색을 갖고 있으며, 일반적으로 해당 픽셀들에 대해 동시에 무언가를 계산해야하는 처리. +* **머신러닝**: 일반적으로 많은 "행렬"과 "벡터" 곱셈이 필요합니다. 거대한 스프레드 시트에 수들이 있고 그 수들을 동시에 곱해야 한다고 생각해보십시오. +* **딥러닝**: 머신러닝의 하위영역으로, 동일한 예시가 적용됩니다. 단지 이 경우에는 하나의 스프레드 시트에 곱해야할 수들이 있는 것이 아니라, 거대한 세트의 스프레드 시트들이 있고, 많은 경우에, 이 모델들을 만들고 사용하기 위해 특수한 프로세서를 사용합니다. + +### 동시성 + 병렬성: 웹 + 머신러닝 + +**FastAPI**를 사용하면 웹 개발에서는 매우 흔한 동시성의 이점을 (NodeJS의 주된 매력만큼) 얻을 수 있습니다. + +뿐만 아니라 머신러닝 시스템과 같이 **CPU에 묶인** 작업을 위해 병렬성과 멀티프로세싱(다수의 프로세스를 병렬적으로 동작시키는 것)을 이용하는 것도 가능합니다. + +파이썬이 **데이터 사이언스**, 머신러닝과 특히 딥러닝에 의 주된 언어라는 간단한 사실에 더해서, 이것은 FastAPI를 데이터 사이언스 / 머신러닝 웹 API와 응용프로그램에 (다른 것들보다) 좋은 선택지가 되게 합니다. + +배포시 병렬을 어떻게 가능하게 하는지 알고싶다면, [배포](/ko/deployment){.internal-link target=_blank}문서를 참고하십시오. + +## `async`와 `await` + +최신 파이썬 버전에는 비동기 코드를 정의하는 매우 직관적인 방법이 있습니다. 이는 이것을 평범한 "순차적" 코드로 보이게 하고, 적절한 순간에 당신을 위해 "대기"합니다. + +연산이 결과를 전달하기 전에 대기를 해야하고 새로운 파이썬 기능들을 지원한다면, 이렇게 코드를 작성할 수 있습니다: + +```Python +burgers = await get_burgers(2) +``` + +여기서 핵심은 `await`입니다. 이것은 파이썬에게 `burgers` 결과를 저장하기 이전에 `get_burgers(2)`의 작업이 완료되기를 🕙 기다리라고 ⏸ 말합니다. 이로 인해, 파이썬은 그동안 (다른 요청을 받는 것과 같은) 다른 작업을 수행해도 된다는 것을 🔀 ⏯ 알게될 것입니다. + +`await`가 동작하기 위해, 이것은 비동기를 지원하는 함수 내부에 있어야 합니다. 이를 위해서 함수를 `async def`를 사용해 정의하기만 하면 됩니다: + +```Python hl_lines="1" +async def get_burgers(number: int): + # Do some asynchronous stuff to create the burgers + return burgers +``` + +...`def`를 사용하는 대신: + +```Python hl_lines="2" +# This is not asynchronous +def get_sequential_burgers(number: int): + # Do some sequential stuff to create the burgers + return burgers +``` + +`async def`를 사용하면, 파이썬은 해당 함수 내에서 `await` 표현에 주의해야한다는 사실과, 해당 함수의 실행을 "일시정지"⏸하고 다시 돌아오기 전까지 다른 작업을 수행🔀할 수 있다는 것을 알게됩니다. + +`async def`f 함수를 호출하고자 할 때, "대기"해야합니다. 따라서, 아래는 동작하지 않습니다. + +```Python +# This won't work, because get_burgers was defined with: async def +burgers = get_burgers(2) +``` + +--- + +따라서, `await`f를 사용해서 호출할 수 있는 라이브러리를 사용한다면, 다음과 같이 `async def`를 사용하는 *경로 작동 함수*를 생성해야 합니다: + +```Python hl_lines="2-3" +@app.get('/burgers') +async def read_burgers(): + burgers = await get_burgers(2) + return burgers +``` + +### 더 세부적인 기술적 사항 + +`await`가 `async def`를 사용하는 함수 내부에서만 사용이 가능하다는 것을 눈치채셨을 것입니다. + +하지만 동시에, `async def`로 정의된 함수들은 "대기"되어야만 합니다. 따라서, `async def`를 사용한 함수들은 역시 `async def`를 사용한 함수 내부에서만 호출될 수 있습니다. + +그렇다면 닭이 먼저냐, 달걀이 먼저냐, 첫 `async` 함수를 어떻게 호출할 수 있겠습니까? + +**FastAPI**를 사용해 작업한다면 이것을 걱정하지 않아도 됩니다. 왜냐하면 그 "첫" 함수는 당신의 *경로 작동 함수*가 될 것이고, FastAPI는 어떻게 올바르게 처리할지 알고있기 때문입니다. + +하지만 FastAPI를 사용하지 않고 `async` / `await`를 사용하고 싶다면, 이 역시 가능합니다. + +### 당신만의 비동기 코드 작성하기 + +Starlette(그리고 FastAPI)는 AnyIO를 기반으로 하고있고, 따라서 파이썬 표준 라이브러리인 asyncioTrio와 호환됩니다. + +특히, 코드에서 고급 패턴이 필요한 고급 동시성을 사용하는 경우 직접적으로 AnyIO를 사용할 수 있습니다. + +FastAPI를 사용하지 않더라도, 높은 호환성 및 AnyIO의 이점(예: *구조화된 동시성*)을 취하기 위해 AnyIO를 사용해 비동기 응용프로그램을 작성할 수 있습니다. + +### 비동기 코드의 다른 형태 + +파이썬에서 `async`와 `await`를 사용하게 된 것은 비교적 최근의 일입니다. + +하지만 이로 인해 비동기 코드 작업이 훨씬 간단해졌습니다. + +같은 (또는 거의 유사한) 문법은 최신 버전의 자바스크립트(브라우저와 NodeJS)에도 추가되었습니다. + +하지만 그 이전에, 비동기 코드를 처리하는 것은 꽤 복잡하고 어려운 일이었습니다. + +파이썬의 예전 버전이라면, 스레드 또는 Gevent를 사용할 수 있을 것입니다. 하지만 코드를 이해하고, 디버깅하고, 이에 대해 생각하는게 훨씬 복잡합니다. + +예전 버전의 NodeJS / 브라우저 자바스크립트라면, "콜백 함수"를 사용했을 것입니다. 그리고 이로 인해 콜백 지옥에 빠지게 될 수 있습니다. + +## 코루틴 + +**코루틴**은 `async def` 함수가 반환하는 것을 칭하는 매우 고급스러운 용어일 뿐입니다. 파이썬은 그것이 시작되고 어느 시점에서 완료되지만 내부에 `await`가 있을 때마다 내부적으로 일시정지⏸될 수도 있는 함수와 유사한 것이라는 사실을 알고있습니다. + +그러나 `async` 및 `await`와 함께 비동기 코드를 사용하는 이 모든 기능들은 "코루틴"으로 간단히 요약됩니다. 이것은 Go의 주된 핵심 기능인 "고루틴"에 견줄 수 있습니다. + +## 결론 + +상기 문장을 다시 한 번 봅시다: + +> 최신 파이썬 버전은 **`async` 및 `await`** 문법과 함께 **“코루틴”**이라고 하는 것을 사용하는 **“비동기 코드”**를 지원합니다. + +이제 이 말을 조금 더 이해할 수 있을 것입니다. ✨ + +이것이 (Starlette을 통해) FastAPI를 강하게 하면서 그것이 인상적인 성능을 낼 수 있게 합니다. + +## 매우 세부적인 기술적 사항 + +!!! warning "경고" + 이 부분은 넘어가도 됩니다. + + 이것들은 **FastAPI**가 내부적으로 어떻게 동작하는지에 대한 매우 세부적인 기술사항입니다. + + 만약 기술적 지식(코루틴, 스레드, 블록킹 등)이 있고 FastAPI가 어떻게 `async def` vs `def`를 다루는지 궁금하다면, 계속하십시오. + +### 경로 작동 함수 + +경로 작동 함수를 `async def` 대신 일반적인 `def`로 선언하는 경우, (서버를 차단하는 것처럼) 그것을 직접 호출하는 대신 대기중인 외부 스레드풀에서 실행됩니다. + +만약 상기에 묘사된대로 동작하지 않는 비동기 프로그램을 사용해왔고 약간의 성능 향상 (약 100 나노초)을 위해 `def`를 사용해서 계산만을 위한 사소한 *경로 작동 함수*를 정의해왔다면, **FastAPI**는 이와는 반대라는 것에 주의하십시오. 이러한 경우에, *경로 작동 함수*가 블로킹 I/O를 수행하는 코드를 사용하지 않는 한 `async def`를 사용하는 편이 더 낫습니다. + +하지만 두 경우 모두, FastAPI가 당신이 전에 사용하던 프레임워크보다 [더 빠를](/#performance){.internal-link target=_blank} (최소한 비견될) 확률이 높습니다. + +### 의존성 + +의존성에도 동일하게 적용됩니다. 의존성이 `async def`가 아닌 표준 `def` 함수라면, 외부 스레드풀에서 실행됩니다. + +### 하위-의존성 + +함수 정의시 매개변수로 서로를 필요로하는 다수의 의존성과 하위-의존성을 가질 수 있고, 그 중 일부는 `async def`로, 다른 일부는 일반적인 `def`로 생성되었을 수 있습니다. 이것은 여전히 잘 동작하고, 일반적인 `def`로 생성된 것들은 "대기"되는 대신에 (스레드풀로부터) 외부 스레드에서 호출됩니다. + +### 다른 유틸리티 함수 + +직접 호출되는 다른 모든 유틸리티 함수는 일반적인 `def`나 `async def`로 생성될 수 있고 FastAPI는 이를 호출하는 방식에 영향을 미치지 않습니다. + +이것은 FastAPI가 당신을 위해 호출하는 함수와는 반대입니다: *경로 작동 함수*와 의존성 + +만약 당신의 유틸리티 함수가 `def`를 사용한 일반적인 함수라면, 스레드풀에서가 아니라 직접 호출(당신이 코드에 작성한 대로)될 것이고, `async def`로 생성된 함수라면 코드에서 호출할 때 그 함수를 `await` 해야 합니다. + +--- + +다시 말하지만, 이것은 당신이 이것에 대해 찾고있던 경우에 한해 유용할 매우 세부적인 기술사항입니다. + +그렇지 않은 경우, 상기의 가이드라인만으로도 충분할 것입니다: [바쁘신 경우](#in-a-hurry). diff --git a/docs/ko/docs/deployment/cloud.md b/docs/ko/docs/deployment/cloud.md new file mode 100644 index 0000000000000..2d6938e20037f --- /dev/null +++ b/docs/ko/docs/deployment/cloud.md @@ -0,0 +1,16 @@ +# FastAPI를 클라우드 제공업체에서 배포하기 + +사실상 거의 **모든 클라우드 제공업체**를 사용하여 여러분의 FastAPI 애플리케이션을 배포할 수 있습니다. + +대부분의 경우, 주요 클라우드 제공업체에서는 FastAPI를 배포할 수 있도록 가이드를 제공합니다. + +## 클라우드 제공업체 - 후원자들 + +몇몇 클라우드 제공업체들은 [**FastAPI를 후원하며**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨, 이를 통해 FastAPI와 FastAPI **생태계**가 지속적이고 건전한 **발전**을 할 수 있습니다. + +이는 FastAPI와 **커뮤니티** (여러분)에 대한 진정한 헌신을 보여줍니다. 그들은 여러분에게 **좋은 서비스**를 제공할 뿐 만이 아니라 여러분이 **훌륭하고 건강한 프레임워크인** FastAPI 를 사용하길 원하기 때문입니다. 🙇 + +아래와 같은 서비스를 사용해보고 각 서비스의 가이드를 따를 수도 있습니다: + +* Platform.sh +* Porter diff --git a/docs/ko/docs/deployment/docker.md b/docs/ko/docs/deployment/docker.md new file mode 100644 index 0000000000000..1c7bced2caba4 --- /dev/null +++ b/docs/ko/docs/deployment/docker.md @@ -0,0 +1,698 @@ +# 컨테이너의 FastAPI - 도커 + +FastAPI 어플리케이션을 배포할 때 일반적인 접근 방법은 **리눅스 컨테이너 이미지**를 생성하는 것입니다. 이 방법은 주로 **도커**를 사용해 이루어집니다. 그런 다음 해당 컨테이너 이미지를 몇가지 방법으로 배포할 수 있습니다. + +리눅스 컨테이너를 사용하는 데에는 **보안**, **반복 가능성**, **단순함** 등의 장점이 있습니다. + +!!! tip "팁" + 시간에 쫓기고 있고 이미 이런것들을 알고 있다면 [`Dockerfile`👇](#build-a-docker-image-for-fastapi)로 점프할 수 있습니다. + +
+도커파일 미리보기 👀 + +```Dockerfile +FROM python:3.9 + +WORKDIR /code + +COPY ./requirements.txt /code/requirements.txt + +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt + +COPY ./app /code/app + +CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] + +# If running behind a proxy like Nginx or Traefik add --proxy-headers +# CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80", "--proxy-headers"] +``` + +
+ +## 컨테이너란 + +컨테이너(주로 리눅스 컨테이너)는 어플리케이션의 의존성과 필요한 파일들을 모두 패키징하는 매우 **가벼운** 방법입니다. 컨테이너는 같은 시스템에 있는 다른 컨테이너(다른 어플리케이션이나 요소들)와 독립적으로 유지됩니다. + +리눅스 컨테이너는 호스트(머신, 가상 머신, 클라우드 서버 등)와 같은 리눅스 커널을 사용해 실행됩니다. 이말은 리눅스 컨테이너가 (전체 운영체제를 모방하는 다른 가상 머신과 비교했을 때) 매우 가볍다는 것을 의미합니다. + +이 방법을 통해, 컨테이너는 직접 프로세스를 실행하는 것과 비슷한 정도의 **적은 자원**을 소비합니다 (가상 머신은 훨씬 많은 자원을 소비할 것입니다). + +컨테이너는 또한 그들만의 **독립된** 실행 프로세스 (일반적으로 하나의 프로세스로 충분합니다), 파일 시스템, 그리고 네트워크를 가지므로 배포, 보안, 개발 및 기타 과정을 단순화 합니다. + +## 컨테이너 이미지란 + +**컨테이너**는 **컨테이너 이미지**를 실행한 것 입니다. + +컨테이너 이미지란 컨테이너에 필요한 모든 파일, 환경 변수 그리고 디폴트 명령/프로그램의 **정적** 버전입니다. 여기서 **정적**이란 말은 컨테이너 **이미지**가 작동되거나 실행되지 않으며, 단지 패키지 파일과 메타 데이터라는 것을 의미합니다. + +저장된 정적 컨텐츠인 **컨테이너 이미지**와 대조되게, **컨테이너**란 보통 실행될 수 있는 작동 인스턴스를 의미합니다. + +**컨테이너**가 (**컨테이너 이미지**로 부터) 시작되고 실행되면, 컨테이너는 파일이나 환경 변수를 생성하거나 변경할 수 있습니다. 이러한 변화는 오직 컨테이너에서만 존재하며, 그 기반이 되는 컨테이너 이미지에는 지속되지 않습니다 (즉 디스크에는 저장되지 않습니다). + +컨테이너 이미지는 **프로그램** 파일과 컨텐츠, 즉 `python`과 어떤 파일 `main.py`에 비교할 수 있습니다. + +그리고 (**컨테이너 이미지**와 대비해서) **컨테이너**는 이미지의 실제 실행 인스턴스로 **프로세스**에 비교할 수 있습니다. 사실, 컨테이너는 **프로세스 러닝**이 있을 때만 실행됩니다 (그리고 보통 하나의 프로세스 입니다). 컨테이너는 내부에서 실행되는 프로세스가 없으면 종료됩니다. + +## 컨테이너 이미지 + +도커는 **컨테이너 이미지**와 **컨테이너**를 생성하고 관리하는데 주요 도구 중 하나가 되어왔습니다. + +그리고 도커 허브에 다양한 도구, 환경, 데이터베이스, 그리고 어플리케이션에 대해 미리 만들어진 **공식 컨테이너 이미지**가 공개되어 있습니다. + +예를 들어, 공식 파이썬 이미지가 있습니다. + +또한 다른 대상, 예를 들면 데이터베이스를 위한 이미지들도 있습니다: + +* PostgreSQL +* MySQL +* MongoDB +* Redis 등 + +미리 만들어진 컨테이너 이미지를 사용하면 서로 다른 도구들을 **결합**하기 쉽습니다. 대부분의 경우에, **공식 이미지들**을 사용하고 환경 변수를 통해 설정할 수 있습니다. + +이런 방법으로 대부분의 경우에 컨테이너와 도커에 대해 배울 수 있으며 다양한 도구와 요소들에 대한 지식을 재사용할 수 있습니다. + +따라서, 서로 다른 **다중 컨테이너**를 생성한 다음 이들을 연결할 수 있습니다. 예를 들어 데이터베이스, 파이썬 어플리케이션, 리액트 프론트엔드 어플리케이션을 사용하는 웹 서버에 대한 컨테이너를 만들어 이들의 내부 네트워크로 각 컨테이너를 연결할 수 있습니다. + +모든 컨테이너 관리 시스템(도커나 쿠버네티스)은 이러한 네트워킹 특성을 포함하고 있습니다. + +## 컨테이너와 프로세스 + +**컨테이너 이미지**는 보통 **컨테이너**를 시작하기 위해 필요한 메타데이터와 디폴트 커맨드/프로그램과 그 프로그램에 전달하기 위한 파라미터들을 포함합니다. 이는 커맨드 라인에서 프로그램을 실행할 때 필요한 값들과 유사합니다. + +**컨테이너**가 시작되면, 해당 커맨드/프로그램이 실행됩니다 (그러나 다른 커맨드/프로그램을 실행하도록 오버라이드 할 수 있습니다). + +컨테이너는 **메인 프로세스**(커맨드 또는 프로그램)이 실행되는 동안 실행됩니다. + +컨테이너는 일반적으로 **단일 프로세스**를 가지고 있지만, 메인 프로세스의 서브 프로세스를 시작하는 것도 가능하며, 이 방법으로 하나의 컨테이너에 **다중 프로세스**를 가질 수 있습니다. + +그러나 **최소한 하나의 실행중인 프로세스**를 가지지 않고서는 실행중인 컨테이너를 가질 수 없습니다. 만약 메인 프로세스가 중단되면, 컨테이너도 중단됩니다. + +## FastAPI를 위한 도커 이미지 빌드하기 + +이제 무언가를 만들어 봅시다! 🚀 + +**공식 파이썬** 이미지에 기반하여, FastAPI를 위한 **도커 이미지**를 **맨 처음부터** 생성하는 방법을 보이겠습니다. + +**대부분의 경우**에 다음과 같은 것들을 하게 됩니다. 예를 들면: + +* **쿠버네티스** 또는 유사한 도구 사용하기 +* **라즈베리 파이**로 실행하기 +* 컨테이너 이미지를 실행할 클라우드 서비스 사용하기 등 + +### 요구 패키지 + +일반적으로는 어플리케이션의 특정 파일을 위한 **패키지 요구 조건**이 있을 것입니다. + +그 요구 조건을 **설치**하는 방법은 여러분이 사용하는 도구에 따라 다를 것입니다. + +가장 일반적인 방법은 패키지 이름과 버전이 줄 별로 기록된 `requirements.txt` 파일을 만드는 것입니다. + +버전의 범위를 설정하기 위해서는 [FastAPI 버전들에 대하여](./versions.md){.internal-link target=_blank}에 쓰여진 것과 같은 아이디어를 사용합니다. + +예를 들어, `requirements.txt` 파일은 다음과 같을 수 있습니다: + +``` +fastapi>=0.68.0,<0.69.0 +pydantic>=1.8.0,<2.0.0 +uvicorn>=0.15.0,<0.16.0 +``` + +그리고 일반적으로 패키지 종속성은 `pip`로 설치합니다. 예를 들어: + +
+ +```console +$ pip install -r requirements.txt +---> 100% +Successfully installed fastapi pydantic uvicorn +``` + +
+ +!!! info "정보" + 패키지 종속성을 정의하고 설치하기 위한 방법과 도구는 다양합니다. + + 나중에 아래 세션에서 Poetry를 사용한 예시를 보이겠습니다. 👇 + +### **FastAPI** 코드 생성하기 + +* `app` 디렉터리를 생성하고 이동합니다. +* 빈 파일 `__init__.py`을 생성합니다. +* 다음과 같은 `main.py`을 생성합니다: + +```Python +from typing import Union + +from fastapi import FastAPI + +app = FastAPI() + + +@app.get("/") +def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} +``` + +### 도커파일 + +이제 같은 프로젝트 디렉터리에 다음과 같은 파일 `Dockerfile`을 생성합니다: + +```{ .dockerfile .annotate } +# (1) +FROM python:3.9 + +# (2) +WORKDIR /code + +# (3) +COPY ./requirements.txt /code/requirements.txt + +# (4) +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt + +# (5) +COPY ./app /code/app + +# (6) +CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] +``` + +1. 공식 파이썬 베이스 이미지에서 시작합니다. + +2. 현재 워킹 디렉터리를 `/code`로 설정합니다. + + 여기에 `requirements.txt` 파일과 `app` 디렉터리를 위치시킬 것입니다. + +3. 요구 조건과 파일을 `/code` 디렉터리로 복사합니다. + + 처음에는 **오직** 요구 조건이 필요한 파일만 복사하고, 이외의 코드는 그대로 둡니다. + + 이 파일이 **자주 바뀌지 않기 때문에**, 도커는 파일을 탐지하여 이 단계의 **캐시**를 사용하여 다음 단계에서도 캐시를 사용할 수 있도록 합니다. + +4. 요구 조건 파일에 있는 패키지 종속성을 설치합니다. + + `--no-cache-dir` 옵션은 `pip`에게 다운로드한 패키지들을 로컬 환경에 저장하지 않도록 전달합니다. 이는 마치 같은 패키지를 설치하기 위해 오직 `pip`만 다시 실행하면 될 것 같지만, 컨테이너로 작업하는 경우 그렇지는 않습니다. + + !!! 노트 + `--no-cache-dir` 는 오직 `pip`와 관련되어 있으며, 도커나 컨테이너와는 무관합니다. + + `--upgrade` 옵션은 `pip`에게 설치된 패키지들을 업데이트하도록 합니다. + + 이전 단계에서 파일을 복사한 것이 **도커 캐시**에 의해 탐지되기 때문에, 이 단계에서도 가능한 한 **도커 캐시**를 사용하게 됩니다. + + 이 단계에서 캐시를 사용하면 **매번** 모든 종속성을 다운로드 받고 설치할 필요가 없어, 개발 과정에서 이미지를 지속적으로 생성하는 데에 드는 **시간**을 많이 **절약**할 수 있습니다. + +5. `/code` 디렉터리에 `./app` 디렉터리를 복사합니다. + + **자주 변경되는** 모든 코드를 포함하고 있기 때문에, 도커 **캐시**는 이 단계나 **이후의 단계에서** 잘 사용되지 않습니다. + + 그러므로 컨테이너 이미지 빌드 시간을 최적화하기 위해 `Dockerfile`의 **거의 끝 부분**에 입력하는 것이 중요합니다. + +6. `uvicorn` 서버를 실행하기 위해 **커맨드**를 설정합니다. + + `CMD`는 문자열 리스트를 입력받고, 각 문자열은 커맨드 라인의 각 줄에 입력할 문자열입니다. + + 이 커맨드는 **현재 워킹 디렉터리**에서 실행되며, 이는 위에서 `WORKDIR /code`로 설정한 `/code` 디렉터리와 같습니다. + + 프로그램이 `/code`에서 시작하고 그 속에 `./app` 디렉터리가 여러분의 코드와 함께 들어있기 때문에, **Uvicorn**은 이를 보고 `app`을 `app.main`으로부터 **불러 올** 것입니다. + +!!! tip "팁" + 각 코드 라인을 코드의 숫자 버블을 클릭하여 리뷰할 수 있습니다. 👆 + +이제 여러분은 다음과 같은 디렉터리 구조를 가지고 있을 것입니다: + +``` +. +├── app +│   ├── __init__.py +│ └── main.py +├── Dockerfile +└── requirements.txt +``` + +#### TLS 종료 프록시의 배후 + +만약 여러분이 컨테이너를 Nginx 또는 Traefik과 같은 TLS 종료 프록시 (로드 밸런서) 뒤에서 실행하고 있다면, `--proxy-headers` 옵션을 더하는 것이 좋습니다. 이 옵션은 Uvicorn에게 어플리케이션이 HTTPS 등의 뒤에서 실행되고 있으므로 프록시에서 전송된 헤더를 신뢰할 수 있다고 알립니다. + +```Dockerfile +CMD ["uvicorn", "app.main:app", "--proxy-headers", "--host", "0.0.0.0", "--port", "80"] +``` + +#### 도커 캐시 + +이 `Dockerfile`에는 중요한 트릭이 있는데, 처음에는 **의존성이 있는 파일만** 복사하고, 나머지 코드는 그대로 둡니다. 왜 이런 방법을 써야하는지 설명하겠습니다. + +```Dockerfile +COPY ./requirements.txt /code/requirements.txt +``` + +도커와 다른 도구들은 컨테이너 이미지를 **증가하는 방식으로 빌드**합니다. `Dockerfile`의 맨 윗 부분부터 시작해, 레이어 위에 새로운 레이어를 더하는 방식으로, `Dockerfile`의 각 지시 사항으로 부터 생성된 어떤 파일이든 더해갑니다. + +도커 그리고 이와 유사한 도구들은 이미지 생성 시에 **내부 캐시**를 사용합니다. 만약 어떤 파일이 마지막으로 컨테이너 이미지를 빌드한 때로부터 바뀌지 않았다면, 파일을 다시 복사하여 새로운 레이어를 처음부터 생성하는 것이 아니라, 마지막에 생성했던 **같은 레이어를 재사용**합니다. + +단지 파일 복사를 지양하는 것으로 효율이 많이 향상되는 것은 아니지만, 그 단계에서 캐시를 사용했기 때문에, **다음 단계에서도 마찬가지로 캐시를 사용**할 수 있습니다. 예를 들어, 다음과 같은 의존성을 설치하는 지시 사항을 위한 캐시를 사용할 수 있습니다: + +```Dockerfile +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt +``` + +패키지를 포함하는 파일은 **자주 변경되지 않습니다**. 따라서 해당 파일만 복사하므로서, 도커는 그 단계의 **캐시를 사용**할 수 있습니다. + +그 다음으로, 도커는 **다음 단계에서** 의존성을 다운로드하고 설치하는 **캐시를 사용**할 수 있게 됩니다. 바로 이 과정에서 우리는 **많은 시간을 절약**하게 됩니다. ✨ ...그리고 기다리는 지루함도 피할 수 있습니다. 😪😆 + +패키지 의존성을 다운로드 받고 설치하는 데이는 **수 분이 걸릴 수 있지만**, **캐시**를 사용하면 최대 **수 초만에** 끝낼 수 있습니다. + +또한 여러분이 개발 과정에서 코드의 변경 사항이 반영되었는지 확인하기 위해 컨테이너 이미지를 계속해서 빌드하면, 절약된 시간은 축적되어 더욱 커질 것입니다. + +그리고 나서 `Dockerfile`의 거의 끝 부분에서, 모든 코드를 복사합니다. 이것이 **가장 빈번하게 변경**되는 부분이며, 대부분의 경우에 이 다음 단계에서는 캐시를 사용할 수 없기 때문에 가장 마지막에 둡니다. + +```Dockerfile +COPY ./app /code/app +``` + +### 도커 이미지 생성하기 + +이제 모든 파일이 제자리에 있으니, 컨테이너 이미지를 빌드합니다. + +* (여러분의 `Dockerfile`과 `app` 디렉터리가 위치한) 프로젝트 디렉터리로 이동합니다. +* FastAPI 이미지를 빌드합니다: + +
+ +```console +$ docker build -t myimage . + +---> 100% +``` + +
+ +!!! tip "팁" + 맨 끝에 있는 `.` 에 주목합시다. 이는 `./`와 동등하며, 도커에게 컨테이너 이미지를 빌드하기 위한 디렉터리를 알려줍니다. + + 이 경우에는 현재 디렉터리(`.`)와 같습니다. + +### 도커 컨테이너 시작하기 + +* 여러분의 이미지에 기반하여 컨테이너를 실행합니다: + +
+ +```console +$ docker run -d --name mycontainer -p 80:80 myimage +``` + +
+ +## 체크하기 + +여러분의 도커 컨테이너 URL에서 실행 사항을 체크할 수 있습니다. 예를 들어: http://192.168.99.100/items/5?q=somequery 또는 http://127.0.0.1/items/5?q=somequery (또는 동일하게, 여러분의 도커 호스트를 이용해서 체크할 수도 있습니다). + +아래와 비슷한 것을 보게 될 것입니다: + +```JSON +{"item_id": 5, "q": "somequery"} +``` + +## 인터랙티브 API 문서 + +이제 여러분은 http://192.168.99.100/docs 또는 http://127.0.0.1/docs로 이동할 수 있습니다(또는, 여러분의 도커 호스트를 이용할 수 있습니다). + +여러분은 자동으로 생성된 인터랙티브 API(Swagger UI에서 제공된)를 볼 수 있습니다: + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +## 대안 API 문서 + +또한 여러분은 http://192.168.99.100/redoc 또는 http://127.0.0.1/redoc으로 이동할 수 있습니다(또는, 여러분의 도커 호스트를 이용할 수 있습니다). + +여러분은 자동으로 생성된 대안 문서(ReDoc에서 제공된)를 볼 수 있습니다: + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +## 단일 파일 FastAPI로 도커 이미지 생성하기 + +만약 여러분의 FastAPI가 하나의 파일이라면, 예를 들어 `./app` 디렉터리 없이 `main.py` 파일만으로 이루어져 있다면, 파일 구조는 다음과 유사할 것입니다: + +``` +. +├── Dockerfile +├── main.py +└── requirements.txt +``` + +그러면 여러분들은 `Dockerfile` 내에 있는 파일을 복사하기 위해 그저 상응하는 경로를 바꾸기만 하면 됩니다: + +```{ .dockerfile .annotate hl_lines="10 13" } +FROM python:3.9 + +WORKDIR /code + +COPY ./requirements.txt /code/requirements.txt + +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt + +# (1) +COPY ./main.py /code/ + +# (2) +CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] +``` + +1. `main.py` 파일을 `/code` 디렉터리로 곧바로 복사합니다(`./app` 디렉터리는 고려하지 않습니다). + +2. Uvicorn을 실행해 `app` 객체를 (`app.main` 대신) `main`으로 부터 불러오도록 합니다. + +그 다음 Uvicorn 커맨드를 조정해서 FastAPI 객체를 불러오는데 `app.main` 대신에 새로운 모듈 `main`을 사용하도록 합니다. + +## 배포 개념 + +이제 컨테이너의 측면에서 [배포 개념](./concepts.md){.internal-link target=_blank}에서 다루었던 것과 같은 배포 개념에 대해 이야기해 보겠습니다. + +컨테이너는 주로 어플리케이션을 빌드하고 배포하기 위한 과정을 단순화하는 도구이지만, **배포 개념**에 대한 특정한 접근법을 강요하지 않기 때문에 가능한 배포 전략에는 여러가지가 있습니다. + +**좋은 소식**은 서로 다른 전략들을 포괄하는 배포 개념이 있다는 점입니다. 🎉 + +컨테이너 측면에서 **배포 개념**을 리뷰해 보겠습니다: + +* HTTPS +* 구동하기 +* 재시작 +* 복제 (실행 중인 프로세스 개수) +* 메모리 +* 시작하기 전 단계들 + +## HTTPS + +만약 우리가 FastAPI 어플리케이션을 위한 **컨테이너 이미지**에만 집중한다면 (그리고 나중에 실행될 **컨테이너**에), HTTPS는 일반적으로 다른 도구에 의해 **외부적으로** 다루어질 것 입니다. + +**HTTPS**와 **인증서**의 **자동** 취득을 다루는 것은 다른 컨테이너가 될 수 있는데, 예를 들어 Traefik을 사용하는 것입니다. + +!!! tip "팁" + Traefik은 도커, 쿠버네티스, 그리고 다른 도구와 통합되어 있어 여러분의 컨테이너를 포함하는 HTTPS를 셋업하고 설정하는 것이 매우 쉽습니다. + +대안적으로, HTTPS는 클라우드 제공자에 의해 서비스의 일환으로 다루어질 수도 있습니다 (이때도 어플리케이션은 여전히 컨테이너에서 실행될 것입니다). + +## 구동과 재시작 + +여러분의 컨테이너를 **시작하고 실행하는** 데에 일반적으로 사용되는 도구는 따로 있습니다. + +이는 **도커** 자체일 수도 있고, **도커 컴포즈**, **쿠버네티스**, **클라우드 서비스** 등이 될 수 있습니다. + +대부분 (또는 전체) 경우에, 컨테이너를 구동하거나 고장시에 재시작하도록 하는 간단한 옵션이 있습니다. 예를 들어, 도커에서는, 커맨드 라인 옵션 `--restart` 입니다. + +컨테이너를 사용하지 않고서는, 어플리케이션을 구동하고 재시작하는 것이 매우 번거롭고 어려울 수 있습니다. 하지만 **컨테이너를 사용한다면** 대부분의 경우에 이런 기능은 기본적으로 포함되어 있습니다. ✨ + +## 복제 - 프로세스 개수 + +만약 여러분이 **쿠버네티스**와 머신 클러스터, 도커 스왐 모드, 노마드, 또는 다른 여러 머신 위에 분산 컨테이너를 관리하는 복잡한 시스템을 다루고 있다면, 여러분은 각 컨테이너에서 (워커와 함께 사용하는 Gunicorn 같은) **프로세스 매니저** 대신 **클러스터 레벨**에서 **복제를 다루**고 싶을 것입니다. + +쿠버네티스와 같은 분산 컨테이너 관리 시스템 중 일부는 일반적으로 들어오는 요청에 대한 **로드 밸런싱**을 지원하면서 **컨테이너 복제**를 다루는 통합된 방법을 가지고 있습니다. 모두 **클러스터 레벨**에서 말이죠. + +이런 경우에, 여러분은 [위에서 묘사된 것](#dockerfile)처럼 **처음부터 도커 이미지를** 빌드해서, 의존성을 설치하고, Uvicorn 워커를 관리하는 Gunicorn 대신 **단일 Uvicorn 프로세스**를 실행하고 싶을 것입니다. + +### 로드 밸런서 + +컨테이너로 작업할 때, 여러분은 일반적으로 **메인 포트의 상황을 감지하는** 요소를 가지고 있을 것입니다. 이는 **HTTPS**를 다루는 **TLS 종료 프록시**와 같은 다른 컨테이너일 수도 있고, 유사한 다른 도구일 수도 있습니다. + +이 요소가 요청들의 **로드**를 읽어들이고 각 워커에게 (바라건대) **균형적으로** 분배한다면, 이 요소는 일반적으로 **로드 밸런서**라고 불립니다. + +!!! tip "팁" + HTTPS를 위해 사용된 **TLS 종료 프록시** 요소 또한 **로드 밸런서**가 될 수 있습니다. + +또한 컨테이너로 작업할 때, 컨테이너를 시작하고 관리하기 위해 사용한 것과 동일한 시스템은 이미 해당 **로드 밸런서**로 부터 여러분의 앱에 해당하는 컨테이너로 **네트워크 통신**(예를 들어, HTTP 요청)을 전송하는 내부적인 도구를 가지고 있을 것입니다 (여기서도 로드 밸런서는 **TLS 종료 프록시**일 수 있습니다). + +### 하나의 로드 밸런서 - 다중 워커 컨테이너 + +**쿠버네티스**나 또는 다른 분산 컨테이너 관리 시스템으로 작업할 때, 시스템 내부의 네트워킹 메커니즘을 이용함으로써 메인 **포트**를 감지하고 있는 단일 **로드 밸런서**는 여러분의 앱에서 실행되고 있는 **여러개의 컨테이너**에 통신(요청들)을 전송할 수 있게 됩니다. + +여러분의 앱에서 실행되고 있는 각각의 컨테이너는 일반적으로 **하나의 프로세스**만 가질 것입니다 (예를 들어, FastAPI 어플리케이션에서 실행되는 하나의 Uvicorn 프로세스처럼). 이 컨테이너들은 모두 같은 것을 실행하는 점에서 **동일한 컨테이너**이지만, 프로세스, 메모리 등은 공유하지 않습니다. 이 방식으로 여러분은 CPU의 **서로 다른 코어들** 또는 **서로 다른 머신들**을 **병렬화**하는 이점을 얻을 수 있습니다. + +또한 **로드 밸런서**가 있는 분산 컨테이너 시스템은 여러분의 앱에 있는 컨테이너 각각에 **차례대로 요청을 분산**시킬 것 입니다. 따라서 각 요청은 여러분의 앱에서 실행되는 여러개의 **복제된 컨테이너들** 중 하나에 의해 다루어질 것 입니다. + +그리고 일반적으로 **로드 밸런서**는 여러분의 클러스터에 있는 *다른* 앱으로 가는 요청들도 다룰 수 있으며 (예를 들어, 다른 도메인으로 가거나 다른 URL 경로 접두사를 가지는 경우), 이 통신들을 클러스터에 있는 *바로 그 다른* 어플리케이션으로 제대로 전송할 수 있습니다. + +### 단일 프로세스를 가지는 컨테이너 + +이 시나리오의 경우, 여러분은 이미 클러스터 레벨에서 복제를 다루고 있을 것이므로 **컨테이너 당 단일 (Uvicorn) 프로세스**를 가지고자 할 것입니다. + +따라서, 여러분은 Gunicorn 이나 Uvicorn 워커, 또는 Uvicorn 워커를 사용하는 Uvicorn 매니저와 같은 프로세스 매니저를 가지고 싶어하지 **않을** 것입니다. 여러분은 컨테이너 당 **단일 Uvicorn 프로세스**를 가지고 싶어할 것입니다 (그러나 아마도 다중 컨테이너를 가질 것입니다). + +이미 여러분이 클러스터 시스템을 관리하고 있으므로, (Uvicorn 워커를 관리하는 Gunicorn 이나 Uvicorn 처럼) 컨테이너 내에 다른 프로세스 매니저를 가지는 것은 **불필요한 복잡성**만 더하게 될 것입니다. + +### 다중 프로세스를 가지는 컨테이너와 특수한 경우들 + +당연한 말이지만, 여러분이 내부적으로 **Uvicorn 워커 프로세스들**를 시작하는 **Gunicorn 프로세스 매니저**를 가지는 단일 컨테이너를 원하는 **특수한 경우**도 있을 것입니다. + +그런 경우에, 여러분들은 **Gunicorn**을 프로세스 매니저로 포함하는 **공식 도커 이미지**를 사용할 수 있습니다. 이 프로세스 매니저는 다중 **Uvicorn 워커 프로세스들**을 실행하며, 디폴트 세팅으로 현재 CPU 코어에 기반하여 자동으로 워커 개수를 조정합니다. 이 사항에 대해서는 아래의 [Gunicorn과 함께하는 공식 도커 이미지 - Uvicorn](#official-docker-image-with-gunicorn-uvicorn)에서 더 다루겠습니다. + +이런 경우에 해당하는 몇가지 예시가 있습니다: + +#### 단순한 앱 + +만약 여러분의 어플리케이션이 **충분히 단순**해서 (적어도 아직은) 프로세스 개수를 파인-튠 할 필요가 없거나 클러스터가 아닌 **단일 서버**에서 실행하고 있다면, 여러분은 컨테이너 내에 프로세스 매니저를 사용하거나 (공식 도커 이미지에서) 자동으로 설정되는 디폴트 값을 사용할 수 있습니다. + +#### 도커 구성 + +여러분은 **도커 컴포즈**로 (클러스터가 아닌) **단일 서버로** 배포할 수 있으며, 이 경우에 공유된 네트워크와 **로드 밸런싱**을 포함하는 (도커 컴포즈로) 컨테이너의 복제를 관리하는 단순한 방법이 없을 수도 있습니다. + +그렇다면 여러분은 **프로세스 매니저**와 함께 내부에 **몇개의 워커 프로세스들**을 시작하는 **단일 컨테이너**를 필요로 할 수 있습니다. + +#### Prometheus와 다른 이유들 + +여러분은 **단일 프로세스**를 가지는 **다중 컨테이너** 대신 **다중 프로세스**를 가지는 **단일 컨테이너**를 채택하는 **다른 이유**가 있을 수 있습니다. + +예를 들어 (여러분의 장치 설정에 따라) Prometheus 익스포터와 같이 같은 컨테이너에 들어오는 **각 요청에 대해** 접근권한을 가지는 도구를 사용할 수 있습니다. + +이 경우에 여러분이 **여러개의 컨테이너들**을 가지고 있다면, Prometheus가 **메트릭을 읽어 들일 때**, 디폴트로 **매번 하나의 컨테이너**(특정 리퀘스트를 관리하는 바로 그 컨테이너)로 부터 읽어들일 것입니다. 이는 모든 복제된 컨테이너에 대해 **축적된 메트릭들**을 읽어들이는 것과 대비됩니다. + +그렇다면 이 경우에는 **다중 프로세스**를 가지는 **하나의 컨테이너**를 두어서 같은 컨테이너에서 모든 내부 프로세스에 대한 Prometheus 메트릭을 수집하는 로컬 도구(예를 들어 Prometheus 익스포터 같은)를 두어서 이 메그릭들을 하나의 컨테이너에 내에서 공유하는 방법이 더 단순할 것입니다. + +--- + +요점은, 이 중의 **어느것도** 여러분들이 반드시 따라야하는 **확정된 사실**이 아니라는 것입니다. 여러분은 이 아이디어들을 **여러분의 고유한 이용 사례를 평가**하는데 사용하고, 여러분의 시스템에 가장 적합한 접근법이 어떤 것인지 결정하며, 다음의 개념들을 관리하는 방법을 확인할 수 있습니다: + +* 보안 - HTTPS +* 구동하기 +* 재시작 +* 복제 (실행 중인 프로세스 개수) +* 메모리 +* 시작하기 전 단계들 + +## 메모리 + +만약 여러분이 **컨테이너 당 단일 프로세스**를 실행한다면, 여러분은 각 컨테이너(복제된 경우에는 여러개의 컨테이너들)에 대해 잘 정의되고, 안정적이며, 제한된 용량의 메모리 소비량을 가지고 있을 것입니다. + +그러면 여러분의 컨테이너 관리 시스템(예를 들어 **쿠버네티스**) 설정에서 앞서 정의된 것과 같은 메모리 제한과 요구사항을 설정할 수 있습니다. 이런 방법으로 **가용 머신**이 필요로하는 메모리와 클러스터에 있는 가용 머신들을 염두에 두고 **컨테이너를 복제**할 수 있습니다. + +만약 여러분의 어플리케이션이 **단순**하다면, 이것은 **문제가 되지 않을** 것이고, 고정된 메모리 제한을 구체화할 필요도 없을 것입니다. 하지만 여러분의 어플리케이션이 (예를 들어 **머신 러닝** 모델같이) **많은 메모리를 소요한다면**, 어플리케이션이 얼마나 많은 양의 메모리를 사용하는지 확인하고 **각 머신에서** 사용하는 **컨테이너의 수**를 조정할 필요가 있습니다 (그리고 필요에 따라 여러분의 클러스터에 머신을 추가할 수 있습니다). + +만약 여러분이 **컨테이너 당 여러개의 프로세스**를 실행한다면 (예를 들어 공식 도커 이미지 처럼), 여러분은 시작된 프로세스 개수가 가용한 것 보다 **더 많은 메모리를 소비**하지 않는지 확인해야 합니다. + +## 시작하기 전 단계들과 컨테이너 + +만약 여러분이 컨테이너(예를 들어 도커, 쿠버네티스)를 사용한다면, 여러분이 접근할 수 있는 주요 방법은 크게 두가지가 있습니다. + +### 다중 컨테이너 + +만약 여러분이 **여러개의 컨테이너**를 가지고 있다면, 아마도 각각의 컨테이너는 **하나의 프로세스**를 가지고 있을 것입니다(예를 들어, **쿠버네티스** 클러스터에서). 그러면 여러분은 복제된 워커 컨테이너를 실행하기 **이전에**, 하나의 컨테이너에 있는 **이전의 단계들을** 수행하는 단일 프로세스를 가지는 **별도의 컨테이너들**을 가지고 싶을 것입니다. + +!!! info "정보" + 만약 여러분이 쿠버네티스를 사용하고 있다면, 아마도 이는 Init Container일 것입니다. + +만약 여러분의 이용 사례에서 이전 단계들을 **병렬적으로 여러번** 수행하는데에 문제가 없다면 (예를 들어 데이터베이스 이전을 실행하지 않고 데이터베이스가 준비되었는지 확인만 하는 경우), 메인 프로세스를 시작하기 전에 이 단계들을 각 컨테이너에 넣을 수 있습니다. + +### 단일 컨테이너 + +만약 여러분의 셋업이 **다중 프로세스**(또는 하나의 프로세스)를 시작하는 **하나의 컨테이너**를 가지는 단순한 셋업이라면, 사전 단계들을 앱을 포함하는 프로세스를 시작하기 직전에 같은 컨테이너에서 실행할 수 있습니다. 공식 도커 이미지는 이를 내부적으로 지원합니다. + +## Gunicorn과 함께하는 공식 도커 이미지 - Uvicorn + +앞 챕터에서 자세하게 설명된 것 처럼, Uvicorn 워커와 같이 실행되는 Gunicorn을 포함하는 공식 도커 이미지가 있습니다: [서버 워커 - Uvicorn과 함께하는 Gunicorn](./server-workers.md){.internal-link target=_blank}. + +이 이미지는 주로 위에서 설명된 상황에서 유용할 것입니다: [다중 프로세스를 가지는 컨테이너와 특수한 경우들](#containers-with-multiple-processes-and-special-cases). + +* tiangolo/uvicorn-gunicorn-fastapi. + +!!! warning "경고" + 여러분이 이 베이스 이미지 또는 다른 유사한 이미지를 필요로 하지 **않을** 높은 가능성이 있으며, [위에서 설명된 것처럼: FastAPI를 위한 도커 이미지 빌드하기](#build-a-docker-image-for-fastapi) 처음부터 이미지를 빌드하는 것이 더 나을 수 있습니다. + +이 이미지는 가능한 CPU 코어에 기반한 **몇개의 워커 프로세스**를 설정하는 **자동-튜닝** 메커니즘을 포함하고 있습니다. + +이 이미지는 **민감한 디폴트** 값을 가지고 있지만, 여러분들은 여전히 **환경 변수** 또는 설정 파일을 통해 설정값을 수정하고 업데이트 할 수 있습니다. + +또한 스크립트를 통해 **시작하기 전 사전 단계**를 실행하는 것을 지원합니다. + +!!! tip "팁" + 모든 설정과 옵션을 보려면, 도커 이미지 페이지로 이동합니다: tiangolo/uvicorn-gunicorn-fastapi. + +### 공식 도커 이미지에 있는 프로세스 개수 + +이 이미지에 있는 **프로세스 개수**는 가용한 CPU **코어들**로 부터 **자동으로 계산**됩니다. + +이것이 의미하는 바는 이미지가 CPU로부터 **최대한의 성능**을 **쥐어짜낸다**는 것입니다. + +여러분은 이 설정 값을 **환경 변수**나 기타 방법들로 조정할 수 있습니다. + +그러나 프로세스의 개수가 컨테이너가 실행되고 있는 CPU에 의존한다는 것은 또한 **소요되는 메모리의 크기** 또한 이에 의존한다는 것을 의미합니다. + +그렇기 때문에, 만약 여러분의 어플리케이션이 많은 메모리를 요구하고 (예를 들어 머신러닝 모델처럼), 여러분의 서버가 CPU 코어 수는 많지만 **적은 메모리**를 가지고 있다면, 여러분의 컨테이너는 가용한 메모리보다 많은 메모리를 사용하려고 시도할 수 있으며, 결국 퍼포먼스를 크게 떨어뜨릴 수 있습니다(심지어 고장이 날 수도 있습니다). 🚨 + +### `Dockerfile` 생성하기 + +이 이미지에 기반해 `Dockerfile`을 생성하는 방법은 다음과 같습니다: + +```Dockerfile +FROM tiangolo/uvicorn-gunicorn-fastapi:python3.9 + +COPY ./requirements.txt /app/requirements.txt + +RUN pip install --no-cache-dir --upgrade -r /app/requirements.txt + +COPY ./app /app +``` + +### 더 큰 어플리케이션 + +만약 여러분이 [다중 파일을 가지는 더 큰 어플리케이션](../tutorial/bigger-applications.md){.internal-link target=_blank}을 생성하는 섹션을 따랐다면, 여러분의 `Dockerfile`은 대신 이렇게 생겼을 것입니다: + +```Dockerfile hl_lines="7" +FROM tiangolo/uvicorn-gunicorn-fastapi:python3.9 + +COPY ./requirements.txt /app/requirements.txt + +RUN pip install --no-cache-dir --upgrade -r /app/requirements.txt + +COPY ./app /app/app +``` + +### 언제 사용할까 + +여러분들이 **쿠버네티스**(또는 유사한 다른 도구) 사용하거나 클러스터 레벨에서 다중 컨테이너를 이용해 이미 **사본**을 설정하고 있다면, 공식 베이스 이미지(또는 유사한 다른 이미지)를 사용하지 **않는** 것 좋습니다. 그런 경우에 여러분은 다음에 설명된 것 처럼 **처음부터 이미지를 빌드하는 것**이 더 낫습니다: [FastAPI를 위한 도커 이미지 빌드하기](#build-a-docker-image-for-fastapi). + +이 이미지는 위의 [다중 프로세스를 가지는 컨테이너와 특수한 경우들](#containers-with-multiple-processes-and-special-cases)에서 설명된 특수한 경우에 대해서만 주로 유용할 것입니다. 예를 들어, 만약 여러분의 어플리케이션이 **충분히 단순**해서 CPU에 기반한 디폴트 프로세스 개수를 설정하는 것이 잘 작동한다면, 클러스터 레벨에서 수동으로 사본을 설정할 필요가 없을 것이고, 여러분의 앱에서 하나 이상의 컨테이너를 실행하지도 않을 것입니다. 또는 만약에 여러분이 **도커 컴포즈**로 배포하거나, 단일 서버에서 실행하거나 하는 경우에도 마찬가지입니다. + +## 컨테이너 이미지 배포하기 + +컨테이너 (도커) 이미지를 완성한 뒤에 이를 배포하는 방법에는 여러가지 방법이 있습니다. + +예를 들어: + +* 단일 서버에서 **도커 컴포즈**로 배포하기 +* **쿠버네티스** 클러스터로 배포하기 +* 도커 스왐 모드 클러스터로 배포하기 +* 노마드 같은 다른 도구로 배포하기 +* 여러분의 컨테이너 이미지를 배포해주는 클라우드 서비스로 배포하기 + +## Poetry의 도커 이미지 + +만약 여러분들이 프로젝트 의존성을 관리하기 위해 Poetry를 사용한다면, 도커의 멀티-스테이지 빌딩을 사용할 수 있습니다: + +```{ .dockerfile .annotate } +# (1) +FROM python:3.9 as requirements-stage + +# (2) +WORKDIR /tmp + +# (3) +RUN pip install poetry + +# (4) +COPY ./pyproject.toml ./poetry.lock* /tmp/ + +# (5) +RUN poetry export -f requirements.txt --output requirements.txt --without-hashes + +# (6) +FROM python:3.9 + +# (7) +WORKDIR /code + +# (8) +COPY --from=requirements-stage /tmp/requirements.txt /code/requirements.txt + +# (9) +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt + +# (10) +COPY ./app /code/app + +# (11) +CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] +``` + +1. 첫 스테이지로, `requirements-stage`라고 이름 붙였습니다. + +2. `/tmp`를 현재의 워킹 디렉터리로 설정합니다. + + 이 위치에 우리는 `requirements.txt` 파일을 생성할 것입니다. + +3. 이 도커 스테이지에서 Poetry를 설치합니다. + +4. 파일 `pyproject.toml`와 `poetry.lock`를 `/tmp` 디렉터리로 복사합니다. + + `./poetry.lock*` (`*`로 끝나는) 파일을 사용하기 때문에, 파일이 아직 사용가능하지 않더라도 고장나지 않을 것입니다. + +5. `requirements.txt` 파일을 생성합니다. + +6. 이것이 마지막 스테이지로, 여기에 위치한 모든 것이 마지막 컨테이너 이미지에 포함될 것입니다. + +7. 현재의 워킹 디렉터리를 `/code`로 설정합니다. + +8. 파일 `requirements.txt`를 `/code` 디렉터리로 복사합니다. + + 이 파일은 오직 이전의 도커 스테이지에만 존재하며, 때문에 복사하기 위해서 `--from-requirements-stage` 옵션이 필요합니다. + +9. 생성된 `requirements.txt` 파일에 패키지 의존성을 설치합니다. + +10. `app` 디렉터리를 `/code` 디렉터리로 복사합니다. + +11. `uvicorn` 커맨드를 실행하여, `app.main`에서 불러온 `app` 객체를 사용하도록 합니다. + +!!! tip "팁" + 버블 숫자를 클릭해 각 줄이 하는 일을 알아볼 수 있습니다. + +**도커 스테이지**란 `Dockefile`의 일부로서 나중에 사용하기 위한 파일들을 생성하기 위한 **일시적인 컨테이너 이미지**로 작동합니다. + +첫 스테이지는 오직 **Poetry를 설치**하고 Poetry의 `pyproject.toml` 파일로부터 프로젝트 의존성을 위한 **`requirements.txt`를 생성**하기 위해 사용됩니다. + +이 `requirements.txt` 파일은 **다음 스테이지**에서 `pip`로 사용될 것입니다. + +마지막 컨테이너 이미지에는 **오직 마지막 스테이지만** 보존됩니다. 이전 스테이지(들)은 버려집니다. + +Poetry를 사용할 때 **도커 멀티-스테이지 빌드**를 사용하는 것이 좋은데, 여러분들의 프로젝트 의존성을 설치하기 위해 마지막 컨테이너 이미지에 **오직** `requirements.txt` 파일만 필요하지, Poetry와 그 의존성은 있을 필요가 없기 때문입니다. + +이 다음 (또한 마지막) 스테이지에서 여러분들은 이전에 설명된 것과 비슷한 방식으로 방식으로 이미지를 빌드할 수 있습니다. + +### TLS 종료 프록시의 배후 - Poetry + +이전에 언급한 것과 같이, 만약 여러분이 컨테이너를 Nginx 또는 Traefik과 같은 TLS 종료 프록시 (로드 밸런서) 뒤에서 실행하고 있다면, 커맨드에 `--proxy-headers` 옵션을 추가합니다: + +```Dockerfile +CMD ["uvicorn", "app.main:app", "--proxy-headers", "--host", "0.0.0.0", "--port", "80"] +``` + +## 요약 + +컨테이너 시스템(예를 들어 **도커**나 **쿠버네티스**)을 사용하여 모든 **배포 개념**을 다루는 것은 꽤 간단합니다: + +* HTTPS +* 구동하기 +* 재시작 +* 복제 (실행 중인 프로세스 개수) +* 메모리 +* 시작하기 전 단계들 + +대부분의 경우에서 여러분은 어떤 베이스 이미지도 사용하지 않고 공식 파이썬 도커 이미지에 기반해 **처음부터 컨테이너 이미지를 빌드**할 것입니다. + +`Dockerfile`에 있는 지시 사항을 **순서대로** 다루고 **도커 캐시**를 사용하는 것으로 여러분은 **빌드 시간을 최소화**할 수 있으며, 이로써 생산성을 최대화할 수 있습니다 (그리고 지루함을 피할 수 있죠) 😎 + +특별한 경우에는, FastAPI를 위한 공식 도커 이미지를 사용할 수도 있습니다. 🤓 diff --git a/docs/ko/docs/deployment/index.md b/docs/ko/docs/deployment/index.md new file mode 100644 index 0000000000000..87b05b68f1abd --- /dev/null +++ b/docs/ko/docs/deployment/index.md @@ -0,0 +1,21 @@ +# 배포하기 - 들어가면서 + +**FastAPI**을 배포하는 것은 비교적 쉽습니다. + +## 배포의 의미 + +**배포**란 애플리케이션을 **사용자가 사용**할 수 있도록 하는 데 필요한 단계를 수행하는 것을 의미합니다. + +**웹 API**의 경우, 일반적으로 **사용자**가 중단이나 오류 없이 애플리케이션에 효율적으로 **접근**할 수 있도록 좋은 성능, 안정성 등을 제공하는 **서버 프로그램과** 함께 **원격 시스템**에 이를 설치하는 작업을 의미합니다. + +이는 지속적으로 코드를 변경하고, 지우고, 수정하고, 개발 서버를 중지했다가 다시 시작하는 등의 **개발** 단계와 대조됩니다. + +## 배포 전략 + +사용하는 도구나 특정 사례에 따라 여러 가지 방법이 있습니다. + +배포도구들을 사용하여 직접 **서버에 배포**하거나, 배포작업의 일부를 수행하는 **클라우드 서비스** 또는 다른 방법을 사용할 수도 있습니다. + +**FastAPI** 애플리케이션을 배포할 때 선택할 수 있는 몇 가지 주요 방법을 보여 드리겠습니다 (대부분 다른 유형의 웹 애플리케이션에도 적용됩니다). + +다음 차례에 자세한 내용과 이를 위한 몇 가지 기술을 볼 수 있습니다. ✨ diff --git a/docs/ko/docs/deployment/server-workers.md b/docs/ko/docs/deployment/server-workers.md new file mode 100644 index 0000000000000..5653c55e3ba56 --- /dev/null +++ b/docs/ko/docs/deployment/server-workers.md @@ -0,0 +1,180 @@ +# 서버 워커 - 구니콘과 유비콘 + +전단계에서의 배포 개념들을 다시 확인해보겠습니다: + +* 보안 - HTTPS +* 서버 시작과 동시에 실행하기 +* 재시작 +* **복제본 (실행 중인 프로세스의 숫자)** +* 메모리 +* 시작하기 전의 여러 단계들 + +지금까지 문서의 모든 튜토리얼을 참고하여 **단일 프로세스**로 Uvicorn과 같은 **서버 프로그램**을 실행했을 것입니다. + +애플리케이션을 배포할 때 **다중 코어**를 활용하고 더 많은 요청을 처리할 수 있도록 **프로세스 복제본**이 필요합니다. + +전 과정이었던 [배포 개념들](./concepts.md){.internal-link target=_blank}에서 본 것처럼 여러가지 방법이 존재합니다. + +지금부터 **구니콘**을 **유비콘 워커 프로세스**와 함께 사용하는 방법을 알려드리겠습니다. + +!!! 정보 + 만약 도커와 쿠버네티스 같은 컨테이너를 사용하고 있다면 다음 챕터 [FastAPI와 컨테이너 - 도커](./docker.md){.internal-link target=_blank}에서 더 많은 정보를 얻을 수 있습니다. + + 특히, 쿠버네티스에서 실행할 때는 구니콘을 사용하지 않고 대신 컨테이너당 하나의 유비콘 프로세스를 실행하는 것이 좋습니다. 이 장의 뒷부분에서 설명하겠습니다. + +## 구니콘과 유비콘 워커 + +**Gunicorn**은 **WSGI 표준**을 주로 사용하는 애플리케이션 서버입니다. 이것은 구니콘이 플라스크와 쟝고와 같은 애플리케이션을 제공할 수 있다는 것을 의미합니다. 구니콘 자체는 최신 **ASGI 표준**을 사용하기 때문에 FastAPI와 호환되지 않습니다. + +하지만 구니콘은 **프로세스 관리자**역할을 하고 사용자에게 특정 **워커 프로세스 클래스**를 알려줍니다. 그런 다음 구니콘은 해당 클래스를 사용하여 하나 이상의 **워커 프로세스**를 시작합니다. + +그리고 **유비콘**은 **구니콘과 호환되는 워커 클래스**가 있습니다. + +이 조합을 사용하여 구니콘은 **프로세스 관리자** 역할을 하며 **포트**와 **IP**를 관찰하고, **유비콘 클래스**를 실행하는 워커 프로세스로 통신 정보를 **전송**합니다. + +그리고 나서 구니콘과 호환되는 **유비콘 워커** 클래스는 구니콘이 보낸 데이터를 FastAPI에서 사용하기 위한 ASGI 표준으로 변환하는 일을 담당합니다. + +## 구니콘과 유비콘 설치하기 + +
+ +```console +$ pip install "uvicorn[standard]" gunicorn + +---> 100% +``` + +
+ +이 명령어는 유비콘 `standard` 추가 패키지(좋은 성능을 위한)와 구니콘을 설치할 것입니다. + +## 구니콘을 유비콘 워커와 함께 실행하기 + +설치 후 구니콘 실행하기: + +
+ +```console +$ gunicorn main:app --workers 4 --worker-class uvicorn.workers.UvicornWorker --bind 0.0.0.0:80 + +[19499] [INFO] Starting gunicorn 20.1.0 +[19499] [INFO] Listening at: http://0.0.0.0:80 (19499) +[19499] [INFO] Using worker: uvicorn.workers.UvicornWorker +[19511] [INFO] Booting worker with pid: 19511 +[19513] [INFO] Booting worker with pid: 19513 +[19514] [INFO] Booting worker with pid: 19514 +[19515] [INFO] Booting worker with pid: 19515 +[19511] [INFO] Started server process [19511] +[19511] [INFO] Waiting for application startup. +[19511] [INFO] Application startup complete. +[19513] [INFO] Started server process [19513] +[19513] [INFO] Waiting for application startup. +[19513] [INFO] Application startup complete. +[19514] [INFO] Started server process [19514] +[19514] [INFO] Waiting for application startup. +[19514] [INFO] Application startup complete. +[19515] [INFO] Started server process [19515] +[19515] [INFO] Waiting for application startup. +[19515] [INFO] Application startup complete. +``` + +
+ +각 옵션이 무엇을 의미하는지 살펴봅시다: + +* 이것은 유비콘과 똑같은 문법입니다. `main`은 파이썬 모듈 네임 "`main`"을 의미하므로 `main.py`파일을 뜻합니다. 그리고 `app`은 **FastAPI** 어플리케이션이 들어 있는 변수의 이름입니다. + * `main:app`이 파이썬의 `import` 문법과 흡사한 면이 있다는 걸 알 수 있습니다: + + ```Python + from main import app + ``` + + * 곧, `main:app`안에 있는 콜론의 의미는 파이썬에서 `from main import app`에서의 `import`와 같습니다. +* `--workers`: 사용할 워커 프로세스의 개수이며 숫자만큼의 유비콘 워커를 실행합니다. 이 예제에서는 4개의 워커를 실행합니다. +* `--worker-class`: 워커 프로세스에서 사용하기 위한 구니콘과 호환되는 워커클래스. + * 이런식으로 구니콘이 import하여 사용할 수 있는 클래스를 전달해줍니다: + + ```Python + import uvicorn.workers.UvicornWorker + ``` + +* `--bind`: 구니콘이 관찰할 IP와 포트를 의미합니다. 콜론 (`:`)을 사용하여 IP와 포트를 구분합니다. + * 만약에 `--bind 0.0.0.0:80` (구니콘 옵션) 대신 유비콘을 직접 실행하고 싶다면 `--host 0.0.0.0`과 `--port 80`을 사용해야 합니다. + +출력에서 각 프로세스에 대한 **PID** (process ID)를 확인할 수 있습니다. (단순한 숫자입니다) + +출력 내용: + +* 구니콘 **프로세스 매니저**는 PID `19499`로 실행됩니다. (직접 실행할 경우 숫자가 다를 수 있습니다) +* 다음으로 `Listening at: http://0.0.0.0:80`을 시작합니다. +* 그런 다음 사용해야할 `uvicorn.workers.UvicornWorker`의 워커클래스를 탐지합니다. +* 그리고 PID `19511`, `19513`, `19514`, 그리고 `19515`를 가진 **4개의 워커**를 실행합니다. + + +또한 구니콘은 워커의 수를 유지하기 위해 **죽은 프로세스**를 관리하고 **재시작**하는 작업을 책임집니다. 이것은 이번 장 상단 목록의 **재시작** 개념을 부분적으로 도와주는 것입니다. + +그럼에도 불구하고 필요할 경우 외부에서 **구니콘을 재시작**하고, 혹은 **서버를 시작할 때 실행**할 수 있도록 하고 싶어할 것입니다. + +## 유비콘과 워커 + +유비콘은 몇 개의 **워커 프로세스**와 함께 실행할 수 있는 선택지가 있습니다. + +그럼에도 불구하고, 유비콘은 워커 프로세스를 다루는 데에 있어서 구니콘보다 더 제한적입니다. 따라서 이 수준(파이썬 수준)의 프로세스 관리자를 사용하려면 구니콘을 프로세스 관리자로 사용하는 것이 좋습니다. + +보통 이렇게 실행할 수 있습니다: + +
+ +```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. +``` + +
+ +새로운 옵션인 `--workers`은 유비콘에게 4개의 워커 프로세스를 사용한다고 알려줍니다. + +각 프로세스의 **PID**를 확인할 수 있습니다. `27365`는 상위 프로세스(**프로세스 매니저**), 그리고 각각의 워커프로세스는 `27368`, `27369`, `27370`, 그리고 `27367`입니다. + +## 배포 개념들 + +여기에서는 **유비콘 워커 프로세스**를 관리하는 **구니콘**(또는 유비콘)을 사용하여 애플리케이션을 **병렬화**하고, CPU **멀티 코어**의 장점을 활용하고, **더 많은 요청**을 처리할 수 있는 방법을 살펴보았습니다. + +워커를 사용하는 것은 배포 개념 목록에서 주로 **복제본** 부분과 **재시작**에 약간 도움이 되지만 다른 배포 개념들도 다루어야 합니다: + +* **보안 - HTTPS** +* **서버 시작과 동시에 실행하기** +* ***재시작*** +* 복제본 (실행 중인 프로세스의 숫자) +* **메모리** +* **시작하기 전의 여러 단계들** + + +## 컨테이너와 도커 + +다음 장인 [FastAPI와 컨테이너 - 도커](./docker.md){.internal-link target=_blank}에서 다른 **배포 개념들**을 다루는 전략들을 알려드리겠습니다. + +또한 간단한 케이스에서 사용할 수 있는, **구니콘과 유비콘 워커**가 포함돼 있는 **공식 도커 이미지**와 함께 몇 가지 기본 구성을 보여드리겠습니다. + +그리고 단일 유비콘 프로세스(구니콘 없이)를 실행할 수 있도록 **사용자 자신의 이미지를 처음부터 구축**하는 방법도 보여드리겠습니다. 이는 간단한 과정이며, **쿠버네티스**와 같은 분산 컨테이너 관리 시스템을 사용할 때 수행할 작업입니다. + +## 요약 + +당신은 **구니콘**(또는 유비콘)을 유비콘 워커와 함께 프로세스 관리자로 사용하여 **멀티-코어 CPU**를 활용하는 **멀티 프로세스를 병렬로 실행**할 수 있습니다. + +다른 배포 개념을 직접 다루면서 **자신만의 배포 시스템**을 구성하는 경우 이러한 도구와 개념들을 활용할 수 있습니다. + +다음 장에서 컨테이너(예: 도커 및 쿠버네티스)와 함께하는 **FastAPI**에 대해 배워보세요. 이러한 툴에는 다른 **배포 개념**들을 간단히 해결할 수 있는 방법이 있습니다. ✨ diff --git a/docs/ko/docs/features.md b/docs/ko/docs/features.md new file mode 100644 index 0000000000000..54479165e8e0a --- /dev/null +++ b/docs/ko/docs/features.md @@ -0,0 +1,203 @@ +--- +hide: + - navigation +--- + +# 기능 + +## FastAPI의 기능 + +**FastAPI**는 다음과 같은 기능을 제공합니다: + +### 개방형 표준을 기반으로 + +* 경로작동, 매개변수, 본문 요청, 보안 그 외의 선언을 포함한 API 생성을 위한 OpenAPI +* JSON Schema (OpenAPI 자체가 JSON Schema를 기반으로 하고 있습니다)를 사용한 자동 데이터 모델 문서화. +* 단순히 떠올려서 덧붙인 기능이 아닙니다. 세심한 검토를 거친 후, 이러한 표준을 기반으로 설계되었습니다. +* 이는 또한 다양한 언어로 자동적인 **클라이언트 코드 생성**을 사용할 수 있게 지원합니다. + +### 문서 자동화 + +대화형 API 문서와 웹 탐색 유저 인터페이스를 제공합니다. 프레임워크가 OpenAPI를 기반으로 하기에, 2가지 옵션이 기본적으로 들어간 여러 옵션이 존재합니다. + +* 대화형 탐색 Swagger UI를 이용해, 브라우저에서 바로 여러분의 API를 호출하거나 테스트할 수 있습니다. + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) + +* ReDoc을 이용해 API 문서화를 대체할 수 있습니다. + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) + +### 그저 현대 파이썬 + +(Pydantic 덕분에) FastAPI는 표준 **파이썬 3.6 타입** 선언에 기반하고 있습니다. 새로 배울 문법이 없습니다. 그저 표준적인 현대 파이썬입니다. + +만약 여러분이 파이썬 타입을 어떻게 사용하는지에 대한 2분 정도의 복습이 필요하다면 (비록 여러분이 FastAPI를 사용하지 않는다 하더라도), 다음의 짧은 자습서를 확인하세요: [파이썬 타입](python-types.md){.internal-link target=\_blank}. + +여러분은 타입을 이용한 표준 파이썬을 다음과 같이 적을 수 있습니다: + +```Python +from datetime import date + +from pydantic import BaseModel + +# 변수를 str로 선언 +# 그 후 함수 안에서 편집기 지원을 받으세요 +def main(user_id: str): + return user_id + + +# Pydantic 모델 +class User(BaseModel): + id: int + name: str + joined: date +``` + +위의 코드는 다음과 같이 사용될 수 있습니다: + +```Python +my_user: User = User(id=3, name="John Doe", joined="2018-07-19") + +second_user_data = { + "id": 4, + "name": "Mary", + "joined": "2018-11-30", +} + +my_second_user: User = User(**second_user_data) +``` + +!!! 정보 + `**second_user_data`가 뜻하는 것: + + `second_user_data` 딕셔너리의 키와 값을 키-값 인자로서 바로 넘겨줍니다. 다음과 동일합니다: `User(id=4, name="Mary", joined="2018-11-30")` + +### 편집기 지원 + +모든 프레임워크는 사용하기 쉽고 직관적으로 설계되었으며, 좋은 개발 경험을 보장하기 위해 개발을 시작하기도 전에 모든 결정들은 여러 편집기에서 테스트됩니다. + +최근 파이썬 개발자 설문조사에서 "자동 완성"이 가장 많이 사용되는 기능이라는 것이 밝혀졌습니다. + +**FastAPI** 프레임워크의 모든 부분은 이를 충족하기 위해 설계되었습니다. 자동완성은 어느 곳에서나 작동합니다. + +여러분은 문서로 다시 돌아올 일이 거의 없을 겁니다. + +다음은 편집기가 어떻게 여러분을 도와주는지 보여줍니다: + +* Visual Studio Code에서: + +![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) + +* PyCharm에서: + +![editor support](https://fastapi.tiangolo.com/img/pycharm-completion.png) + +여러분이 이전에 불가능하다고 고려했던 코드도 완성할 수 있을 겁니다. 예를 들어, 요청에서 전달되는 (중첩될 수도 있는)JSON 본문 내부에 있는 `price` 키입니다. + +잘못된 키 이름을 적을 일도, 문서를 왔다 갔다할 일도 없으며, 혹은 마지막으로 `username` 또는 `user_name`을 사용했는지 찾기 위해 위 아래로 스크롤할 일도 없습니다. + +### 토막 정보 + +어느 곳에서나 선택적 구성이 가능한 모든 것에 합리적인 기본값이 설정되어 있습니다. 모든 매개변수는 여러분이 필요하거나, 원하는 API를 정의하기 위해 미세하게 조정할 수 있습니다. + +하지만 기본적으로 모든 것이 "그냥 작동합니다". + +### 검증 + +* 다음을 포함한, 대부분의 (혹은 모든?) 파이썬 **데이터 타입** 검증할 수 있습니다: + * JSON 객체 (`dict`). + * 아이템 타입을 정의하는 JSON 배열 (`list`). + * 최소 길이와 최대 길이를 정의하는 문자열 (`str`) 필드. + * 최솟값과 최댓값을 가지는 숫자 (`int`, `float`), 그 외. + +* 다음과 같이 더욱 이색적인 타입에 대해 검증할 수 있습니다: + * URL. + * 이메일. + * UUID. + * ...다른 것들. + +모든 검증은 견고하면서 잘 확립된 **Pydantic**에 의해 처리됩니다. + +### 보안과 인증 + +보안과 인증이 통합되어 있습니다. 데이터베이스나 데이터 모델과의 타협없이 사용할 수 있습니다. + +다음을 포함하는, 모든 보안 스키마가 OpenAPI에 정의되어 있습니다. + +* HTTP Basic. +* **OAuth2** (**JWT tokens** 또한 포함). [OAuth2 with JWT](tutorial/security/oauth2-jwt.md){.internal-link target=\_blank}에 있는 자습서를 확인해 보세요. +* 다음에 들어 있는 API 키: + * 헤더. + * 매개변수. + * 쿠키 및 그 외. + +추가적으로 (**세션 쿠키**를 포함한) 모든 보안 기능은 Starlette에 있습니다. + +모두 재사용할 수 있는 도구와 컴포넌트로 만들어져 있어 여러분의 시스템, 데이터 저장소, 관계형 및 NoSQL 데이터베이스 등과 쉽게 통합할 수 있습니다. + +### 의존성 주입 + +FastAPI는 사용하기 매우 간편하지만, 엄청난 의존성 주입시스템을 포함하고 있습니다. + +* 의존성은 의존성을 가질수도 있어, 이를 통해 의존성의 계층이나 **의존성의 "그래프"**를 형성합니다. +* 모든 것이 프레임워크에 의해 **자동적으로 처리됩니다**. +* 모든 의존성은 요청에서 데이터를 요구하여 자동 문서화와 **경로 작동 제약을 강화할 수 있습니다**. +* 의존성에서 정의된 _경로 작동_ 매개변수에 대해서도 **자동 검증**이 이루어 집니다. +* 복잡한 사용자의 인증 시스템, **데이터베이스 연결**, 등등을 지원합니다. +* 데이터베이스, 프론트엔드 등과 관련되어 **타협하지 않아도 됩니다**. 하지만 그 모든 것과 쉽게 통합이 가능합니다. + +### 제한 없는 "플러그인" + +또는 다른 방법으로, 그것들을 사용할 필요 없이 필요한 코드만 임포트할 수 있습니다. + +어느 통합도 (의존성과 함께) 사용하기 쉽게 설계되어 있어, *경로 작동*에 사용된 것과 동일한 구조와 문법을 사용하여 2줄의 코드로 여러분의 어플리케이션에 사용할 "플러그인"을 만들 수 있습니다. + +### 테스트 결과 + +* 100% 테스트 범위. +* 100% 타입이 명시된 코드 베이스. +* 상용 어플리케이션에서의 사용. + +## Starlette 기능 + +**FastAPI**는 Starlette를 기반으로 구축되었으며, 이와 완전히 호환됩니다. 따라서, 여러분이 보유하고 있는 어떤 추가적인 Starlette 코드도 작동할 것입니다. + +`FastAPI`는 실제로 `Starlette`의 하위 클래스입니다. 그래서, 여러분이 이미 Starlette을 알고 있거나 사용하고 있으면, 대부분의 기능이 같은 방식으로 작동할 것입니다. + +**FastAPI**를 사용하면 여러분은 **Starlette**의 기능 대부분을 얻게 될 것입니다(FastAPI가 단순히 Starlette를 강화했기 때문입니다): + +* 아주 인상적인 성능. 이는 **NodeJS**와 **Go**와 동등하게 사용 가능한 가장 빠른 파이썬 프레임워크 중 하나입니다. +* **WebSocket** 지원. +* 프로세스 내의 백그라운드 작업. +* 시작과 종료 이벤트. +* HTTPX 기반 테스트 클라이언트. +* **CORS**, GZip, 정적 파일, 스트리밍 응답. +* **세션과 쿠키** 지원. +* 100% 테스트 범위. +* 100% 타입이 명시된 코드 베이스. + +## Pydantic 기능 + +**FastAPI**는 Pydantic을 기반으로 하며 Pydantic과 완벽하게 호환됩니다. 그래서 어느 추가적인 Pydantic 코드를 여러분이 가지고 있든 작동할 것입니다. + +Pydantic을 기반으로 하는, 데이터베이스를 위한 ORM, ODM을 포함한 외부 라이브러리를 포함합니다. + +이는 모든 것이 자동으로 검증되기 때문에, 많은 경우에서 요청을 통해 얻은 동일한 객체를, **직접 데이터베이스로** 넘겨줄 수 있습니다. + +반대로도 마찬가지이며, 많은 경우에서 여러분은 **직접 클라이언트로** 그저 객체를 넘겨줄 수 있습니다. + +**FastAPI**를 사용하면 (모든 데이터 처리를 위해 FastAPI가 Pydantic을 기반으로 하기 있기에) **Pydantic**의 모든 기능을 얻게 됩니다: + +* **어렵지 않은 언어**: + * 새로운 스키마 정의 마이크로 언어를 배우지 않아도 됩니다. + * 여러분이 파이썬 타입을 안다면, 여러분은 Pydantic을 어떻게 사용하는지 아는 겁니다. +* 여러분의 **IDE/린터/뇌**와 잘 어울립니다: + * Pydantic 데이터 구조는 단순 여러분이 정의한 클래스의 인스턴스이기 때문에, 자동 완성, 린팅, mypy 그리고 여러분의 직관까지 여러분의 검증된 데이터와 올바르게 작동합니다. +* **복잡한 구조**를 검증합니다: + * 계층적인 Pydantic 모델, 파이썬 `typing`의 `List`와 `Dict`, 그 외를 사용합니다. + * 그리고 검증자는 복잡한 데이터 스키마를 명확하고 쉽게 정의 및 확인하며 JSON 스키마로 문서화합니다. + * 여러분은 깊게 **중첩된 JSON** 객체를 가질 수 있으며, 이 객체 모두 검증하고 설명을 붙일 수 있습니다. +* **확장 가능성**: + * Pydantic은 사용자 정의 데이터 타입을 정의할 수 있게 하거나, 검증자 데코레이터가 붙은 모델의 메소드를 사용하여 검증을 확장할 수 있습니다. +* 100% 테스트 범위. diff --git a/docs/ko/docs/help/index.md b/docs/ko/docs/help/index.md new file mode 100644 index 0000000000000..fc023071ac9c0 --- /dev/null +++ b/docs/ko/docs/help/index.md @@ -0,0 +1,3 @@ +# 도움 + +도움을 주고 받고, 기여하고, 참여합니다. 🤝 diff --git a/docs/ko/docs/index.md b/docs/ko/docs/index.md index a6991a9b86737..eeadc0363cd97 100644 --- a/docs/ko/docs/index.md +++ b/docs/ko/docs/index.md @@ -24,7 +24,7 @@ --- -FastAPI는 현대적이고, 빠르며(고성능), 파이썬 표준 타입 힌트에 기초한 Python3.6+의 API를 빌드하기 위한 웹 프레임워크입니다. +FastAPI는 현대적이고, 빠르며(고성능), 파이썬 표준 타입 힌트에 기초한 Python3.8+의 API를 빌드하기 위한 웹 프레임워크입니다. 주요 특징으로: @@ -107,12 +107,12 @@ FastAPI는 현대적이고, 빠르며(고성능), 파이썬 표준 타입 힌트 ## 요구사항 -Python 3.7+ +Python 3.8+ FastAPI는 거인들의 어깨 위에 서 있습니다: * 웹 부분을 위한 Starlette. -* 데이터 부분을 위한 Pydantic. +* 데이터 부분을 위한 Pydantic. ## 설치 @@ -323,7 +323,7 @@ def update_item(item_id: int, item: Item): 새로운 문법, 특정 라이브러리의 메소드나 클래스 등을 배울 필요가 없습니다. -그저 표준 **Python 3.6+**입니다. +그저 표준 **Python 3.8+** 입니다. 예를 들어, `int`에 대해선: @@ -386,7 +386,7 @@ item: Item --- -우리는 그저 수박 겉핡기만 했을 뿐인데 여러분은 벌써 어떻게 작동하는지 알고 있습니다. +우리는 그저 수박 겉 핥기만 했을 뿐인데 여러분은 벌써 어떻게 작동하는지 알고 있습니다. 다음 줄을 바꿔보십시오: @@ -443,7 +443,7 @@ Starlette이 사용하는: * HTTPX - `TestClient`를 사용하려면 필요. * jinja2 - 기본 템플릿 설정을 사용하려면 필요. -* python-multipart - `request.form()`과 함께 "parsing"의 지원을 원하면 필요. +* python-multipart - `request.form()`과 함께 "parsing"의 지원을 원하면 필요. * itsdangerous - `SessionMiddleware` 지원을 위해 필요. * pyyaml - Starlette의 `SchemaGenerator` 지원을 위해 필요 (FastAPI와 쓸때는 필요 없을 것입니다). * graphene - `GraphQLApp` 지원을 위해 필요. diff --git a/docs/ko/docs/learn/index.md b/docs/ko/docs/learn/index.md new file mode 100644 index 0000000000000..7ac3a99b647ab --- /dev/null +++ b/docs/ko/docs/learn/index.md @@ -0,0 +1,5 @@ +# 배우기 + +여기 **FastAPI**를 배우기 위한 입문 자료와 자습서가 있습니다. + +여러분은 FastAPI를 배우기 위해 **책**, **강의**, **공식 자료** 그리고 추천받은 방법을 고려할 수 있습니다. 😎 diff --git a/docs/ko/docs/python-types.md b/docs/ko/docs/python-types.md new file mode 100644 index 0000000000000..267ce6c7e3b93 --- /dev/null +++ b/docs/ko/docs/python-types.md @@ -0,0 +1,315 @@ +# 파이썬 타입 소개 + +파이썬은 선택적으로 "타입 힌트(type hints)"를 지원합니다. + +이러한 **타입 힌트**들은 변수의 타입을 선언할 수 있게 해주는 특수한 구문입니다. + +변수의 타입을 지정하면 에디터와 툴이 더 많은 도움을 줄 수 있게 됩니다. + +이 문서는 파이썬 타입 힌트에 대한 **빠른 자습서 / 내용환기** 수준의 문서입니다. 여기서는 **FastAPI**를 쓰기 위한 최소한의 내용만을 다룹니다. + +**FastAPI**는 타입 힌트에 기반을 두고 있으며, 이는 많은 장점과 이익이 있습니다. + +비록 **FastAPI**를 쓰지 않는다고 하더라도, 조금이라도 알아두면 도움이 될 것입니다. + +!!! note "참고" + 파이썬에 능숙하셔서 타입 힌트에 대해 모두 아신다면, 다음 챕터로 건너뛰세요. + +## 동기 부여 + +간단한 예제부터 시작해봅시다: + +```Python +{!../../../docs_src/python_types/tutorial001.py!} +``` + +이 프로그램을 실행한 결과값: + +``` +John Doe +``` + +함수는 아래와 같이 실행됩니다: + +* `first_name`과 `last_name`를 받습니다. +* `title()`로 각 첫 문자를 대문자로 변환시킵니다. +* 두 단어를 중간에 공백을 두고 연결합니다. + +```Python hl_lines="2" +{!../../../docs_src/python_types/tutorial001.py!} +``` + +### 코드 수정 + +이건 매우 간단한 프로그램입니다. + +그런데 처음부터 작성한다고 생각을 해봅시다. + +여러분은 매개변수를 준비했고, 함수를 정의하기 시작했을 겁니다. + +이때 "첫 글자를 대문자로 바꾸는 함수"를 호출해야 합니다. + +`upper`였나? 아니면 `uppercase`? `first_uppercase`? `capitalize`? + +그때 개발자들의 오랜 친구, 에디터 자동완성을 시도해봅니다. + +당신은 `first_name`를 입력한 뒤 점(`.`)을 입력하고 자동완성을 켜기 위해서 `Ctrl+Space`를 눌렀습니다. + +하지만 슬프게도 아무런 도움이 되지 않습니다: + + + +### 타입 추가하기 + +이전 버전에서 한 줄만 수정해봅시다. + +저희는 이 함수의 매개변수 부분: + +```Python + first_name, last_name +``` + +을 아래와 같이 바꿀 겁니다: + +```Python + first_name: str, last_name: str +``` + +이게 다입니다. + +이게 "타입 힌트"입니다: + +```Python hl_lines="1" +{!../../../docs_src/python_types/tutorial002.py!} +``` + +타입힌트는 다음과 같이 기본 값을 선언하는 것과는 다릅니다: + +```Python + first_name="john", last_name="doe" +``` + +이는 다른 것입니다. + +등호(`=`) 대신 콜론(`:`)을 쓰고 있습니다. + +일반적으로 타입힌트를 추가한다고 해서 특별하게 어떤 일이 일어나지도 않습니다. + +그렇지만 이제, 다시 함수를 만드는 도중이라고 생각해봅시다. 다만 이번엔 타입 힌트가 있습니다. + +같은 상황에서 `Ctrl+Space`로 자동완성을 작동시키면, + + + +아래와 같이 "그렇지!"하는 옵션이 나올때까지 스크롤을 내려서 볼 수 있습니다: + + + +## 더 큰 동기부여 + +아래 함수를 보면, 이미 타입 힌트가 적용되어 있는 걸 볼 수 있습니다: + +```Python hl_lines="1" +{!../../../docs_src/python_types/tutorial003.py!} +``` + +편집기가 변수의 타입을 알고 있기 때문에, 자동완성 뿐 아니라 에러도 확인할 수 있습니다: + + + +이제 고쳐야하는 걸 알기 때문에, `age`를 `str(age)`과 같이 문자열로 바꾸게 됩니다: + +```Python hl_lines="2" +{!../../../docs_src/python_types/tutorial004.py!} +``` + +## 타입 선언 + +방금 함수의 매개변수로써 타입 힌트를 선언하는 주요 장소를 보았습니다. + +이 위치는 여러분이 **FastAPI**와 함께 이를 사용하는 주요 장소입니다. + +### Simple 타입 + +`str`뿐 아니라 모든 파이썬 표준 타입을 선언할 수 있습니다. + +예를 들면: + +* `int` +* `float` +* `bool` +* `bytes` + +```Python hl_lines="1" +{!../../../docs_src/python_types/tutorial005.py!} +``` + +### 타입 매개변수를 활용한 Generic(제네릭) 타입 + +`dict`, `list`, `set`, `tuple`과 같은 값을 저장할 수 있는 데이터 구조가 있고, 내부의 값은 각자의 타입을 가질 수도 있습니다. + +타입과 내부 타입을 선언하기 위해서는 파이썬 표준 모듈인 `typing`을 이용해야 합니다. + +구체적으로는 아래 타입 힌트를 지원합니다. + +#### `List` + +예를 들면, `str`의 `list`인 변수를 정의해봅시다. + +`typing`에서 `List`(대문자 `L`)를 import 합니다. + +```Python hl_lines="1" +{!../../../docs_src/python_types/tutorial006.py!} +``` + +콜론(`:`) 문법을 이용하여 변수를 선언합니다. + +타입으로는 `List`를 넣어줍니다. + +이때 배열은 내부 타입을 포함하는 타입이기 때문에 대괄호 안에 넣어줍니다. + +```Python hl_lines="4" +{!../../../docs_src/python_types/tutorial006.py!} +``` + +!!! tip "팁" + 대괄호 안의 내부 타입은 "타입 매개변수(type paramters)"라고 합니다. + + 이번 예제에서는 `str`이 `List`에 들어간 타입 매개변수 입니다. + +이는 "`items`은 `list`인데, 배열에 들어있는 아이템 각각은 `str`이다"라는 뜻입니다. + +이렇게 함으로써, 에디터는 배열에 들어있는 아이템을 처리할때도 도움을 줄 수 있게 됩니다: + + + +타입이 없으면 이건 거의 불가능이나 다름 없습니다. + +변수 `item`은 `items`의 개별 요소라는 사실을 알아두세요. + +그리고 에디터는 계속 `str`라는 사실을 알고 도와줍니다. + +#### `Tuple`과 `Set` + +`tuple`과 `set`도 동일하게 선언할 수 있습니다. + +```Python hl_lines="1 4" +{!../../../docs_src/python_types/tutorial007.py!} +``` + +이 뜻은 아래와 같습니다: + +* 변수 `items_t`는, 차례대로 `int`, `int`, `str`인 `tuple`이다. +* 변수 `items_s`는, 각 아이템이 `bytes`인 `set`이다. + +#### `Dict` + +`dict`를 선언하려면 컴마로 구분된 2개의 파라미터가 필요합니다. + +첫 번째 매개변수는 `dict`의 키(key)이고, + +두 번째 매개변수는 `dict`의 값(value)입니다. + +```Python hl_lines="1 4" +{!../../../docs_src/python_types/tutorial008.py!} +``` + +이 뜻은 아래와 같습니다: + +* 변수 `prices`는 `dict`이다: + * `dict`의 키(key)는 `str`타입이다. (각 아이템의 이름(name)) + * `dict`의 값(value)는 `float`타입이다. (각 아이템의 가격(price)) + +#### `Optional` + +`str`과 같이 타입을 선언할 때 `Optional`을 쓸 수도 있는데, "선택적(Optional)"이기때문에 `None`도 될 수 있습니다: + +```Python hl_lines="1 4" +{!../../../docs_src/python_types/tutorial009.py!} +``` + +`Optional[str]`을 `str` 대신 쓰게 되면, 특정 값이 실제로는 `None`이 될 수도 있는데 항상 `str`이라고 가정하는 상황에서 에디터가 에러를 찾게 도와줄 수 있습니다. + +#### Generic(제네릭) 타입 + +이 타입은 대괄호 안에 매개변수를 가지며, 종류는: + +* `List` +* `Tuple` +* `Set` +* `Dict` +* `Optional` +* ...등등 + +위와 같은 타입은 **Generic(제네릭) 타입** 혹은 **Generics(제네릭스)**라고 불립니다. + +### 타입으로서의 클래스 + +변수의 타입으로 클래스를 선언할 수도 있습니다. + +이름(name)을 가진 `Person` 클래스가 있다고 해봅시다. + +```Python hl_lines="1-3" +{!../../../docs_src/python_types/tutorial010.py!} +``` + +그렇게 하면 변수를 `Person`이라고 선언할 수 있게 됩니다. + +```Python hl_lines="6" +{!../../../docs_src/python_types/tutorial010.py!} +``` + +그리고 역시나 모든 에디터 도움을 받게 되겠죠. + + + +## Pydantic 모델 + +Pydantic은 데이터 검증(Validation)을 위한 파이썬 라이브러리입니다. + +당신은 속성들을 포함한 클래스 형태로 "모양(shape)"을 선언할 수 있습니다. + +그리고 각 속성은 타입을 가지고 있습니다. + +이 클래스를 활용하여서 값을 가지고 있는 인스턴스를 만들게 되면, 필요한 경우에는 적당한 타입으로 변환까지 시키기도 하여 데이터가 포함된 객체를 반환합니다. + +그리고 결과 객체에 대해서는 에디터의 도움을 받을 수 있게 됩니다. + +Pydantic 공식 문서 예시: + +```Python +{!../../../docs_src/python_types/tutorial011.py!} +``` + +!!! info "정보" + Pydantic<에 대해 더 배우고 싶다면 공식 문서를 참고하세요. + + +**FastAPI**는 모두 Pydantic을 기반으로 되어 있습니다. + +이 모든 것이 실제로 어떻게 사용되는지에 대해서는 [자습서 - 사용자 안내서](tutorial/index.md){.internal-link target=_blank} 에서 더 많이 확인하실 수 있습니다. + +## **FastAPI**에서의 타입 힌트 + +**FastAPI**는 여러 부분에서 타입 힌트의 장점을 취하고 있습니다. + +**FastAPI**에서 타입 힌트와 함께 매개변수를 선언하면 장점은: + +* **에디터 도움**. +* **타입 확인**. + +...그리고 **FastAPI**는 같은 정의를 아래에도 적용합니다: + +* **요구사항 정의**: 요청 경로 매개변수, 쿼리 매개변수, 헤더, 바디, 의존성 등. +* **데이터 변환**: 요청에서 요구한 타입으로. +* **데이터 검증**: 각 요청마다: + * 데이터가 유효하지 않은 경우에는 **자동으로 에러**를 발생합니다. +* OpenAPI를 활용한 **API 문서화**: + * 자동으로 상호작용하는 유저 인터페이스에 쓰이게 됩니다. + +위 내용이 다소 추상적일 수도 있지만, 걱정마세요. [자습서 - 사용자 안내서](tutorial/index.md){.internal-link target=_blank}에서 전부 확인 가능합니다. + +가장 중요한 건, 표준 파이썬 타입을 한 곳에서(클래스를 더하거나, 데코레이터 사용하는 대신) 사용함으로써 **FastAPI**가 당신을 위해 많은 일을 해준다는 사실이죠. + +!!! info "정보" + 만약 모든 자습서를 다 보았음에도 타입에 대해서 더 보고자 방문한 경우에는 `mypy`에서 제공하는 "cheat sheet"이 좋은 자료가 될 겁니다. diff --git a/docs/ko/docs/tutorial/background-tasks.md b/docs/ko/docs/tutorial/background-tasks.md new file mode 100644 index 0000000000000..ee83d6570f058 --- /dev/null +++ b/docs/ko/docs/tutorial/background-tasks.md @@ -0,0 +1,102 @@ +# 백그라운드 작업 + +FastAPI에서는 응답을 반환한 후에 실행할 백그라운드 작업을 정의할 수 있습니다. + +백그라운드 작업은 클라이언트가 응답을 받기 위해 작업이 완료될 때까지 기다릴 필요가 없기 때문에 요청 후에 발생해야하는 작업에 매우 유용합니다. + +이러한 작업에는 다음이 포함됩니다. + +* 작업을 수행한 후 전송되는 이메일 알림 + * 이메일 서버에 연결하고 이메일을 전송하는 것은 (몇 초 정도) "느린" 경향이 있으므로, 응답은 즉시 반환하고 이메일 알림은 백그라운드에서 전송하는 게 가능합니다. +* 데이터 처리: + * 예를 들어 처리에 오랜 시간이 걸리는 데이터를 받았을 때 "Accepted" (HTTP 202)을 반환하고, 백그라운드에서 데이터를 처리할 수 있습니다. + +## `백그라운드 작업` 사용 + +먼저 아래와 같이 `BackgroundTasks`를 임포트하고, `BackgroundTasks`를 _경로 작동 함수_ 에서 매개변수로 가져오고 정의합니다. + +```Python hl_lines="1 13" +{!../../../docs_src/background_tasks/tutorial001.py!} +``` + +**FastAPI** 는 `BackgroundTasks` 개체를 생성하고, 매개 변수로 전달합니다. + +## 작업 함수 생성 + +백그라운드 작업으로 실행할 함수를 정의합니다. + +이것은 단순히 매개변수를 받을 수 있는 표준 함수일 뿐입니다. + +**FastAPI**는 이것이 `async def` 함수이든, 일반 `def` 함수이든 내부적으로 이를 올바르게 처리합니다. + +이 경우, 아래 작업은 파일에 쓰는 함수입니다. (이메일 보내기 시물레이션) + +그리고 이 작업은 `async`와 `await`를 사용하지 않으므로 일반 `def` 함수로 선언합니다. + +```Python hl_lines="6-9" +{!../../../docs_src/background_tasks/tutorial001.py!} +``` + +## 백그라운드 작업 추가 + +_경로 작동 함수_ 내에서 작업 함수를 `.add_task()` 함수 통해 _백그라운드 작업_ 개체에 전달합니다. + +```Python hl_lines="14" +{!../../../docs_src/background_tasks/tutorial001.py!} +``` + +`.add_task()` 함수는 다음과 같은 인자를 받습니다 : + +- 백그라운드에서 실행되는 작업 함수 (`write_notification`). +- 작업 함수에 순서대로 전달되어야 하는 일련의 인자 (`email`). +- 작업 함수에 전달되어야하는 모든 키워드 인자 (`message="some notification"`). + +## 의존성 주입 + +`BackgroundTasks`를 의존성 주입 시스템과 함께 사용하면 _경로 작동 함수_, 종속성, 하위 종속성 등 여러 수준에서 BackgroundTasks 유형의 매개변수를 선언할 수 있습니다. + +**FastAPI**는 각 경우에 수행할 작업과 동일한 개체를 내부적으로 재사용하기에, 모든 백그라운드 작업이 함께 병합되고 나중에 백그라운드에서 실행됩니다. + +=== "Python 3.6 and above" + + ```Python hl_lines="13 15 22 25" + {!> ../../../docs_src/background_tasks/tutorial002.py!} + ``` + +=== "Python 3.10 and above" + + ```Python hl_lines="11 13 20 23" + {!> ../../../docs_src/background_tasks/tutorial002_py310.py!} + ``` + +이 예제에서는 응답이 반환된 후에 `log.txt` 파일에 메시지가 기록됩니다. + +요청에 쿼리가 있는 경우 백그라운드 작업의 로그에 기록됩니다. + +그리고 _경로 작동 함수_ 에서 생성된 또 다른 백그라운드 작업은 경로 매개 변수를 활용하여 사용하여 메시지를 작성합니다. + +## 기술적 세부사항 + +`BackgroundTasks` 클래스는 `starlette.background`에서 직접 가져옵니다. + +`BackgroundTasks` 클래스는 FastAPI에서 직접 임포트하거나 포함하기 때문에 실수로 `BackgroundTask` (끝에 `s`가 없음)을 임포트하더라도 starlette.background에서 `BackgroundTask`를 가져오는 것을 방지할 수 있습니다. + +(`BackgroundTask`가 아닌) `BackgroundTasks`를 사용하면, _경로 작동 함수_ 매개변수로 사용할 수 있게 되고 나머지는 **FastAPI**가 대신 처리하도록 할 수 있습니다. 이것은 `Request` 객체를 직접 사용하는 것과 같은 방식입니다. + +FastAPI에서 `BackgroundTask`를 단독으로 사용하는 것은 여전히 가능합니다. 하지만 객체를 코드에서 생성하고, 이 객체를 포함하는 Starlette `Response`를 반환해야 합니다. + +`Starlette의 공식 문서`에서 백그라운드 작업에 대한 자세한 내용을 확인할 수 있습니다. + +## 경고 + +만약 무거운 백그라운드 작업을 수행해야하고 동일한 프로세스에서 실행할 필요가 없는 경우 (예: 메모리, 변수 등을 공유할 필요가 없음) `Celery`와 같은 큰 도구를 사용하면 도움이 될 수 있습니다. + +RabbitMQ 또는 Redis와 같은 메시지/작업 큐 시스템 보다 복잡한 구성이 필요한 경향이 있지만, 여러 작업 프로세스를 특히 여러 서버의 백그라운드에서 실행할 수 있습니다. + +예제를 보시려면 [프로젝트 생성기](../project-generation.md){.internal-link target=\_blank} 를 참고하세요. 해당 예제에는 이미 구성된 `Celery`가 포함되어 있습니다. + +그러나 동일한 FastAPI 앱에서 변수 및 개체에 접근해야햐는 작은 백그라운드 수행이 필요한 경우 (예 : 알림 이메일 보내기) 간단하게 `BackgroundTasks`를 사용해보세요. + +## 요약 + +백그라운드 작업을 추가하기 위해 _경로 작동 함수_ 에 매개변수로 `BackgroundTasks`를 가져오고 사용합니다. diff --git a/docs/ko/docs/tutorial/body-fields.md b/docs/ko/docs/tutorial/body-fields.md new file mode 100644 index 0000000000000..fc7209726c201 --- /dev/null +++ b/docs/ko/docs/tutorial/body-fields.md @@ -0,0 +1,116 @@ +# 본문 - 필드 + +`Query`, `Path`와 `Body`를 사용해 *경로 작동 함수* 매개변수 내에서 추가적인 검증이나 메타데이터를 선언한 것처럼 Pydantic의 `Field`를 사용하여 모델 내에서 검증과 메타데이터를 선언할 수 있습니다. + +## `Field` 임포트 + +먼저 이를 임포트해야 합니다: + +=== "Python 3.10+" + + ```Python hl_lines="4" + {!> ../../../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.8+" + + ```Python hl_lines="4" + {!> ../../../docs_src/body_fields/tutorial001_an.py!} + ``` + +=== "Python 3.10+ Annotated가 없는 경우" + + !!! 팁 + 가능하다면 `Annotated`가 달린 버전을 권장합니다. + + ```Python hl_lines="2" + {!> ../../../docs_src/body_fields/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ Annotated가 없는 경우" + + !!! tip "팁" + 가능하다면 `Annotated`가 달린 버전을 권장합니다. + + ```Python hl_lines="4" + {!> ../../../docs_src/body_fields/tutorial001.py!} + ``` + +!!! warning "경고" + `Field`는 다른 것들처럼 (`Query`, `Path`, `Body` 등) `fastapi`에서가 아닌 `pydantic`에서 바로 임포트 되는 점에 주의하세요. + +## 모델 어트리뷰트 선언 + +그 다음 모델 어트리뷰트와 함께 `Field`를 사용할 수 있습니다: + +=== "Python 3.10+" + + ```Python hl_lines="11-14" + {!> ../../../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.8+" + + ```Python hl_lines="12-15" + {!> ../../../docs_src/body_fields/tutorial001_an.py!} + ``` + +=== "Python 3.10+ Annotated가 없는 경우" + + !!! tip "팁" + 가능하다면 `Annotated`가 달린 버전을 권장합니다. + + ```Python hl_lines="9-12" + {!> ../../../docs_src/body_fields/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ Annotated가 없는 경우" + + !!! tip "팁" + 가능하다면 `Annotated`가 달린 버전을 권장합니다. + + ```Python hl_lines="11-14" + {!> ../../../docs_src/body_fields/tutorial001.py!} + ``` + +`Field`는 `Query`, `Path`와 `Body`와 같은 방식으로 동작하며, 모두 같은 매개변수들 등을 가집니다. + +!!! note "기술적 세부사항" + 실제로 `Query`, `Path`등, 여러분이 앞으로 볼 다른 것들은 공통 클래스인 `Param` 클래스의 서브클래스 객체를 만드는데, 그 자체로 Pydantic의 `FieldInfo` 클래스의 서브클래스입니다. + + 그리고 Pydantic의 `Field` 또한 `FieldInfo`의 인스턴스를 반환합니다. + + `Body` 또한 `FieldInfo`의 서브클래스 객체를 직접적으로 반환합니다. 그리고 `Body` 클래스의 서브클래스인 것들도 여러분이 나중에 보게될 것입니다. + + `Query`, `Path`와 그 외 것들을 `fastapi`에서 임포트할 때, 이는 실제로 특별한 클래스를 반환하는 함수인 것을 기억해 주세요. + +!!! tip "팁" + 주목할 점은 타입, 기본 값 및 `Field`로 이루어진 각 모델 어트리뷰트가 `Path`, `Query`와 `Body`대신 `Field`를 사용하는 *경로 작동 함수*의 매개변수와 같은 구조를 가진다는 점 입니다. + +## 별도 정보 추가 + +`Field`, `Query`, `Body`, 그 외 안에 별도 정보를 선언할 수 있습니다. 이는 생성된 JSON 스키마에 포함됩니다. + +여러분이 예제를 선언할 때 나중에 이 공식 문서에서 별도 정보를 추가하는 방법을 배울 것입니다. + +!!! warning "경고" + 별도 키가 전달된 `Field` 또한 여러분의 어플리케이션의 OpenAPI 스키마에 나타날 것입니다. + 이런 키가 OpenAPI 명세서, [the OpenAPI validator](https://validator.swagger.io/)같은 몇몇 OpenAPI 도구들에 포함되지 못할 수 있으며, 여러분이 생성한 스키마와 호환되지 않을 수 있습니다. + +## 요약 + +모델 어트리뷰트를 위한 추가 검증과 메타데이터 선언하기 위해 Pydantic의 `Field` 를 사용할 수 있습니다. + +또한 추가적인 JSON 스키마 메타데이터를 전달하기 위한 별도의 키워드 인자를 사용할 수 있습니다. diff --git a/docs/ko/docs/tutorial/body-multiple-params.md b/docs/ko/docs/tutorial/body-multiple-params.md new file mode 100644 index 0000000000000..2cf5df7f31727 --- /dev/null +++ b/docs/ko/docs/tutorial/body-multiple-params.md @@ -0,0 +1,170 @@ +# 본문 - 다중 매개변수 + +지금부터 `Path`와 `Query`를 어떻게 사용하는지 확인하겠습니다. + +요청 본문 선언에 대한 심화 사용법을 알아보겠습니다. + +## `Path`, `Query` 및 본문 매개변수 혼합 + +당연하게 `Path`, `Query` 및 요청 본문 매개변수 선언을 자유롭게 혼합해서 사용할 수 있고, **FastAPI**는 어떤 동작을 할지 압니다. + +또한, 기본 값을 `None`으로 설정해 본문 매개변수를 선택사항으로 선언할 수 있습니다. + +```Python hl_lines="19-21" +{!../../../docs_src/body_multiple_params/tutorial001.py!} +``` + +!!! note "참고" + 이 경우에는 본문으로 부터 가져온 ` item`은 기본값이 `None`이기 때문에, 선택사항이라는 점을 유의해야 합니다. + +## 다중 본문 매개변수 + +이전 예제에서 보듯이, *경로 작동*은 아래와 같이 `Item` 속성을 가진 JSON 본문을 예상합니다: + +```JSON +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 +} +``` + +하지만, 다중 본문 매개변수 역시 선언할 수 있습니다. 예. `item`과 `user`: + +```Python hl_lines="22" +{!../../../docs_src/body_multiple_params/tutorial002.py!} +``` + +이 경우에, **FastAPI**는 이 함수 안에 한 개 이상의 본문 매개변수(Pydantic 모델인 두 매개변수)가 있다고 알 것입니다. + +그래서, 본문의 매개변수 이름을 키(필드 명)로 사용할 수 있고, 다음과 같은 본문을 예측합니다: + +```JSON +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + }, + "user": { + "username": "dave", + "full_name": "Dave Grohl" + } +} +``` + +!!! note "참고" + 이전과 같이 `item`이 선언 되었더라도, 본문 내의 `item` 키가 있을 것이라고 예측합니다. + +FastAPI는 요청을 자동으로 변환해, 매개변수의 `item`과 `user`를 특별한 내용으로 받도록 할 것입니다. + +복합 데이터의 검증을 수행하고 OpenAPI 스키마 및 자동 문서를 문서화합니다. + +## 본문 내의 단일 값 + +쿼리 및 경로 매개변수에 대한 추가 데이터를 정의하는 `Query`와 `Path`와 같이, **FastAPI**는 동등한 `Body`를 제공합니다. + +예를 들어 이전의 모델을 확장하면, `item`과 `user`와 동일한 본문에 또 다른 `importance`라는 키를 갖도록 할 수있습니다. + +단일 값을 그대로 선언한다면, **FastAPI**는 쿼리 매개변수로 가정할 것입니다. + +하지만, **FastAPI**의 `Body`를 사용해 다른 본문 키로 처리하도록 제어할 수 있습니다: + + +```Python hl_lines="23" +{!../../../docs_src/body_multiple_params/tutorial003.py!} +``` + +이 경우에는 **FastAPI**는 본문을 이와 같이 예측할 것입니다: + + +```JSON +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + }, + "user": { + "username": "dave", + "full_name": "Dave Grohl" + }, + "importance": 5 +} +``` + +다시 말해, 데이터 타입, 검증, 문서 등을 변환합니다. + +## 다중 본문 매개변수와 쿼리 + +당연히, 필요할 때마다 추가적인 쿼리 매개변수를 선언할 수 있고, 이는 본문 매개변수에 추가됩니다. + +기본적으로 단일 값은 쿼리 매개변수로 해석되므로, 명시적으로 `Query`를 추가할 필요가 없고, 아래처럼 할 수 있습니다: + +```Python hl_lines="27" +{!../../../docs_src/body_multiple_params/tutorial004.py!} +``` + +이렇게: + +```Python +q: Optional[str] = None +``` + +!!! info "정보" + `Body` 또한 `Query`, `Path` 그리고 이후에 볼 다른 것들처럼 동일한 추가 검증과 메타데이터 매개변수를 갖고 있습니다. + +## 단일 본문 매개변수 삽입하기 + +Pydantic 모델 `Item`의 `item`을 본문 매개변수로 오직 한개만 갖고있다고 하겠습니다. + +기본적으로 **FastAPI**는 직접 본문으로 예측할 것입니다. + +하지만, 만약 모델 내용에 `item `키를 가진 JSON으로 예측하길 원한다면, 추가적인 본문 매개변수를 선언한 것처럼 `Body`의 특별한 매개변수인 `embed`를 사용할 수 있습니다: + +```Python hl_lines="17" +{!../../../docs_src/body_multiple_params/tutorial005.py!} +``` + +아래 처럼: + +```Python +item: Item = Body(..., embed=True) +``` + +이 경우에 **FastAPI**는 본문을 아래 대신에: + +```JSON hl_lines="2" +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 +} +``` + +아래 처럼 예측할 것 입니다: + +```JSON +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + } +} +``` + +## 정리 + +요청이 단 한개의 본문을 가지고 있더라도, *경로 작동 함수*로 다중 본문 매개변수를 추가할 수 있습니다. + +하지만, **FastAPI**는 이를 처리하고, 함수에 올바른 데이터를 제공하며, *경로 작동*으로 올바른 스키마를 검증하고 문서화 합니다. + +또한, 단일 값을 본문의 일부로 받도록 선언할 수 있습니다. + +그리고 **FastAPI**는 단 한개의 매개변수가 선언 되더라도, 본문 내의 키로 삽입 시킬 수 있습니다. diff --git a/docs/ko/docs/tutorial/body-nested-models.md b/docs/ko/docs/tutorial/body-nested-models.md new file mode 100644 index 0000000000000..edf1a5f77a800 --- /dev/null +++ b/docs/ko/docs/tutorial/body-nested-models.md @@ -0,0 +1,243 @@ +# 본문 - 중첩 모델 + +**FastAPI**를 이용하면 (Pydantic 덕분에) 단독으로 깊이 중첩된 모델을 정의, 검증, 문서화하며 사용할 수 있습니다. +## 리스트 필드 + +어트리뷰트를 서브타입으로 정의할 수 있습니다. 예를 들어 파이썬 `list`는: + +```Python hl_lines="14" +{!../../../docs_src/body_nested_models/tutorial001.py!} +``` + +이는 `tags`를 항목 리스트로 만듭니다. 각 항목의 타입을 선언하지 않더라도요. + +## 타입 매개변수가 있는 리스트 필드 + +하지만 파이썬은 내부의 타입이나 "타입 매개변수"를 선언할 수 있는 특정 방법이 있습니다: + +### typing의 `List` 임포트 + +먼저, 파이썬 표준 `typing` 모듈에서 `List`를 임포트합니다: + +```Python hl_lines="1" +{!../../../docs_src/body_nested_models/tutorial002.py!} +``` + +### 타입 매개변수로 `List` 선언 + +`list`, `dict`, `tuple`과 같은 타입 매개변수(내부 타입)를 갖는 타입을 선언하려면: + +* `typing` 모듈에서 임포트 +* 대괄호를 사용하여 "타입 매개변수"로 내부 타입 전달: `[` 및 `]` + +```Python +from typing import List + +my_list: List[str] +``` + +이 모든 것은 타입 선언을 위한 표준 파이썬 문법입니다. + +내부 타입을 갖는 모델 어트리뷰트에 대해 동일한 표준 문법을 사용하세요. + +마찬가지로 예제에서 `tags`를 구체적으로 "문자열의 리스트"로 만들 수 있습니다: + +```Python hl_lines="14" +{!../../../docs_src/body_nested_models/tutorial002.py!} +``` + +## 집합 타입 + +그런데 생각해보니 태그는 반복되면 안 돼고, 고유한(Unique) 문자열이어야 할 것 같습니다. + +그리고 파이썬은 집합을 위한 특별한 데이터 타입 `set`이 있습니다. + +그렇다면 `Set`을 임포트 하고 `tags`를 `str`의 `set`으로 선언할 수 있습니다: + +```Python hl_lines="1 14" +{!../../../docs_src/body_nested_models/tutorial003.py!} +``` + +덕분에 중복 데이터가 있는 요청을 수신하더라도 고유한 항목들의 집합으로 변환됩니다. + +그리고 해당 데이터를 출력 할 때마다 소스에 중복이 있더라도 고유한 항목들의 집합으로 출력됩니다. + +또한 그에 따라 주석이 생기고 문서화됩니다. + +## 중첩 모델 + +Pydantic 모델의 각 어트리뷰트는 타입을 갖습니다. + +그런데 해당 타입 자체로 또다른 Pydantic 모델의 타입이 될 수 있습니다. + +그러므로 특정한 어트리뷰트의 이름, 타입, 검증을 사용하여 깊게 중첩된 JSON "객체"를 선언할 수 있습니다. + +모든 것이 단독으로 중첩됩니다. + +### 서브모델 정의 + +예를 들어, `Image` 모델을 선언할 수 있습니다: + +```Python hl_lines="9-11" +{!../../../docs_src/body_nested_models/tutorial004.py!} +``` + +### 서브모듈을 타입으로 사용 + +그리고 어트리뷰트의 타입으로 사용할 수 있습니다: + +```Python hl_lines="20" +{!../../../docs_src/body_nested_models/tutorial004.py!} +``` + +이는 **FastAPI**가 다음과 유사한 본문을 기대한다는 것을 의미합니다: + +```JSON +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2, + "tags": ["rock", "metal", "bar"], + "image": { + "url": "http://example.com/baz.jpg", + "name": "The Foo live" + } +} +``` + +다시 한번, **FastAPI**를 사용하여 해당 선언을 함으로써 얻는 것은: + +* 중첩 모델도 편집기 지원(자동완성 등) +* 데이터 변환 +* 데이터 검증 +* 자동 문서화 + +## 특별한 타입과 검증 + +`str`, `int`, `float` 등과 같은 단일 타입과는 별개로, `str`을 상속하는 더 복잡한 단일 타입을 사용할 수 있습니다. + +모든 옵션을 보려면, Pydantic's exotic types 문서를 확인하세요. 다음 장에서 몇가지 예제를 볼 수 있습니다. + +예를 들어 `Image` 모델 안에 `url` 필드를 `str` 대신 Pydantic의 `HttpUrl`로 선언할 수 있습니다: + +```Python hl_lines="4 10" +{!../../../docs_src/body_nested_models/tutorial005.py!} +``` + +이 문자열이 유효한 URL인지 검사하고 JSON 스키마/OpenAPI로 문서화 됩니다. + +## 서브모델 리스트를 갖는 어트리뷰트 + +`list`, `set` 등의 서브타입으로 Pydantic 모델을 사용할 수도 있습니다: + +```Python hl_lines="20" +{!../../../docs_src/body_nested_models/tutorial006.py!} +``` + +아래와 같은 JSON 본문으로 예상(변환, 검증, 문서화 등을)합니다: + +```JSON hl_lines="11" +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2, + "tags": [ + "rock", + "metal", + "bar" + ], + "images": [ + { + "url": "http://example.com/baz.jpg", + "name": "The Foo live" + }, + { + "url": "http://example.com/dave.jpg", + "name": "The Baz" + } + ] +} +``` + +!!! info "정보" + `images` 키가 어떻게 이미지 객체 리스트를 갖는지 주목하세요. + +## 깊게 중첩된 모델 + +단독으로 깊게 중첩된 모델을 정의할 수 있습니다: + +```Python hl_lines="9 14 20 23 27" +{!../../../docs_src/body_nested_models/tutorial007.py!} +``` + +!!! info "정보" + `Offer`가 선택사항 `Image` 리스트를 차례로 갖는 `Item` 리스트를 어떻게 가지고 있는지 주목하세요 + +## 순수 리스트의 본문 + +예상되는 JSON 본문의 최상위 값이 JSON `array`(파이썬 `list`)면, Pydantic 모델에서와 마찬가지로 함수의 매개변수에서 타입을 선언할 수 있습니다: + +```Python +images: List[Image] +``` + +이를 아래처럼: + +```Python hl_lines="15" +{!../../../docs_src/body_nested_models/tutorial008.py!} +``` + +## 어디서나 편집기 지원 + +그리고 어디서나 편집기 지원을 받을수 있습니다. + +리스트 내부 항목의 경우에도: + + + +Pydantic 모델 대신에 `dict`를 직접 사용하여 작업할 경우, 이러한 편집기 지원을 받을수 없습니다. + +하지만 수신한 딕셔너리가 자동으로 변환되고 출력도 자동으로 JSON으로 변환되므로 걱정할 필요는 없습니다. + +## 단독 `dict`의 본문 + +일부 타입의 키와 다른 타입의 값을 사용하여 `dict`로 본문을 선언할 수 있습니다. + +(Pydantic을 사용한 경우처럼) 유효한 필드/어트리뷰트 이름이 무엇인지 알 필요가 없습니다. + +아직 모르는 키를 받으려는 경우 유용합니다. + +--- + +다른 유용한 경우는 다른 타입의 키를 가질 때입니다. 예. `int`. + +여기서 그 경우를 볼 것입니다. + +이 경우, `float` 값을 가진 `int` 키가 있는 모든 `dict`를 받아들입니다: + +```Python hl_lines="15" +{!../../../docs_src/body_nested_models/tutorial009.py!} +``` + +!!! tip "팁" + JSON은 오직 `str`형 키만 지원한다는 것을 염두에 두세요. + + 하지만 Pydantic은 자동 데이터 변환이 있습니다. + + 즉, API 클라이언트가 문자열을 키로 보내더라도 해당 문자열이 순수한 정수를 포함하는한 Pydantic은 이를 변환하고 검증합니다. + + 그러므로 `weights`로 받은 `dict`는 실제로 `int` 키와 `float` 값을 가집니다. + +## 요약 + +**FastAPI**를 사용하면 Pydantic 모델이 제공하는 최대 유연성을 확보하면서 코드를 간단하고 짧게, 그리고 우아하게 유지할 수 있습니다. + +물론 아래의 이점도 있습니다: + +* 편집기 지원 (자동완성이 어디서나!) +* 데이터 변환 (일명 파싱/직렬화) +* 데이터 검증 +* 스키마 문서화 +* 자동 문서 diff --git a/docs/ko/docs/tutorial/body.md b/docs/ko/docs/tutorial/body.md new file mode 100644 index 0000000000000..8b98284bb2957 --- /dev/null +++ b/docs/ko/docs/tutorial/body.md @@ -0,0 +1,213 @@ +# 요청 본문 + +클라이언트(브라우저라고 해봅시다)로부터 여러분의 API로 데이터를 보내야 할 때, **요청 본문**으로 보냅니다. + +**요청** 본문은 클라이언트에서 API로 보내지는 데이터입니다. **응답** 본문은 API가 클라이언트로 보내는 데이터입니다. + +여러분의 API는 대부분의 경우 **응답** 본문을 보내야 합니다. 하지만 클라이언트는 **요청** 본문을 매 번 보낼 필요가 없습니다. + +**요청** 본문을 선언하기 위해서 모든 강력함과 이점을 갖춘 Pydantic 모델을 사용합니다. + +!!! 정보 + 데이터를 보내기 위해, (좀 더 보편적인) `POST`, `PUT`, `DELETE` 혹은 `PATCH` 중에 하나를 사용하는 것이 좋습니다. + + `GET` 요청에 본문을 담아 보내는 것은 명세서에 정의되지 않은 행동입니다. 그럼에도 불구하고, 이 방식은 아주 복잡한/극한의 사용 상황에서만 FastAPI에 의해 지원됩니다. + + `GET` 요청에 본문을 담는 것은 권장되지 않기에, Swagger UI같은 대화형 문서에서는 `GET` 사용시 담기는 본문에 대한 문서를 표시하지 않으며, 중간에 있는 프록시는 이를 지원하지 않을 수도 있습니다. + +## Pydantic의 `BaseModel` 임포트 + +먼저 `pydantic`에서 `BaseModel`를 임포트해야 합니다: + +=== "Python 3.10+" + + ```Python hl_lines="2" + {!> ../../../docs_src/body/tutorial001_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="4" + {!> ../../../docs_src/body/tutorial001.py!} + ``` + +## 여러분의 데이터 모델 만들기 + +`BaseModel`를 상속받은 클래스로 여러분의 데이터 모델을 선언합니다. + +모든 어트리뷰트에 대해 표준 파이썬 타입을 사용합니다: + +=== "Python 3.10+" + + ```Python hl_lines="5-9" + {!> ../../../docs_src/body/tutorial001_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="7-11" + {!> ../../../docs_src/body/tutorial001.py!} + ``` + +쿼리 매개변수를 선언할 때와 같이, 모델 어트리뷰트가 기본 값을 가지고 있어도 이는 필수가 아닙니다. 그외에는 필수입니다. 그저 `None`을 사용하여 선택적으로 만들 수 있습니다. + +예를 들면, 위의 이 모델은 JSON "`object`" (혹은 파이썬 `dict`)을 다음과 같이 선언합니다: + +```JSON +{ + "name": "Foo", + "description": "선택적인 설명란", + "price": 45.2, + "tax": 3.5 +} +``` + +...`description`과 `tax`는 (기본 값이 `None`으로 되어 있어) 선택적이기 때문에, 이 JSON "`object`"는 다음과 같은 상황에서도 유효합니다: + +```JSON +{ + "name": "Foo", + "price": 45.2 +} +``` + +## 매개변수로서 선언하기 + +여러분의 *경로 작동*에 추가하기 위해, 경로 매개변수 그리고 쿼리 매개변수에서 선언했던 것과 같은 방식으로 선언하면 됩니다. + +=== "Python 3.10+" + + ```Python hl_lines="16" + {!> ../../../docs_src/body/tutorial001_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="18" + {!> ../../../docs_src/body/tutorial001.py!} + ``` + +...그리고 만들어낸 모델인 `Item`으로 타입을 선언합니다. + +## 결과 + +위에서의 단순한 파이썬 타입 선언으로, **FastAPI**는 다음과 같이 동작합니다: + +* 요청의 본문을 JSON으로 읽어 들입니다. +* (필요하다면) 대응되는 타입으로 변환합니다. +* 데이터를 검증합니다. + * 만약 데이터가 유효하지 않다면, 정확히 어떤 것이 그리고 어디에서 데이터가 잘 못 되었는지 지시하는 친절하고 명료한 에러를 반환할 것입니다. +* 매개변수 `item`에 포함된 수신 데이터를 제공합니다. + * 함수 내에서 매개변수를 `Item` 타입으로 선언했기 때문에, 모든 어트리뷰트와 그에 대한 타입에 대한 편집기 지원(완성 등)을 또한 받을 수 있습니다. +* 여러분의 모델을 위한 JSON 스키마 정의를 생성합니다. 여러분의 프로젝트에 적합하다면 여러분이 사용하고 싶은 곳 어디에서나 사용할 수 있습니다. +* 이러한 스키마는, 생성된 OpenAPI 스키마 일부가 될 것이며, 자동 문서화 UI에 사용됩니다. + +## 자동 문서화 + +모델의 JSON 스키마는 생성된 OpenAPI 스키마에 포함되며 대화형 API 문서에 표시됩니다: + + + +이를 필요로 하는 각각의 *경로 작동*내부의 API 문서에도 사용됩니다: + + + +## 편집기 지원 + +편집기에서, 함수 내에서 타입 힌트와 완성을 어디서나 (만약 Pydantic model 대신에 `dict`을 받을 경우 나타나지 않을 수 있습니다) 받을 수 있습니다: + + + +잘못된 타입 연산에 대한 에러 확인도 받을 수 있습니다: + + + +단순한 우연이 아닙니다. 프레임워크 전체가 이러한 디자인을 중심으로 설계되었습니다. + +그 어떤 실행 전에, 모든 편집기에서 작동할 수 있도록 보장하기 위해 설계 단계에서 혹독하게 테스트되었습니다. + +이를 지원하기 위해 Pydantic 자체에서 몇몇 변경점이 있었습니다. + +이전 스크린샷은 Visual Studio Code를 찍은 것입니다. + +하지만 똑같은 편집기 지원을 PyCharm에서 받을 수 있거나, 대부분의 다른 편집기에서도 받을 수 있습니다: + + + +!!! 팁 + 만약 PyCharm를 편집기로 사용한다면, Pydantic PyCharm Plugin을 사용할 수 있습니다. + + 다음 사항을 포함해 Pydantic 모델에 대한 편집기 지원을 향상시킵니다: + + * 자동 완성 + * 타입 확인 + * 리팩토링 + * 검색 + * 점검 + +## 모델 사용하기 + +함수 안에서 모델 객체의 모든 어트리뷰트에 직접 접근 가능합니다: + +=== "Python 3.10+" + + ```Python hl_lines="19" + {!> ../../../docs_src/body/tutorial002_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="21" + {!> ../../../docs_src/body/tutorial002.py!} + ``` + +## 요청 본문 + 경로 매개변수 + +경로 매개변수와 요청 본문을 동시에 선언할 수 있습니다. + +**FastAPI**는 경로 매개변수와 일치하는 함수 매개변수가 **경로에서 가져와야 한다**는 것을 인지하며, Pydantic 모델로 선언된 그 함수 매개변수는 **요청 본문에서 가져와야 한다**는 것을 인지할 것입니다. + +=== "Python 3.10+" + + ```Python hl_lines="15-16" + {!> ../../../docs_src/body/tutorial003_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="17-18" + {!> ../../../docs_src/body/tutorial003.py!} + ``` + +## 요청 본문 + 경로 + 쿼리 매개변수 + +**본문**, **경로** 그리고 **쿼리** 매개변수 모두 동시에 선언할 수도 있습니다. + +**FastAPI**는 각각을 인지하고 데이터를 옳바른 위치에 가져올 것입니다. + +=== "Python 3.10+" + + ```Python hl_lines="16" + {!> ../../../docs_src/body/tutorial004_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="18" + {!> ../../../docs_src/body/tutorial004.py!} + ``` + +함수 매개변수는 다음을 따라서 인지하게 됩니다: + +* 만약 매개변수가 **경로**에도 선언되어 있다면, 이는 경로 매개변수로 사용될 것입니다. +* 만약 매개변수가 (`int`, `float`, `str`, `bool` 등과 같은) **유일한 타입**으로 되어있으면, **쿼리** 매개변수로 해석될 것입니다. +* 만약 매개변수가 **Pydantic 모델** 타입으로 선언되어 있으면, 요청 **본문**으로 해석될 것입니다. + +!!! 참고 + FastAPI는 `q`의 값이 필요없음을 알게 될 것입니다. 기본 값이 `= None`이기 때문입니다. + + `Union[str, None]`에 있는 `Union`은 FastAPI에 의해 사용된 것이 아니지만, 편집기로 하여금 더 나은 지원과 에러 탐지를 지원할 것입니다. + +## Pydantic없이 + +만약 Pydantic 모델을 사용하고 싶지 않다면, **Body** 매개변수를 사용할 수도 있습니다. [Body - 다중 매개변수: 본문에 있는 유일한 값](body-multiple-params.md#singular-values-in-body){.internal-link target=_blank} 문서를 확인하세요. diff --git a/docs/ko/docs/tutorial/cookie-params.md b/docs/ko/docs/tutorial/cookie-params.md new file mode 100644 index 0000000000000..d4f3d57a34d31 --- /dev/null +++ b/docs/ko/docs/tutorial/cookie-params.md @@ -0,0 +1,97 @@ +# 쿠키 매개변수 + +쿠키 매개변수를 `Query`와 `Path` 매개변수들과 같은 방식으로 정의할 수 있습니다. + +## `Cookie` 임포트 + +먼저 `Cookie`를 임포트합니다: + +=== "Python 3.10+" + + ```Python hl_lines="3" + {!> ../../../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.8+" + + ```Python hl_lines="3" + {!> ../../../docs_src/cookie_params/tutorial001_an.py!} + ``` + +=== "Python 3.10+ Annotated가 없는 경우" + + !!! tip "팁" + 가능하다면 `Annotated`가 달린 버전을 권장합니다. + + ```Python hl_lines="1" + {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ Annotated가 없는 경우" + + !!! tip "팁" + 가능하다면 `Annotated`가 달린 버전을 권장합니다. + + ```Python hl_lines="3" + {!> ../../../docs_src/cookie_params/tutorial001.py!} + ``` + +## `Cookie` 매개변수 선언 + +그런 다음, `Path`와 `Query`처럼 동일한 구조를 사용하는 쿠키 매개변수를 선언합니다. + +첫 번째 값은 기본값이며, 추가 검증이나 어노테이션 매개변수 모두 전달할 수 있습니다: + +=== "Python 3.10+" + + ```Python hl_lines="9" + {!> ../../../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.8+" + + ```Python hl_lines="10" + {!> ../../../docs_src/cookie_params/tutorial001_an.py!} + ``` + +=== "Python 3.10+ Annotated가 없는 경우" + + !!! tip "팁" + 가능하다면 `Annotated`가 달린 버전을 권장합니다. + + ```Python hl_lines="7" + {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ Annotated가 없는 경우" + + !!! tip "팁" + 가능하다면 `Annotated`가 달린 버전을 권장합니다. + + ```Python hl_lines="9" + {!> ../../../docs_src/cookie_params/tutorial001.py!} + ``` + +!!! note "기술 세부사항" + `Cookie`는 `Path` 및 `Query`의 "자매"클래스입니다. 이 역시 동일한 공통 `Param` 클래스를 상속합니다. + + `Query`, `Path`, `Cookie` 그리고 다른 것들은 `fastapi`에서 임포트 할 때, 실제로는 특별한 클래스를 반환하는 함수임을 기억하세요. + +!!! info "정보" + 쿠키를 선언하기 위해서는 `Cookie`를 사용해야 합니다. 그렇지 않으면 해당 매개변수를 쿼리 매개변수로 해석하기 때문입니다. + +## 요약 + +`Cookie`는 `Query`, `Path`와 동일한 패턴을 사용하여 선언합니다. diff --git a/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md index bbf3a82838c70..38cdc2e1a9470 100644 --- a/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md @@ -71,9 +71,9 @@ fluffy = Cat(name="Mr Fluffy") FastAPI가 실질적으로 확인하는 것은 "호출 가능성"(함수, 클래스 또는 다른 모든 것)과 정의된 매개변수들입니다. -"호출 가능"한 것을 의존성으로서 **FastAPI**에 전달하면, 그 "호출 가능"한 것의 매개변수들을 분석한 후 이를 *경로 동작 함수*를 위한 매개변수와 동일한 방식으로 처리합니다. 하위-의존성 또한 같은 방식으로 처리합니다. +"호출 가능"한 것을 의존성으로서 **FastAPI**에 전달하면, 그 "호출 가능"한 것의 매개변수들을 분석한 후 이를 *경로 작동 함수*를 위한 매개변수와 동일한 방식으로 처리합니다. 하위-의존성 또한 같은 방식으로 처리합니다. -매개변수가 없는 "호출 가능"한 것 역시 매개변수가 없는 *경로 동작 함수*와 동일한 방식으로 적용됩니다. +매개변수가 없는 "호출 가능"한 것 역시 매개변수가 없는 *경로 작동 함수*와 동일한 방식으로 적용됩니다. 그래서, 우리는 위 예제에서의 `common_paramenters` 의존성을 클래스 `CommonQueryParams`로 바꿀 수 있습니다. diff --git a/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md new file mode 100644 index 0000000000000..92b2c7d1cd716 --- /dev/null +++ b/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -0,0 +1,139 @@ +# 경로 작동 데코레이터에서의 의존성 + +몇몇 경우에는, *경로 작동 함수* 안에서 의존성의 반환 값이 필요하지 않습니다. + +또는 의존성이 값을 반환하지 않습니다. + +그러나 여전히 실행/해결될 필요가 있습니다. + +그런 경우에, `Depends`를 사용하여 *경로 작동 함수*의 매개변수로 선언하는 것보다 *경로 작동 데코레이터*에 `dependencies`의 `list`를 추가할 수 있습니다. + +## *경로 작동 데코레이터*에 `dependencies` 추가하기 + +*경로 작동 데코레이터*는 `dependencies`라는 선택적인 인자를 받습니다. + +`Depends()`로 된 `list`이어야합니다: + +=== "Python 3.9+" + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="18" + {!> ../../../docs_src/dependencies/tutorial006_an.py!} + ``` + +=== "Python 3.8 Annotated가 없는 경우" + + !!! tip "팁" + 가능하다면 `Annotated`가 달린 버전을 권장합니다. + + ```Python hl_lines="17" + {!> ../../../docs_src/dependencies/tutorial006.py!} + ``` + +이러한 의존성들은 기존 의존성들과 같은 방식으로 실행/해결됩니다. 그러나 값은 (무엇이든 반환한다면) *경로 작동 함수*에 제공되지 않습니다. + +!!! tip "팁" + 일부 편집기에서는 사용되지 않는 함수 매개변수를 검사하고 오류로 표시합니다. + + *경로 작동 데코레이터*에서 `dependencies`를 사용하면 편집기/도구 오류를 피하며 실행되도록 할 수 있습니다. + + 또한 코드에서 사용되지 않는 매개변수를 보고 불필요하다고 생각할 수 있는 새로운 개발자의 혼란을 방지하는데 도움이 될 수 있습니다. + +!!! info "정보" + 이 예시에서 `X-Key`와 `X-Token`이라는 커스텀 헤더를 만들어 사용했습니다. + + 그러나 실제로 보안을 구현할 때는 통합된 [보안 유틸리티 (다음 챕터)](../security/index.md){.internal-link target=_blank}를 사용하는 것이 더 많은 이점을 얻을 수 있습니다. + +## 의존성 오류와 값 반환하기 + +평소에 사용하던대로 같은 의존성 *함수*를 사용할 수 있습니다. + +### 의존성 요구사항 + +(헤더같은) 요청 요구사항이나 하위-의존성을 선언할 수 있습니다: + +=== "Python 3.9+" + + ```Python hl_lines="8 13" + {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="7 12" + {!> ../../../docs_src/dependencies/tutorial006_an.py!} + ``` + +=== "Python 3.8 Annotated가 없는 경우" + + !!! tip "팁" + 가능하다면 `Annotated`가 달린 버전을 권장합니다. + + ```Python hl_lines="6 11" + {!> ../../../docs_src/dependencies/tutorial006.py!} + ``` + +### 오류 발생시키기 + +다음 의존성은 기존 의존성과 동일하게 예외를 `raise`를 일으킬 수 있습니다: + +=== "Python 3.9+" + + ```Python hl_lines="10 15" + {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9 14" + {!> ../../../docs_src/dependencies/tutorial006_an.py!} + ``` + +=== "Python 3.8 Annotated가 없는 경우" + + !!! tip "팁" + 가능하다면 `Annotated`가 달린 버전을 권장합니다. + + ```Python hl_lines="8 13" + {!> ../../../docs_src/dependencies/tutorial006.py!} + ``` + +### 값 반환하기 + +값을 반환하거나, 그러지 않을 수 있으며 값은 사용되지 않습니다. + +그래서 이미 다른 곳에서 사용된 (값을 반환하는) 일반적인 의존성을 재사용할 수 있고, 비록 값은 사용되지 않지만 의존성은 실행될 것입니다: + +=== "Python 3.9+" + + ```Python hl_lines="11 16" + {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="10 15" + {!> ../../../docs_src/dependencies/tutorial006_an.py!} + ``` + +=== "Python 3.8 Annotated가 없는 경우" + + !!! tip "팁" + 가능하다면 `Annotated`가 달린 버전을 권장합니다. + + ```Python hl_lines="9 14" + {!> ../../../docs_src/dependencies/tutorial006.py!} + ``` + +## *경로 작동* 모음에 대한 의존성 + +나중에 여러 파일을 가지고 있을 수 있는 더 큰 애플리케이션을 구조화하는 법([더 큰 애플리케이션 - 여러 파일들](../../tutorial/bigger-applications.md){.internal-link target=_blank})을 읽을 때, *경로 작동* 모음에 대한 단일 `dependencies` 매개변수를 선언하는 법에 대해서 배우게 될 것입니다. + +## 전역 의존성 + +다음으로 각 *경로 작동*에 적용되도록 `FastAPI` 애플리케이션 전체에 의존성을 추가하는 법을 볼 것입니다. diff --git a/docs/ko/docs/tutorial/dependencies/global-dependencies.md b/docs/ko/docs/tutorial/dependencies/global-dependencies.md new file mode 100644 index 0000000000000..930f6e6787c53 --- /dev/null +++ b/docs/ko/docs/tutorial/dependencies/global-dependencies.md @@ -0,0 +1,34 @@ +# 전역 의존성 + +몇몇 애플리케이션에서는 애플리케이션 전체에 의존성을 추가하고 싶을 수 있습니다. + +[*경로 작동 데코레이터*에 `dependencies` 추가하기](dependencies-in-path-operation-decorators.md){.internal-link target=_blank}와 유사한 방법으로 `FastAPI` 애플리케이션에 그것들을 추가할 수 있습니다. + +그런 경우에, 애플리케이션의 모든 *경로 작동*에 적용될 것입니다: + +=== "Python 3.9+" + + ```Python hl_lines="16" + {!> ../../../docs_src/dependencies/tutorial012_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="16" + {!> ../../../docs_src/dependencies/tutorial012_an.py!} + ``` + +=== "Python 3.8 Annotated가 없는 경우" + + !!! tip "팁" + 가능하다면 `Annotated`가 달린 버전을 권장합니다. + + ```Python hl_lines="15" + {!> ../../../docs_src/dependencies/tutorial012.py!} + ``` + +그리고 [*경로 작동 데코레이터*에 `dependencies` 추가하기](dependencies-in-path-operation-decorators.md){.internal-link target=_blank}에 대한 아이디어는 여전히 적용되지만 여기에서는 앱에 있는 모든 *경로 작동*에 적용됩니다. + +## *경로 작동* 모음에 대한 의존성 + +이후에 여러 파일들을 가지는 더 큰 애플리케이션을 구조화하는 법([더 큰 애플리케이션 - 여러 파일들](../../tutorial/bigger-applications.md){.internal-link target=_blank})을 읽을 때, *경로 작동* 모음에 대한 단일 `dependencies` 매개변수를 선언하는 법에 대해서 배우게 될 것입니다. diff --git a/docs/ko/docs/tutorial/dependencies/index.md b/docs/ko/docs/tutorial/dependencies/index.md new file mode 100644 index 0000000000000..c56dddae3a010 --- /dev/null +++ b/docs/ko/docs/tutorial/dependencies/index.md @@ -0,0 +1,353 @@ +# 의존성 + +**FastAPI**는 아주 강력하지만 직관적인 **의존성 주입** 시스템을 가지고 있습니다. + +이는 사용하기 아주 쉽게 설계했으며, 어느 개발자나 다른 컴포넌트와 **FastAPI**를 쉽게 통합할 수 있도록 만들었습니다. + +## "의존성 주입"은 무엇입니까? + +**"의존성 주입"**은 프로그래밍에서 여러분의 코드(이 경우, 경로 작동 함수)가 작동하고 사용하는 데 필요로 하는 것, 즉 "의존성"을 선언할 수 있는 방법을 의미합니다. + +그 후에, 시스템(이 경우 FastAPI)은 여러분의 코드가 요구하는 의존성을 제공하기 위해 필요한 모든 작업을 처리합니다.(의존성을 "주입"합니다) + +이는 여러분이 다음과 같은 사항을 필요로 할 때 매우 유용합니다: + +* 공용된 로직을 가졌을 경우 (같은 코드 로직이 계속 반복되는 경우). +* 데이터베이스 연결을 공유하는 경우. +* 보안, 인증, 역할 요구 사항 등을 강제하는 경우. +* 그리고 많은 다른 사항... + +이 모든 사항을 할 때 코드 반복을 최소화합니다. + +## 첫번째 단계 + +아주 간단한 예제를 봅시다. 너무 간단할 것이기에 지금 당장은 유용하지 않을 수 있습니다. + +하지만 이를 통해 **의존성 주입** 시스템이 어떻게 작동하는지에 중점을 둘 것입니다. + +### 의존성 혹은 "디펜더블" 만들기 + +의존성에 집중해 봅시다. + +*경로 작동 함수*가 가질 수 있는 모든 매개변수를 갖는 단순한 함수입니다: + +=== "Python 3.10+" + + ```Python hl_lines="8-9" + {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="8-11" + {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9-12" + {!> ../../../docs_src/dependencies/tutorial001_an.py!} + ``` + +=== "Python 3.10+ Annotated가 없는 경우" + + !!! tip "팁" + 가능하다면 `Annotated`가 달린 버전을 권장합니다. + + ```Python hl_lines="6-7" + {!> ../../../docs_src/dependencies/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ Annotated가 없는 경우" + + !!! tip "팁" + 가능하다면 `Annotated`가 달린 버전을 권장합니다. + + ```Python hl_lines="8-11" + {!> ../../../docs_src/dependencies/tutorial001.py!} + ``` + +이게 다입니다. + +**단 두 줄입니다**. + +그리고, 이 함수는 여러분의 모든 *경로 작동 함수*가 가지고 있는 것과 같은 형태와 구조를 가지고 있습니다. + +여러분은 이를 "데코레이터"가 없는 (`@app.get("/some-path")`가 없는) *경로 작동 함수*라고 생각할 수 있습니다. + +그리고 여러분이 원하는 무엇이든 반환할 수 있습니다. + +이 경우, 이 의존성은 다음과 같은 경우를 기대합니다: + +* 선택적인 쿼리 매개변수 `q`, `str`을 자료형으로 가집니다. +* 선택적인 쿼리 매개변수 `skip`, `int`를 자료형으로 가지며 기본 값은 `0`입니다. +* 선택적인 쿼리 매개변수 `limit`,`int`를 자료형으로 가지며 기본 값은 `100`입니다. + +그 후 위의 값을 포함한 `dict` 자료형으로 반환할 뿐입니다. + +!!! 정보 + FastAPI는 0.95.0 버전부터 `Annotated`에 대한 지원을 (그리고 이를 사용하기 권장합니다) 추가했습니다. + + 옛날 버전을 가지고 있는 경우, `Annotated`를 사용하려 하면 에러를 맞이하게 될 것입니다. + + `Annotated`를 사용하기 전에 최소 0.95.1로 [FastAPI 버전 업그레이드](../../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank}를 확실하게 하세요. + +### `Depends` 불러오기 + +=== "Python 3.10+" + + ```Python hl_lines="3" + {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="3" + {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="3" + {!> ../../../docs_src/dependencies/tutorial001_an.py!} + ``` + +=== "Python 3.10+ Annotated가 없는 경우" + + !!! tip "팁" + 가능하다면 `Annotated`가 달린 버전을 권장합니다. + + ```Python hl_lines="1" + {!> ../../../docs_src/dependencies/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ Annotated가 없는 경우" + + !!! tip "팁" + 가능하다면 `Annotated`가 달린 버전을 권장합니다. + + ```Python hl_lines="3" + {!> ../../../docs_src/dependencies/tutorial001.py!} + ``` + +### "의존자"에 의존성 명시하기 + +*경로 작동 함수*의 매개변수로 `Body`, `Query` 등을 사용하는 방식과 같이 새로운 매개변수로 `Depends`를 사용합니다: + +=== "Python 3.10+" + + ```Python hl_lines="13 18" + {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="15 20" + {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="16 21" + {!> ../../../docs_src/dependencies/tutorial001_an.py!} + ``` + +=== "Python 3.10+ Annotated가 없는 경우" + + !!! tip "팁" + 가능하다면 `Annotated`가 달린 버전을 권장합니다. + + ```Python hl_lines="11 16" + {!> ../../../docs_src/dependencies/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ Annotated가 없는 경우" + + !!! tip "팁" + 가능하다면 `Annotated`가 달린 버전을 권장합니다. + + ```Python hl_lines="15 20" + {!> ../../../docs_src/dependencies/tutorial001.py!} + ``` + +비록 `Body`, `Query` 등을 사용하는 것과 같은 방식으로 여러분의 함수의 매개변수에 있는 `Depends`를 사용하지만, `Depends`는 약간 다르게 작동합니다. + +`Depends`에 단일 매개변수만 전달했습니다. + +이 매개변수는 함수같은 것이어야 합니다. + +여러분은 직접 **호출하지 않았습니다** (끝에 괄호를 치지 않았습니다), 단지 `Depends()`에 매개변수로 넘겨 줬을 뿐입니다. + +그리고 그 함수는 *경로 작동 함수*가 작동하는 것과 같은 방식으로 매개변수를 받습니다. + +!!! tip "팁" + 여러분은 다음 장에서 함수를 제외하고서, "다른 것들"이 어떻게 의존성으로 사용되는지 알게 될 것입니다. + +새로운 요청이 도착할 때마다, **FastAPI**는 다음을 처리합니다: + +* 올바른 매개변수를 가진 의존성("디펜더블") 함수를 호출합니다. +* 함수에서 결과를 받아옵니다. +* *경로 작동 함수*에 있는 매개변수에 그 결과를 할당합니다 + +```mermaid +graph TB + +common_parameters(["common_parameters"]) +read_items["/items/"] +read_users["/users/"] + +common_parameters --> read_items +common_parameters --> read_users +``` + +이렇게 하면 공용 코드를 한번만 적어도 되며, **FastAPI**는 *경로 작동*을 위해 이에 대한 호출을 처리합니다. + +!!! check "확인" + 특별한 클래스를 만들지 않아도 되며, 이러한 것 혹은 비슷한 종류를 **FastAPI**에 "등록"하기 위해 어떤 곳에 넘겨주지 않아도 됩니다. + + 단순히 `Depends`에 넘겨주기만 하면 되며, **FastAPI**는 나머지를 어찌할지 알고 있습니다. + +## `Annotated`인 의존성 공유하기 + +위의 예제에서 몇몇 작은 **코드 중복**이 있다는 것을 보았을 겁니다. + +`common_parameters()`의존을 사용해야 한다면, 타입 명시와 `Depends()`와 함께 전체 매개변수를 적어야 합니다: + +```Python +commons: Annotated[dict, Depends(common_parameters)] +``` + +하지만 `Annotated`를 사용하고 있기에, `Annotated` 값을 변수에 저장하고 여러 장소에서 사용할 수 있습니다: + +=== "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.8+" + + ```Python hl_lines="15 19 24" + {!> ../../../docs_src/dependencies/tutorial001_02_an.py!} + ``` + +!!! tip "팁" + 이는 그저 표준 파이썬이고 "type alias"라고 부르며 사실 **FastAPI**에 국한되는 것은 아닙니다. + + 하지만, `Annotated`를 포함하여, **FastAPI**가 파이썬 표준을 기반으로 하고 있기에, 이를 여러분의 코드 트릭으로 사용할 수 있습니다. 😎 + +이 의존성은 계속해서 예상한대로 작동할 것이며, **제일 좋은 부분**은 **타입 정보가 보존된다는 것입니다**. 즉 여러분의 편집기가 **자동 완성**, **인라인 에러** 등을 계속해서 제공할 수 있다는 것입니다. `mypy`같은 다른 도구도 마찬가지입니다. + +이는 특히 **많은 *경로 작동***에서 **같은 의존성**을 계속해서 사용하는 **거대 코드 기반**안에서 사용하면 유용할 것입니다. + +## `async`하게, 혹은 `async`하지 않게 + +의존성이 (*경로 작동 함수*에서 처럼 똑같이) **FastAPI**에 의해 호출될 수 있으며, 함수를 정의할 때 동일한 규칙이 적용됩니다. + +`async def`을 사용하거나 혹은 일반적인 `def`를 사용할 수 있습니다. + +그리고 일반적인 `def` *경로 작동 함수* 안에 `async def`로 의존성을 선언할 수 있으며, `async def` *경로 작동 함수* 안에 `def`로 의존성을 선언하는 등의 방법이 있습니다. + +아무 문제 없습니다. **FastAPI**는 무엇을 할지 알고 있습니다. + +!!! note "참고" + 잘 모르시겠다면, [Async: *"In a hurry?"*](../../async.md){.internal-link target=_blank} 문서에서 `async`와 `await`에 대해 확인할 수 있습니다. + +## OpenAPI와 통합 + +모든 요청 선언, 검증과 의존성(및 하위 의존성)에 대한 요구 사항은 동일한 OpenAPI 스키마에 통합됩니다. + +따라서 대화형 문서에 이러한 의존성에 대한 모든 정보 역시 포함하고 있습니다: + + + +## 간단한 사용법 + +이를 보면, *경로 작동 함수*는 *경로*와 *작동*이 매칭되면 언제든지 사용되도록 정의되었으며, **FastAPI**는 올바른 매개변수를 가진 함수를 호출하고 해당 요청에서 데이터를 추출합니다. + +사실, 모든 (혹은 대부분의) 웹 프레임워크는 이와 같은 방식으로 작동합니다. + +여러분은 이러한 함수들을 절대 직접 호출하지 않습니다. 프레임워크(이 경우 **FastAPI**)에 의해 호출됩니다. + +의존성 주입 시스템과 함께라면 **FastAPI**에게 여러분의 *경로 작동 함수*가 실행되기 전에 실행되어야 하는 무언가에 여러분의 *경로 작동 함수* 또한 "의존"하고 있음을 알릴 수 있으며, **FastAPI**는 이를 실행하고 결과를 "주입"할 것입니다. + +"의존성 주입"이라는 동일한 아이디어에 대한 다른 일반적인 용어는 다음과 같습니다: + +* 리소스 +* 제공자 +* 서비스 +* 인젝터블 +* 컴포넌트 + +## **FastAPI** 플러그인 + +통합과 "플러그인"은 **의존성 주입** 시스템을 사용하여 구축할 수 있습니다. 하지만 실제로 **"플러그인"을 만들 필요는 없습니다**, 왜냐하면 의존성을 사용함으로써 여러분의 *경로 작동 함수*에 통합과 상호 작용을 무한대로 선언할 수 있기 때문입니다. + +그리고 "말 그대로", 그저 필요로 하는 파이썬 패키지를 임포트하고 단 몇 줄의 코드로 여러분의 API 함수와 통합함으로써, 의존성을 아주 간단하고 직관적인 방법으로 만들 수 있습니다. + +관계형 및 NoSQL 데이터베이스, 보안 등, 이에 대한 예시를 다음 장에서 볼 수 있습니다. + +## **FastAPI** 호환성 + +의존성 주입 시스템의 단순함은 **FastAPI**를 다음과 같은 요소들과 호환할 수 있게 합니다: + +* 모든 관계형 데이터베이스 +* NoSQL 데이터베이스 +* 외부 패키지 +* 외부 API +* 인증 및 권한 부여 시스템 +* API 사용 모니터링 시스템 +* 응답 데이터 주입 시스템 +* 기타 등등. + +## 간편하고 강력하다 + +계층적인 의존성 주입 시스템은 정의하고 사용하기 쉽지만, 여전히 매우 강력합니다. + +여러분은 스스로를 의존하는 의존성을 정의할 수 있습니다. + +끝에는, 계층적인 나무로 된 의존성이 만들어지며, 그리고 **의존성 주입** 시스템은 (하위 의존성도 마찬가지로) 이러한 의존성들을 처리하고 각 단계마다 결과를 제공합니다(주입합니다). + +예를 들면, 여러분이 4개의 API 엔드포인트(*경로 작동*)를 가지고 있다고 해봅시다: + +* `/items/public/` +* `/items/private/` +* `/users/{user_id}/activate` +* `/items/pro/` + +그 다음 각각에 대해 그저 의존성과 하위 의존성을 사용하여 다른 권한 요구 사항을 추가할 수 있을 겁니다: + +```mermaid +graph TB + +current_user(["current_user"]) +active_user(["active_user"]) +admin_user(["admin_user"]) +paying_user(["paying_user"]) + +public["/items/public/"] +private["/items/private/"] +activate_user["/users/{user_id}/activate"] +pro_items["/items/pro/"] + +current_user --> active_user +active_user --> admin_user +active_user --> paying_user + +current_user --> public +active_user --> private +admin_user --> activate_user +paying_user --> pro_items +``` + +## **OpenAPI**와의 통합 + +이 모든 의존성은 각각의 요구사항을 선언하는 동시에, *경로 작동*에 매개변수, 검증 등을 추가합니다. + +**FastAPI**는 이 모든 것을 OpenAPI 스키마에 추가할 것이며, 이를 통해 대화형 문서 시스템에 나타날 것입니다. diff --git a/docs/ko/docs/tutorial/first-steps.md b/docs/ko/docs/tutorial/first-steps.md index a669cb2ba7e79..e3b42bce73bbf 100644 --- a/docs/ko/docs/tutorial/first-steps.md +++ b/docs/ko/docs/tutorial/first-steps.md @@ -1,12 +1,12 @@ # 첫걸음 -가장 단순한 FastAPI 파일은 다음과 같이 보일 겁니다: +가장 단순한 FastAPI 파일은 다음과 같이 보일 것입니다: ```Python {!../../../docs_src/first_steps/tutorial001.py!} ``` -위를 `main.py`에 복사합니다. +위 코드를 `main.py`에 복사합니다. 라이브 서버를 실행합니다: @@ -29,9 +29,9 @@ $ uvicorn main:app --reload * `main`: 파일 `main.py` (파이썬 "모듈"). * `app`: `main.py` 내부의 `app = FastAPI()` 줄에서 생성한 오브젝트. - * `--reload`: 코드 변경 후 서버 재시작. 개발에만 사용. + * `--reload`: 코드 변경 시 자동으로 서버 재시작. 개발 시에만 사용. -출력에 아래와 같은 줄이 있습니다: +출력되는 줄들 중에는 아래와 같은 내용이 있습니다: ```hl_lines="4" INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) @@ -75,7 +75,7 @@ INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) #### API "스키마" -이 경우, OpenAPI는 API의 스키마를 어떻게 정의하는지 지시하는 규격입니다. +OpenAPI는 API의 스키마를 어떻게 정의하는지 지시하는 규격입니다. 이 스키마 정의는 API 경로, 가능한 매개변수 등을 포함합니다. @@ -87,13 +87,13 @@ INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) #### OpenAPI와 JSON 스키마 -OpenAPI는 API에 대한 API 스키마를 정의합니다. 또한 이 스키마에는 JSON 데이터 스키마의 표준인 **JSON 스키마**를 사용하여 API에서 보내고 받은 데이터의 정의(또는 "스키마")를 포함합니다. +OpenAPI는 당신의 API에 대한 API 스키마를 정의합니다. 또한 이 스키마는 JSON 데이터 스키마의 표준인 **JSON 스키마**를 사용하여 당신의 API가 보내고 받는 데이터의 정의(또는 "스키마")를 포함합니다. #### `openapi.json` 확인 -가공되지 않은 OpenAPI 스키마가 어떻게 생겼는지 궁금하다면, FastAPI는 자동으로 API의 설명과 함께 JSON (스키마)를 생성합니다. +FastAPI는 자동으로 API의 설명과 함께 JSON (스키마)를 생성합니다. -여기에서 직접 볼 수 있습니다: http://127.0.0.1:8000/openapi.json. +가공되지 않은 OpenAPI 스키마가 어떻게 생겼는지 궁금하다면, 여기에서 직접 볼 수 있습니다: http://127.0.0.1:8000/openapi.json. 다음과 같이 시작하는 JSON을 확인할 수 있습니다: @@ -124,7 +124,7 @@ OpenAPI 스키마는 포함된 두 개의 대화형 문서 시스템을 제공 그리고 OpenAPI의 모든 것을 기반으로 하는 수십 가지 대안이 있습니다. **FastAPI**로 빌드한 애플리케이션에 이러한 대안을 쉽게 추가 할 수 있습니다. -API와 통신하는 클라이언트를 위해 코드를 자동으로 생성하는 데도 사용할 수 있습니다. 예로 프론트엔드, 모바일, IoT 애플리케이션이 있습니다. +API와 통신하는 클라이언트(프론트엔드, 모바일, IoT 애플리케이션 등)를 위해 코드를 자동으로 생성하는 데도 사용할 수 있습니다. ## 단계별 요약 @@ -134,7 +134,7 @@ API와 통신하는 클라이언트를 위해 코드를 자동으로 생성하 {!../../../docs_src/first_steps/tutorial001.py!} ``` -`FastAPI`는 API에 대한 모든 기능을 제공하는 파이썬 클래스입니다. +`FastAPI`는 당신의 API를 위한 모든 기능을 제공하는 파이썬 클래스입니다. !!! note "기술 세부사항" `FastAPI`는 `Starlette`를 직접 상속하는 클래스입니다. @@ -147,11 +147,11 @@ API와 통신하는 클라이언트를 위해 코드를 자동으로 생성하 {!../../../docs_src/first_steps/tutorial001.py!} ``` -여기 있는 `app` 변수는 `FastAPI` 클래스의 "인스턴스"가 됩니다. +여기에서 `app` 변수는 `FastAPI` 클래스의 "인스턴스"가 됩니다. -이것은 모든 API를 생성하기 위한 상호작용의 주요 지점이 될 것입니다. +이것은 당신의 모든 API를 생성하기 위한 상호작용의 주요 지점이 될 것입니다. -이 `app`은 다음 명령에서 `uvicorn`이 참조하고 것과 동일합니다: +이 `app`은 다음 명령에서 `uvicorn`이 참조하고 있는 것과 동일합니다:
@@ -181,11 +181,11 @@ $ uvicorn main:my_awesome_api --reload
-### 3 단계: *경로 동작* 생성 +### 3 단계: *경로 작동* 생성 #### 경로 -여기서 "경로"는 첫 번째 `/`에서 시작하는 URL의 마지막 부분을 나타냅니다. +여기서 "경로"는 첫 번째 `/`부터 시작하는 URL의 뒷부분을 의미합니다. 그러므로 아래와 같은 URL에서: @@ -200,13 +200,13 @@ https://example.com/items/foo ``` !!! info "정보" - "경로"는 일반적으로 "앤드포인트" 또는 "라우트"라고도 불립니다. + "경로"는 일반적으로 "엔드포인트" 또는 "라우트"라고도 불립니다. -API를 빌드하는 동안 "경로"는 "관심사"와 "리소스"를 분리하는 주요 방법입니다. +API를 설계할 때 "경로"는 "관심사"와 "리소스"를 분리하기 위한 주요한 방법입니다. -#### 동작 +#### 작동 -여기서 "동작(Operation)"은 HTTP "메소드" 중 하나를 나타냅니다. +"작동(Operation)"은 HTTP "메소드" 중 하나를 나타냅니다. 다음 중 하나이며: @@ -215,7 +215,7 @@ API를 빌드하는 동안 "경로"는 "관심사"와 "리소스"를 분리하 * `PUT` * `DELETE` -...이국적인 것들도 있습니다: +...흔히 사용되지 않는 것들도 있습니다: * `OPTIONS` * `HEAD` @@ -226,20 +226,20 @@ HTTP 프로토콜에서는 이러한 "메소드"를 하나(또는 이상) 사용 --- -API를 빌드하는 동안 일반적으로 특정 행동을 수행하기 위해 특정 HTTP 메소드를 사용합니다. +API를 설계할 때 일반적으로 특정 행동을 수행하기 위해 특정 HTTP 메소드를 사용합니다. -일반적으로 다음을 사용합니다: +일반적으로 다음과 같습니다: * `POST`: 데이터를 생성하기 위해. * `GET`: 데이터를 읽기 위해. -* `PUT`: 데이터를 업데이트하기 위해. +* `PUT`: 데이터를 수정하기 위해. * `DELETE`: 데이터를 삭제하기 위해. -그래서 OpenAPI에서는 각 HTTP 메소드들을 "동작"이라 부릅니다. +그래서 OpenAPI에서는 각 HTTP 메소드들을 "작동"이라 부릅니다. -이제부터 우리는 메소드를 "**동작**"이라고도 부를겁니다. +우리 역시 이제부터 메소드를 "**작동**"이라고 부를 것입니다. -#### *경로 동작 데코레이터* 정의 +#### *경로 작동 데코레이터* 정의 ```Python hl_lines="6" {!../../../docs_src/first_steps/tutorial001.py!} @@ -248,26 +248,26 @@ API를 빌드하는 동안 일반적으로 특정 행동을 수행하기 위해 `@app.get("/")`은 **FastAPI**에게 바로 아래에 있는 함수가 다음으로 이동하는 요청을 처리한다는 것을 알려줍니다. * 경로 `/` -* get 동작 사용 +* get 작동 사용 !!! info "`@decorator` 정보" 이 `@something` 문법은 파이썬에서 "데코레이터"라 부릅니다. - 함수 맨 위에 놓습니다. 마치 예쁜 장식용(Decorative) 모자처럼(개인적으로 이 용어가 여기서 유래한거 같습니다). + 마치 예쁜 장식용(Decorative) 모자처럼(개인적으로 이 용어가 여기서 유래한 것 같습니다) 함수 맨 위에 놓습니다. - "데코레이터" 아래 있는 함수를 받고 그걸 이용해 무언가 합니다. + "데코레이터"는 아래 있는 함수를 받아 그것으로 무언가를 합니다. - 우리의 경우, 이 데코레이터는 **FastAPI**에게 아래 함수가 **경로** `/`에 해당하는 `get` **동작**하라고 알려줍니다. + 우리의 경우, 이 데코레이터는 **FastAPI**에게 아래 함수가 **경로** `/`의 `get` **작동**에 해당한다고 알려줍니다. - 이것이 "**경로 동작 데코레이터**"입니다. + 이것이 "**경로 작동 데코레이터**"입니다. -다른 동작도 쓸 수 있습니다: +다른 작동도 사용할 수 있습니다: * `@app.post()` * `@app.put()` * `@app.delete()` -이국적인 것들도 있습니다: +흔히 사용되지 않는 것들도 있습니다: * `@app.options()` * `@app.head()` @@ -275,20 +275,20 @@ API를 빌드하는 동안 일반적으로 특정 행동을 수행하기 위해 * `@app.trace()` !!! tip "팁" - 각 동작(HTTP 메소드)을 원하는 대로 사용해도 됩니다. + 각 작동(HTTP 메소드)을 원하는 대로 사용해도 됩니다. **FastAPI**는 특정 의미를 강제하지 않습니다. - 여기서 정보는 지침서일뿐 요구사항이 아닙니다. + 여기서 정보는 지침서일뿐 강제사항이 아닙니다. - 예를 들어 GraphQL을 사용할때 일반적으로 `POST` 동작만 사용하여 모든 행동을 수행합니다. + 예를 들어 GraphQL을 사용하는 경우, 일반적으로 `POST` 작동만 사용하여 모든 행동을 수행합니다. -### 4 단계: **경로 동작 함수** 정의 +### 4 단계: **경로 작동 함수** 정의 -다음은 우리의 "**경로 동작 함수**"입니다: +다음은 우리의 "**경로 작동 함수**"입니다: * **경로**: 는 `/`입니다. -* **동작**: 은 `get`입니다. +* **작동**: 은 `get`입니다. * **함수**: 는 "데코레이터" 아래에 있는 함수입니다 (`@app.get("/")` 아래). ```Python hl_lines="7" @@ -297,19 +297,19 @@ API를 빌드하는 동안 일반적으로 특정 행동을 수행하기 위해 이것은 파이썬 함수입니다. -`GET` 동작을 사용하여 URL "`/`"에 대한 요청을 받을 때마다 **FastAPI**에 의해 호출됩니다. +URL "`/`"에 대한 `GET` 작동을 사용하는 요청을 받을 때마다 **FastAPI**에 의해 호출됩니다. -위의 경우 `async` 함수입니다. +위의 예시에서 이 함수는 `async`(비동기) 함수입니다. --- -`async def` 대신 일반 함수로 정의할 수 있습니다: +`async def`을 이용하는 대신 일반 함수로 정의할 수 있습니다: ```Python hl_lines="7" {!../../../docs_src/first_steps/tutorial003.py!} ``` -!!! note 참고 +!!! note "참고" 차이점을 모르겠다면 [Async: *"In a hurry?"*](../async.md#in-a-hurry){.internal-link target=_blank}을 확인하세요. ### 5 단계: 콘텐츠 반환 @@ -322,12 +322,12 @@ API를 빌드하는 동안 일반적으로 특정 행동을 수행하기 위해 Pydantic 모델을 반환할 수도 있습니다(나중에 더 자세히 살펴봅니다). -JSON으로 자동 변환되는 객체들과 모델들이 많이 있습니다(ORM 등을 포함해서요). 가장 마음에 드는 것을 사용하세요, 이미 지원되고 있을 겁니다. +JSON으로 자동 변환되는 객체들과 모델들(ORM 등을 포함해서)이 많이 있습니다. 가장 마음에 드는 것을 사용하십시오, 이미 지원되고 있을 것입니다. ## 요약 * `FastAPI` 임포트. * `app` 인스턴스 생성. -* (`@app.get("/")`처럼) **경로 동작 데코레이터** 작성. -* (위에 있는 `def root(): ...`처럼) **경로 동작 함수** 작성. +* (`@app.get("/")`처럼) **경로 작동 데코레이터** 작성. +* (위에 있는 `def root(): ...`처럼) **경로 작동 함수** 작성. * (`uvicorn main:app --reload`처럼) 개발 서버 실행. diff --git a/docs/ko/docs/tutorial/index.md b/docs/ko/docs/tutorial/index.md index deb5ca8f27c4d..94d6dfb923a07 100644 --- a/docs/ko/docs/tutorial/index.md +++ b/docs/ko/docs/tutorial/index.md @@ -1,16 +1,16 @@ # 자습서 - 사용자 안내서 -이 자습서는 **FastAPI**의 대부분의 기능을 단계별로 사용하는 방법을 보여줍니다. +이 자습서는 단계별로 **FastAPI**의 대부분의 기능에 대해 설명합니다. -각 섹션은 이전 섹션을 기반해서 점진적으로 만들어 졌지만, 주제에 따라 다르게 구성되었기 때문에 특정 API 요구사항을 해결하기 위해서라면 어느 특정 항목으로던지 직접 이동할 수 있습니다. +각 섹션은 이전 섹션에 기반하는 순차적인 구조로 작성되었지만, 각 주제로 구분되어 있기 때문에 필요에 따라 특정 섹션으로 바로 이동하여 필요한 내용을 바로 확인할 수 있습니다. -또한 향후 참조가 될 수 있도록 만들어졌습니다. +또한 향후에도 참조 자료로 쓰일 수 있도록 작성되었습니다. -그러므로 다시 돌아와서 정확히 필요한 것을 확인할 수 있습니다. +그러므로 필요할 때에 다시 돌아와서 원하는 것을 정확히 찾을 수 있습니다. ## 코드 실행하기 -모든 코드 블록은 복사하고 직접 사용할 수 있습니다(실제로 테스트한 파이썬 파일입니다). +모든 코드 블록은 복사하여 바로 사용할 수 있습니다(실제로 테스트된 파이썬 파일입니다). 예제를 실행하려면 코드를 `main.py` 파일에 복사하고 다음을 사용하여 `uvicorn`을 시작합니다: @@ -28,17 +28,18 @@ $ uvicorn main:app --reload
-코드를 작성하거나 복사, 편집할 때, 로컬에서 실행하는 것을 **강력히 장려**합니다. +코드를 작성하거나 복사, 편집할 때, 로컬 환경에서 실행하는 것을 **강력히 권장**합니다. + +로컬 편집기에서 사용한다면, 모든 타입 검사와 자동완성 등 작성해야 하는 코드가 얼마나 적은지 보면서 FastAPI의 비로소 경험할 수 있습니다. -편집기에서 이렇게 사용한다면, 모든 타입 검사와 자동완성 등 작성해야 하는 코드가 얼마나 적은지 보면서 FastAPI의 장점을 실제로 확인할 수 있습니다. --- ## FastAPI 설치 -첫 번째 단계는 FastAPI 설치입니다. +첫 번째 단계는 FastAPI를 설치하는 것입니다. -자습시에는 모든 선택적인 의존성 및 기능을 사용하여 설치할 수 있습니다: +자습시에는 모든 선택적인 의존성 및 기능을 함께 설치하는 것을 추천합니다:
@@ -50,7 +51,7 @@ $ pip install "fastapi[all]"
-...코드를 실행하는 서버로 사용할 수 있는 `uvicorn` 역시 포함하고 있습니다. +...이는 코드를 실행하는 서버로 사용할 수 있는 `uvicorn` 또한 포함하고 있습니다. !!! note "참고" 부분적으로 설치할 수도 있습니다. @@ -73,8 +74,8 @@ $ pip install "fastapi[all]" 이 **자습서 - 사용자 안내서** 다음에 읽을 수 있는 **고급 사용자 안내서**도 있습니다. -**고급 사용자 안내서**는 현재 문서를 기반으로 하고, 동일한 개념을 사용하며, 추가 기능들을 알려줍니다. +**고급 사용자 안내서**는 현재 문서를 기반으로 하고, 동일한 개념을 사용하며, 추가적인 기능들에 대해 설명합니다. -하지만 (지금 읽고 있는) **자습서 - 사용자 안내서**를 먼저 읽는게 좋습니다. +하지만 (지금 읽고 있는) **자습서 - 사용자 안내서**를 먼저 읽는 것을 권장합니다. -**자습서 - 사용자 안내서**만으로도 완전한 애플리케이션을 구축할 수 있으며, 필요에 따라 **고급 사용자 안내서**에서 제공하는 몇 가지 추가적인 기능을 사용하여 다양한 방식으로 확장할 수 있도록 설계되었습니다. +**자습서 - 사용자 안내서**만으로도 완전한 애플리케이션을 구축할 수 있도록 작성되었으며, 필요에 따라 **고급 사용자 안내서**의 추가적인 아이디어를 적용하여 다양한 방식으로 확장할 수 있습니다. diff --git a/docs/ko/docs/tutorial/middleware.md b/docs/ko/docs/tutorial/middleware.md new file mode 100644 index 0000000000000..f35b446a613bf --- /dev/null +++ b/docs/ko/docs/tutorial/middleware.md @@ -0,0 +1,61 @@ +# 미들웨어 + +미들웨어를 **FastAPI** 응용 프로그램에 추가할 수 있습니다. + +"미들웨어"는 특정 *경로 작동*에 의해 처리되기 전, 모든 **요청**에 대해서 동작하는 함수입니다. 또한 모든 **응답**이 반환되기 전에도 동일하게 동작합니다. + +* 미들웨어는 응용 프로그램으로 오는 **요청**를 가져옵니다. +* **요청** 또는 다른 필요한 코드를 실행 시킬 수 있습니다. +* **요청**을 응용 프로그램의 *경로 작동*으로 전달하여 처리합니다. +* 애플리케이션의 *경로 작업*에서 생성한 **응답**를 받습니다. +* **응답** 또는 다른 필요한 코드를 실행시키는 동작을 할 수 있습니다. +* **응답**를 반환합니다. + +!!! note "기술 세부사항" + 만약 `yield`를 사용한 의존성을 가지고 있다면, 미들웨어가 실행되고 난 후에 exit이 실행됩니다. + + 만약 (나중에 문서에서 다룰) 백그라운드 작업이 있다면, 모든 미들웨어가 실행되고 *난 후에* 실행됩니다. + +## 미들웨어 만들기 + +미들웨어를 작성하기 위해서 함수 상단에 `@app.middleware("http")` 데코레이터를 사용할 수 있습니다. + +미들웨어 함수는 다음 항목들을 받습니다: + +* `request`. +* `request`를 매개변수로 받는 `call_next` 함수. + * 이 함수는 `request`를 해당하는 *경로 작업*으로 전달합니다. + * 그런 다음, *경로 작업*에 의해 생성된 `response` 를 반환합니다. +* `response`를 반환하기 전에 추가로 `response`를 수정할 수 있습니다. + +```Python hl_lines="8-9 11 14" +{!../../../docs_src/middleware/tutorial001.py!} +``` + +!!! tip "팁" + 사용자 정의 헤더는 'X-' 접두사를 사용하여 추가할 수 있습니다. + + 그러나 만약 클라이언트의 브라우저에서 볼 수 있는 사용자 정의 헤더를 가지고 있다면, 그것들을 CORS 설정([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank})에 Starlette CORS 문서에 명시된 `expose_headers` 매개변수를 이용하여 헤더들을 추가하여야합니다. + +!!! note "기술적 세부사항" + `from starlette.requests import request`를 사용할 수도 있습니다. + + **FastAPI**는 개발자에게 편의를 위해 이를 제공합니다. 그러나 Starlette에서 직접 파생되었습니다. + +### `response`의 전과 후 + +*경로 작동*을 받기 전 `request`와 함께 작동할 수 있는 코드를 추가할 수 있습니다. + +그리고 `response` 또한 생성된 후 반환되기 전에 코드를 추가 할 수 있습니다. + +예를 들어, 요청을 수행하고 응답을 생성하는데 까지 걸린 시간 값을 가지고 있는 `X-Process-Time` 같은 사용자 정의 헤더를 추가할 수 있습니다. + +```Python hl_lines="10 12-13" +{!../../../docs_src/middleware/tutorial001.py!} +``` + +## 다른 미들웨어 + +미들웨어에 대한 더 많은 정보는 [숙련된 사용자 안내서: 향상된 미들웨어](../advanced/middleware.md){.internal-link target=\_blank}에서 확인할 수 있습니다. + +다음 부분에서 미들웨어와 함께 CORS를 어떻게 다루는지에 대해 확인할 것입니다. diff --git a/docs/ko/docs/tutorial/path-operation-configuration.md b/docs/ko/docs/tutorial/path-operation-configuration.md new file mode 100644 index 0000000000000..411c4349309f1 --- /dev/null +++ b/docs/ko/docs/tutorial/path-operation-configuration.md @@ -0,0 +1,97 @@ +# 경로 작동 설정 + +*경로 작동 데코레이터*를 설정하기 위해서 전달할수 있는 몇 가지 매개변수가 있습니다. + +!!! warning "경고" + 아래 매개변수들은 *경로 작동 함수*가 아닌 *경로 작동 데코레이터*에 직접 전달된다는 사실을 기억하십시오. + +## 응답 상태 코드 + +*경로 작동*의 응답에 사용될 (HTTP) `status_code`를 정의할수 있습니다. + +`404`와 같은 `int`형 코드를 직접 전달할수 있습니다. + +하지만 각 코드의 의미를 모른다면, `status`에 있는 단축 상수들을 사용할수 있습니다: + +```Python hl_lines="3 17" +{!../../../docs_src/path_operation_configuration/tutorial001.py!} +``` + +각 상태 코드들은 응답에 사용되며, OpenAPI 스키마에 추가됩니다. + +!!! note "기술적 세부사항" + 다음과 같이 임포트하셔도 좋습니다. `from starlette import status`. + + **FastAPI**는 개발자 여러분의 편의를 위해서 `starlette.status`와 동일한 `fastapi.status`를 제공합니다. 하지만 Starlette에서 직접 온 것입니다. + +## 태그 + +(보통 단일 `str`인) `str`로 구성된 `list`와 함께 매개변수 `tags`를 전달하여, `경로 작동`에 태그를 추가할 수 있습니다: + +```Python hl_lines="17 22 27" +{!../../../docs_src/path_operation_configuration/tutorial002.py!} +``` + +전달된 태그들은 OpenAPI의 스키마에 추가되며, 자동 문서 인터페이스에서 사용됩니다: + + + +## 요약과 기술 + +`summary`와 `description`을 추가할 수 있습니다: + +```Python hl_lines="20-21" +{!../../../docs_src/path_operation_configuration/tutorial003.py!} +``` + +## 독스트링으로 만든 기술 + +설명은 보통 길어지고 여러 줄에 걸쳐있기 때문에, *경로 작동* 기술을 함수 독스트링 에 선언할 수 있습니다, 이를 **FastAPI**가 독스트링으로부터 읽습니다. + +마크다운 문법으로 독스트링을 작성할 수 있습니다, 작성된 마크다운 형식의 독스트링은 (마크다운의 들여쓰기를 고려하여) 올바르게 화면에 출력됩니다. + +```Python hl_lines="19-27" +{!../../../docs_src/path_operation_configuration/tutorial004.py!} +``` + +이는 대화형 문서에서 사용됩니다: + + + +## 응답 기술 + +`response_description` 매개변수로 응답에 관한 설명을 명시할 수 있습니다: + +```Python hl_lines="21" +{!../../../docs_src/path_operation_configuration/tutorial005.py!} +``` + +!!! info "정보" + `response_description`은 구체적으로 응답을 지칭하며, `description`은 일반적인 *경로 작동*을 지칭합니다. + +!!! check "확인" + OpenAPI는 각 *경로 작동*이 응답에 관한 설명을 요구할 것을 명시합니다. + + 따라서, 응답에 관한 설명이 없을경우, **FastAPI**가 자동으로 "성공 응답" 중 하나를 생성합니다. + + + +## 단일 *경로 작동* 지원중단 + +단일 *경로 작동*을 없애지 않고 지원중단을 해야한다면, `deprecated` 매개변수를 전달하면 됩니다. + +```Python hl_lines="16" +{!../../../docs_src/path_operation_configuration/tutorial006.py!} +``` + +대화형 문서에 지원중단이라고 표시됩니다. + + + +지원중단된 경우와 지원중단 되지 않은 경우에 대한 *경로 작동*이 어떻게 보이는 지 확인하십시오. + + + +## 정리 + +*경로 작동 데코레이터*에 매개변수(들)를 전달함으로 *경로 작동*을 설정하고 메타데이터를 추가할수 있습니다. diff --git a/docs/ko/docs/tutorial/path-params.md b/docs/ko/docs/tutorial/path-params.md index 5cf397e7ae0e2..a75c3cc8cccf3 100644 --- a/docs/ko/docs/tutorial/path-params.md +++ b/docs/ko/docs/tutorial/path-params.md @@ -1,6 +1,6 @@ # 경로 매개변수 -파이썬 포맷 문자열이 사용하는 동일한 문법으로 "매개변수" 또는 "변수"를 경로에 선언할 수 있습니다: +파이썬의 포맷 문자열 리터럴에서 사용되는 문법을 이용하여 경로 "매개변수" 또는 "변수"를 선언할 수 있습니다: ```Python hl_lines="6-7" {!../../../docs_src/path_params/tutorial001.py!} @@ -22,10 +22,10 @@ {!../../../docs_src/path_params/tutorial002.py!} ``` -지금과 같은 경우, `item_id`는 `int`로 선언 되었습니다. +위의 예시에서, `item_id`는 `int`로 선언되었습니다. !!! check "확인" - 이 기능은 함수 내에서 오류 검사, 자동완성 등을 편집기를 지원합니다 + 이 기능은 함수 내에서 오류 검사, 자동완성 등의 편집기 기능을 활용할 수 있게 해줍니다. ## 데이터 변환 @@ -42,7 +42,7 @@ ## 데이터 검증 -하지만 브라우저에서 http://127.0.0.1:8000/items/foo로 이동하면, 멋진 HTTP 오류를 볼 수 있습니다: +하지만 브라우저에서 http://127.0.0.1:8000/items/foo로 이동하면, HTTP 오류가 잘 뜨는 것을 확인할 수 있습니다: ```JSON { @@ -61,12 +61,12 @@ 경로 매개변수 `item_id`는 `int`가 아닌 `"foo"` 값이기 때문입니다. -`int` 대신 `float`을 전달하면 동일한 오류가 나타납니다: http://127.0.0.1:8000/items/4.2 +`int`가 아닌 `float`을 전달하는 경우에도 동일한 오류가 나타납니다: http://127.0.0.1:8000/items/4.2 !!! check "확인" 즉, 파이썬 타입 선언을 하면 **FastAPI**는 데이터 검증을 합니다. - 오류는 검증을 통과하지 못한 지점도 정확하게 명시합니다. + 오류에는 정확히 어느 지점에서 검증을 통과하지 못했는지 명시됩니다. 이는 API와 상호 작용하는 코드를 개발하고 디버깅하는 데 매우 유용합니다. @@ -77,11 +77,11 @@ !!! check "확인" - 다시 한번, 그저 파이썬 타입 선언을 하기만 하면 **FastAPI**는 자동 대화식 API 문서(Swagger UI 통합)를 제공합니다. + 그저 파이썬 타입 선언을 하기만 하면 **FastAPI**는 자동 대화형 API 문서(Swagger UI)를 제공합니다. - 경로 매개변수는 정수형으로 선언됐음을 주목하세요. + 경로 매개변수가 정수형으로 명시된 것을 확인할 수 있습니다. -## 표준 기반의 이점, 대체 문서화 +## 표준 기반의 이점, 대체 문서 그리고 생성된 스키마는 OpenAPI 표준에서 나온 것이기 때문에 호환되는 도구가 많이 있습니다. @@ -89,53 +89,53 @@ -이와 마찬가지로 호환되는 도구가 많이 있습니다. 다양한 언어에 대한 코드 생성 도구를 포함합니다. +이와 마찬가지로 다양한 언어에 대한 코드 생성 도구를 포함하여 여러 호환되는 도구가 있습니다. ## Pydantic -모든 데이터 검증은 Pydantic에 의해 내부적으로 수행되므로 이로 인한 모든 이점을 얻을 수 있습니다. 여러분은 관리를 잘 받고 있음을 느낄 수 있습니다. +모든 데이터 검증은 Pydantic에 의해 내부적으로 수행되므로 이로 인한 이점을 모두 얻을 수 있습니다. 여러분은 관리를 잘 받고 있음을 느낄 수 있습니다. -`str`, `float`, `bool`과 다른 복잡한 데이터 타입 선언을 할 수 있습니다. +`str`, `float`, `bool`, 그리고 다른 여러 복잡한 데이터 타입 선언을 할 수 있습니다. -이 중 몇 가지는 자습서의 다음 장에서 살펴봅니다. +이 중 몇 가지는 자습서의 다음 장에 설명되어 있습니다. ## 순서 문제 -*경로 동작*을 만들때 고정 경로를 갖고 있는 상황들을 맞닦뜨릴 수 있습니다. +*경로 작동*을 만들때 고정 경로를 갖고 있는 상황들을 맞닥뜨릴 수 있습니다. `/users/me`처럼, 현재 사용자의 데이터를 가져온다고 합시다. 사용자 ID를 이용해 특정 사용자의 정보를 가져오는 경로 `/users/{user_id}`도 있습니다. -*경로 동작*은 순차적으로 평가되기 때문에 `/users/{user_id}` 이전에 `/users/me`를 먼저 선언해야 합니다: +*경로 작동*은 순차적으로 실행되기 때문에 `/users/{user_id}` 이전에 `/users/me`를 먼저 선언해야 합니다: ```Python hl_lines="6 11" {!../../../docs_src/path_params/tutorial003.py!} ``` -그렇지 않으면 `/users/{user_id}`는 매개변수 `user_id`의 값을 `"me"`라고 "생각하여" `/users/me`도 연결합니다. +그렇지 않으면 `/users/{user_id}`는 `/users/me` 요청 또한 매개변수 `user_id`의 값이 `"me"`인 것으로 "생각하게" 됩니다. ## 사전정의 값 -만약 *경로 매개변수*를 받는 *경로 동작*이 있지만, 유효하고 미리 정의할 수 있는 *경로 매개변수* 값을 원한다면 파이썬 표준 `Enum`을 사용할 수 있습니다. +만약 *경로 매개변수*를 받는 *경로 작동*이 있지만, *경로 매개변수*로 가능한 값들을 미리 정의하고 싶다면 파이썬 표준 `Enum`을 사용할 수 있습니다. ### `Enum` 클래스 생성 `Enum`을 임포트하고 `str`과 `Enum`을 상속하는 서브 클래스를 만듭니다. -`str`을 상속함으로써 API 문서는 값이 `string` 형이어야 하는 것을 알게 되고 제대로 렌더링 할 수 있게 됩니다. +`str`을 상속함으로써 API 문서는 값이 `string` 형이어야 하는 것을 알게 되고 이는 문서에 제대로 표시됩니다. -고정값으로 사용할 수 있는 유효한 클래스 어트리뷰트를 만듭니다: +가능한 값들에 해당하는 고정된 값의 클래스 어트리뷰트들을 만듭니다: ```Python hl_lines="1 6-9" {!../../../docs_src/path_params/tutorial005.py!} ``` !!! info "정보" - 열거형(또는 enums)은 파이썬 버전 3.4 이후로 사용가능합니다. + 열거형(또는 enums)은 파이썬 버전 3.4 이후로 사용 가능합니다. !!! tip "팁" - 혹시 헷갈린다면, "AlexNet", "ResNet", 그리고 "LeNet"은 그저 기계 학습 모델들의 이름입니다. + 혹시 궁금하다면, "AlexNet", "ResNet", 그리고 "LeNet"은 그저 기계 학습 모델들의 이름입니다. ### *경로 매개변수* 선언 @@ -147,7 +147,7 @@ ### 문서 확인 -*경로 매개변수*에 사용할 수 있는 값은 미리 정의되어 있으므로 대화형 문서에서 멋지게 표시됩니다: +*경로 매개변수*에 사용할 수 있는 값은 미리 정의되어 있으므로 대화형 문서에서 잘 표시됩니다: @@ -157,7 +157,7 @@ #### *열거형 멤버* 비교 -열거체 `ModelName`의 *열거형 멤버*를 비교할 수 있습니다: +열거형 `ModelName`의 *열거형 멤버*를 비교할 수 있습니다: ```Python hl_lines="17" {!../../../docs_src/path_params/tutorial005.py!} @@ -165,7 +165,7 @@ #### *열거형 값* 가져오기 -`model_name.value` 또는 일반적으로 `your_enum_member.value`를 이용하여 실제값(지금의 경우 `str`)을 가져올 수 있습니다: +`model_name.value` 또는 일반적으로 `your_enum_member.value`를 이용하여 실제 값(위 예시의 경우 `str`)을 가져올 수 있습니다: ```Python hl_lines="20" {!../../../docs_src/path_params/tutorial005.py!} @@ -176,7 +176,7 @@ #### *열거형 멤버* 반환 -*경로 동작*에서 중첩 JSON 본문(예: `dict`) 역시 *열거형 멤버*를 반환할 수 있습니다. +*경로 작동*에서 *열거형 멤버*를 반환할 수 있습니다. 이는 중첩 JSON 본문(예: `dict`)내의 값으로도 가능합니다. 클라이언트에 반환하기 전에 해당 값(이 경우 문자열)으로 변환됩니다: @@ -195,50 +195,50 @@ ## 경로를 포함하는 경로 매개변수 -`/files/{file_path}`가 있는 *경로 동작*이 있다고 해봅시다. +경로를 포함하는 *경로 작동* `/files/{file_path}`이 있다고 해봅시다. -그런데 여러분은 `home/johndoe/myfile.txt`처럼 *path*에 들어있는 `file_path` 자체가 필요합니다. +그런데 이 경우 `file_path` 자체가 `home/johndoe/myfile.txt`와 같은 경로를 포함해야 합니다. -따라서 해당 파일의 URL은 다음처럼 됩니다: `/files/home/johndoe/myfile.txt`. +이때 해당 파일의 URL은 다음처럼 됩니다: `/files/home/johndoe/myfile.txt`. ### OpenAPI 지원 테스트와 정의가 어려운 시나리오로 이어질 수 있으므로 OpenAPI는 *경로*를 포함하는 *경로 매개변수*를 내부에 선언하는 방법을 지원하지 않습니다. -그럼에도 Starlette의 내부 도구중 하나를 사용하여 **FastAPI**에서는 할 수 있습니다. +그럼에도 Starlette의 내부 도구중 하나를 사용하여 **FastAPI**에서는 이가 가능합니다. -매개변수에 경로가 포함되어야 한다는 문서를 추가하지 않아도 문서는 계속 작동합니다. +문서에 매개변수에 경로가 포함되어야 한다는 정보가 명시되지는 않지만 여전히 작동합니다. ### 경로 변환기 -Starlette에서 직접 옵션을 사용하면 다음과 같은 URL을 사용하여 *path*를 포함하는 *경로 매개변수*를 선언 할 수 있습니다: +Starlette의 옵션을 직접 이용하여 다음과 같은 URL을 사용함으로써 *path*를 포함하는 *경로 매개변수*를 선언할 수 있습니다: ``` /files/{file_path:path} ``` -이러한 경우 매개변수의 이름은 `file_path`이고 마지막 부분 `:path`는 매개변수가 *경로*와 일치해야함을 알려줍니다. +이러한 경우 매개변수의 이름은 `file_path`이며, 마지막 부분 `:path`는 매개변수가 *경로*와 일치해야 함을 명시합니다. -그러므로 다음과 같이 사용할 수 있습니다: +따라서 다음과 같이 사용할 수 있습니다: ```Python hl_lines="6" {!../../../docs_src/path_params/tutorial004.py!} ``` !!! tip "팁" - 매개변수가 `/home/johndoe/myfile.txt`를 갖고 있어 슬래시로 시작(`/`)해야 할 수 있습니다. + 매개변수가 가져야 하는 값이 `/home/johndoe/myfile.txt`와 같이 슬래시로 시작(`/`)해야 할 수 있습니다. 이 경우 URL은: `/files//home/johndoe/myfile.txt`이며 `files`과 `home` 사이에 이중 슬래시(`//`)가 생깁니다. ## 요약 -**FastAPI**과 함께라면 짧고 직관적인 표준 파이썬 타입 선언을 사용하여 다음을 얻을 수 있습니다: +**FastAPI**를 이용하면 짧고 직관적인 표준 파이썬 타입 선언을 사용하여 다음을 얻을 수 있습니다: * 편집기 지원: 오류 검사, 자동완성 등 * 데이터 "파싱" * 데이터 검증 * API 주석(Annotation)과 자동 문서 -위 사항들을 그저 한번에 선언하면 됩니다. +단 한번의 선언만으로 위 사항들을 모두 선언할 수 있습니다. -이는 (원래 성능과는 별개로) 대체 프레임워크와 비교했을 때 **FastAPI**의 주요 가시적 장점일 것입니다. +이는 대체 프레임워크와 비교했을 때 (엄청나게 빠른 성능 외에도) **FastAPI**의 주요한 장점일 것입니다. diff --git a/docs/ko/docs/tutorial/query-params-str-validations.md b/docs/ko/docs/tutorial/query-params-str-validations.md new file mode 100644 index 0000000000000..2e6396cccf306 --- /dev/null +++ b/docs/ko/docs/tutorial/query-params-str-validations.md @@ -0,0 +1,303 @@ +# 쿼리 매개변수와 문자열 검증 + +**FastAPI**를 사용하면 매개변수에 대한 추가 정보 및 검증을 선언할 수 있습니다. + +이 응용 프로그램을 예로 들어보겠습니다: + +```Python hl_lines="9" +{!../../../docs_src/query_params_str_validations/tutorial001.py!} +``` + +쿼리 매개변수 `q`는 `Optional[str]` 자료형입니다. 즉, `str` 자료형이지만 `None` 역시 될 수 있음을 뜻하고, 실제로 기본값은 `None`이기 때문에 FastAPI는 이 매개변수가 필수가 아니라는 것을 압니다. + +!!! note "참고" + FastAPI는 `q`의 기본값이 `= None`이기 때문에 필수가 아님을 압니다. + + `Optional[str]`에 있는 `Optional`은 FastAPI가 사용하는게 아니지만, 편집기에게 더 나은 지원과 오류 탐지를 제공하게 해줍니다. + +## 추가 검증 + +`q`가 선택적이지만 값이 주어질 때마다 **값이 50 글자를 초과하지 않게** 강제하려 합니다. + +### `Query` 임포트 + +이를 위해 먼저 `fastapi`에서 `Query`를 임포트합니다: + +```Python hl_lines="3" +{!../../../docs_src/query_params_str_validations/tutorial002.py!} +``` + +## 기본값으로 `Query` 사용 + +이제 `Query`를 매개변수의 기본값으로 사용하여 `max_length` 매개변수를 50으로 설정합니다: + +```Python hl_lines="9" +{!../../../docs_src/query_params_str_validations/tutorial002.py!} +``` + +기본값 `None`을 `Query(None)`으로 바꿔야 하므로, `Query`의 첫 번째 매개변수는 기본값을 정의하는 것과 같은 목적으로 사용됩니다. + +그러므로: + +```Python +q: Optional[str] = Query(None) +``` + +...위 코드는 아래와 동일하게 매개변수를 선택적으로 만듭니다: + +```Python +q: Optional[str] = None +``` + +하지만 명시적으로 쿼리 매개변수를 선언합니다. + +!!! info "정보" + FastAPI는 다음 부분에 관심이 있습니다: + + ```Python + = None + ``` + + 또는: + + ```Python + = Query(None) + ``` + + 그리고 `None`을 사용하여 쿼라 매개변수가 필수적이지 않다는 것을 파악합니다. + + `Optional` 부분은 편집기에게 더 나은 지원을 제공하기 위해서만 사용됩니다. + +또한 `Query`로 더 많은 매개변수를 전달할 수 있습니다. 지금의 경우 문자열에 적용되는 `max_length` 매개변수입니다: + +```Python +q: str = Query(None, max_length=50) +``` + +이는 데이터를 검증할 것이고, 데이터가 유효하지 않다면 명백한 오류를 보여주며, OpenAPI 스키마 *경로 작동*에 매개변수를 문서화 합니다. + +## 검증 추가 + +매개변수 `min_length` 또한 추가할 수 있습니다: + +```Python hl_lines="9" +{!../../../docs_src/query_params_str_validations/tutorial003.py!} +``` + +## 정규식 추가 + +매개변수와 일치해야 하는 정규표현식을 정의할 수 있습니다: + +```Python hl_lines="10" +{!../../../docs_src/query_params_str_validations/tutorial004.py!} +``` + +이 특정 정규표현식은 전달 받은 매개변수 값을 검사합니다: + +* `^`: 이전에 문자가 없고 뒤따르는 문자로 시작합니다. +* `fixedquery`: 정확히 `fixedquery` 값을 갖습니다. +* `$`: 여기서 끝나고 `fixedquery` 이후로 아무 문자도 갖지 않습니다. + +**"정규표현식"** 개념에 대해 상실감을 느꼈다면 걱정하지 않아도 됩니다. 많은 사람에게 어려운 주제입니다. 아직은 정규표현식 없이도 많은 작업들을 할 수 있습니다. + +하지만 언제든지 가서 배울수 있고, **FastAPI**에서 직접 사용할 수 있다는 사실을 알고 있어야 합니다. + +## 기본값 + +기본값으로 사용하는 첫 번째 인자로 `None`을 전달하듯이, 다른 값을 전달할 수 있습니다. + +`min_length`가 `3`이고, 기본값이 `"fixedquery"`인 쿼리 매개변수 `q`를 선언해봅시다: + +```Python hl_lines="7" +{!../../../docs_src/query_params_str_validations/tutorial005.py!} +``` + +!!! note "참고" + 기본값을 갖는 것만으로 매개변수는 선택적이 됩니다. + +## 필수로 만들기 + +더 많은 검증이나 메타데이터를 선언할 필요가 없는 경우, 다음과 같이 기본값을 선언하지 않고 쿼리 매개변수 `q`를 필수로 만들 수 있습니다: + +```Python +q: str +``` + +아래 대신: + +```Python +q: Optional[str] = None +``` + +그러나 이제 다음과 같이 `Query`로 선언합니다: + +```Python +q: Optional[str] = Query(None, min_length=3) +``` + +그래서 `Query`를 필수값으로 만들어야 할 때면, 첫 번째 인자로 `...`를 사용할 수 있습니다: + +```Python hl_lines="7" +{!../../../docs_src/query_params_str_validations/tutorial006.py!} +``` + +!!! info "정보" + 이전에 `...`를 본적이 없다면: 특별한 단일값으로, 파이썬의 일부이며 "Ellipsis"라 부릅니다. + +이렇게 하면 **FastAPI**가 이 매개변수는 필수임을 알 수 있습니다. + +## 쿼리 매개변수 리스트 / 다중값 + +쿼리 매개변수를 `Query`와 함께 명시적으로 선언할 때, 값들의 리스트나 다른 방법으로 여러 값을 받도록 선언 할 수도 있습니다. + +예를 들어, URL에서 여러번 나오는 `q` 쿼리 매개변수를 선언하려면 다음과 같이 작성할 수 있습니다: + +```Python hl_lines="9" +{!../../../docs_src/query_params_str_validations/tutorial011.py!} +``` + +아래와 같은 URL을 사용합니다: + +``` +http://localhost:8000/items/?q=foo&q=bar +``` + +여러 `q` *쿼리 매개변수* 값들을 (`foo` 및 `bar`) 파이썬 `list`로 *경로 작동 함수* 내 *함수 매개변수* `q`로 전달 받습니다. + +따라서 해당 URL에 대한 응답은 다음과 같습니다: + +```JSON +{ + "q": [ + "foo", + "bar" + ] +} +``` + +!!! tip "팁" + 위의 예와 같이 `list` 자료형으로 쿼리 매개변수를 선언하려면 `Query`를 명시적으로 사용해야 합니다. 그렇지 않으면 요청 본문으로 해석됩니다. + +대화형 API 문서는 여러 값을 허용하도록 수정 됩니다: + + + +### 쿼리 매개변수 리스트 / 기본값을 사용하는 다중값 + +그리고 제공된 값이 없으면 기본 `list` 값을 정의할 수도 있습니다: + +```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[str]` 대신 `list`를 직접 사용할 수도 있습니다: + +```Python hl_lines="7" +{!../../../docs_src/query_params_str_validations/tutorial013.py!} +``` + +!!! note "참고" + 이 경우 FastAPI는 리스트의 내용을 검사하지 않음을 명심하기 바랍니다. + + 예를 들어, `List[int]`는 리스트 내용이 정수인지 검사(및 문서화)합니다. 하지만 `list` 단독일 경우는 아닙니다. + +## 더 많은 메타데이터 선언 + +매개변수에 대한 정보를 추가할 수 있습니다. + +해당 정보는 생성된 OpenAPI에 포함되고 문서 사용자 인터페이스 및 외부 도구에서 사용됩니다. + +!!! note "참고" + 도구에 따라 OpenAPI 지원 수준이 다를 수 있음을 명심하기 바랍니다. + + 일부는 아직 선언된 추가 정보를 모두 표시하지 않을 수 있지만, 대부분의 경우 누락된 기능은 이미 개발 계획이 있습니다. + +`title`을 추가할 수 있습니다: + +```Python hl_lines="10" +{!../../../docs_src/query_params_str_validations/tutorial007.py!} +``` + +그리고 `description`도 추가할 수 있습니다: + +```Python hl_lines="13" +{!../../../docs_src/query_params_str_validations/tutorial008.py!} +``` + +## 별칭 매개변수 + +매개변수가 `item-query`이길 원한다고 가정해 봅시다. + +마치 다음과 같습니다: + +``` +http://127.0.0.1:8000/items/?item-query=foobaritems +``` + +그러나 `item-query`은 유효한 파이썬 변수 이름이 아닙니다. + +가장 가까운 것은 `item_query`일 겁니다. + +하지만 정확히`item-query`이길 원합니다... + +이럴 경우 `alias`를 선언할 수 있으며, 해당 별칭은 매개변수 값을 찾는 데 사용됩니다: + +```Python hl_lines="9" +{!../../../docs_src/query_params_str_validations/tutorial009.py!} +``` + +## 매개변수 사용하지 않게 하기 + +이제는 더이상 이 매개변수를 마음에 들어하지 않는다고 가정해 봅시다. + +이 매개변수를 사용하는 클라이언트가 있기 때문에 한동안은 남겨둬야 하지만, 사용되지 않는다(deprecated)고 확실하게 문서에서 보여주고 싶습니다. + +그렇다면 `deprecated=True` 매개변수를 `Query`로 전달합니다: + +```Python hl_lines="18" +{!../../../docs_src/query_params_str_validations/tutorial010.py!} +``` + +문서가 아래와 같이 보일겁니다: + + + +## 요약 + +매개변수에 검증과 메타데이터를 추가 선언할 수 있습니다. + +제네릭 검증과 메타데이터: + +* `alias` +* `title` +* `description` +* `deprecated` + +특정 문자열 검증: + +* `min_length` +* `max_length` +* `regex` + +예제에서 `str` 값의 검증을 어떻게 추가하는지 살펴보았습니다. + +숫자와 같은 다른 자료형에 대한 검증을 어떻게 선언하는지 확인하려면 다음 장을 확인하기 바랍니다. diff --git a/docs/ko/docs/tutorial/query-params.md b/docs/ko/docs/tutorial/query-params.md index bb631e6ffc310..8c7f9167b0069 100644 --- a/docs/ko/docs/tutorial/query-params.md +++ b/docs/ko/docs/tutorial/query-params.md @@ -1,6 +1,6 @@ # 쿼리 매개변수 -경로 매개변수의 일부가 아닌 다른 함수 매개변수를 선언할 때, "쿼리" 매개변수로 자동 해석합니다. +경로 매개변수의 일부가 아닌 다른 함수 매개변수를 선언하면 "쿼리" 매개변수로 자동 해석합니다. ```Python hl_lines="9" {!../../../docs_src/query_params/tutorial001.py!} @@ -8,7 +8,7 @@ 쿼리는 URL에서 `?` 후에 나오고 `&`으로 구분되는 키-값 쌍의 집합입니다. -예를 들어, URL에서: +예를 들어, 아래 URL에서: ``` http://127.0.0.1:8000/items/?skip=0&limit=10 @@ -21,7 +21,7 @@ http://127.0.0.1:8000/items/?skip=0&limit=10 URL의 일부이므로 "자연스럽게" 문자열입니다. -하지만 파이썬 타입과 함께 선언할 경우(위 예에서 `int`), 해당 타입으로 변환되고 이에 대해 검증합니다. +하지만 파이썬 타입과 함께 선언할 경우(위 예에서 `int`), 해당 타입으로 변환 및 검증됩니다. 경로 매개변수에 적용된 동일한 프로세스가 쿼리 매개변수에도 적용됩니다: @@ -36,13 +36,13 @@ URL의 일부이므로 "자연스럽게" 문자열입니다. 위 예에서 `skip=0`과 `limit=10`은 기본값을 갖고 있습니다. -그러므로 URL로 이동하면: +그러므로 URL로 이동하는 것은: ``` http://127.0.0.1:8000/items/ ``` -아래로 이동한 것과 같습니다: +아래로 이동하는 것과 같습니다: ``` http://127.0.0.1:8000/items/?skip=0&limit=10 @@ -136,7 +136,7 @@ http://127.0.0.1:8000/items/foo?short=yes 특정값을 추가하지 않고 선택적으로 만들기 위해선 기본값을 `None`으로 설정하면 됩니다. -그러나 쿼리 매개변수를 필수로 만들려면 기본값을 선언할 수 없습니다: +그러나 쿼리 매개변수를 필수로 만들려면 단순히 기본값을 선언하지 않으면 됩니다: ```Python hl_lines="6-7" {!../../../docs_src/query_params/tutorial005.py!} @@ -144,7 +144,7 @@ http://127.0.0.1:8000/items/foo?short=yes 여기 쿼리 매개변수 `needy`는 `str`형인 필수 쿼리 매개변수입니다. -브라우저에서 URL을 아래처럼 연다면: +브라우저에서 아래와 같은 URL을 연다면: ``` http://127.0.0.1:8000/items/foo-item @@ -188,7 +188,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy {!../../../docs_src/query_params/tutorial006.py!} ``` -이 경우 3가지 쿼리 매개변수가 있습니다: +위 예시에서는 3가지 쿼리 매개변수가 있습니다: * `needy`, 필수적인 `str`. * `skip`, 기본값이 `0`인 `int`. diff --git a/docs/ko/docs/tutorial/request-files.md b/docs/ko/docs/tutorial/request-files.md index decefe981fef7..468c46283d1e1 100644 --- a/docs/ko/docs/tutorial/request-files.md +++ b/docs/ko/docs/tutorial/request-files.md @@ -3,7 +3,7 @@ `File`을 사용하여 클라이언트가 업로드할 파일들을 정의할 수 있습니다. !!! info "정보" - 업로드된 파일을 전달받기 위해 먼저 `python-multipart`를 설치해야합니다. + 업로드된 파일을 전달받기 위해 먼저 `python-multipart`를 설치해야합니다. 예시) `pip install python-multipart`. @@ -108,7 +108,7 @@ HTML의 폼들(`
`)이 서버에 데이터를 전송하는 방식은 인코딩과 폼 필드에 대해 더 알고싶다면, POST에 관한MDN웹 문서 를 참고하기 바랍니다,. -!!! warning "주의" +!!! warning "경고" 다수의 `File` 과 `Form` 매개변수를 한 *경로 작동*에 선언하는 것이 가능하지만, 요청의 본문이 `application/json` 가 아닌 `multipart/form-data` 로 인코딩 되기 때문에 JSON으로 받아야하는 `Body` 필드를 함께 선언할 수는 없습니다. 이는 **FastAPI**의 한계가 아니라, HTTP 프로토콜에 의한 것입니다. diff --git a/docs/ko/docs/tutorial/request-forms-and-files.md b/docs/ko/docs/tutorial/request-forms-and-files.md index ddf232e7fedd4..bd5f41918768e 100644 --- a/docs/ko/docs/tutorial/request-forms-and-files.md +++ b/docs/ko/docs/tutorial/request-forms-and-files.md @@ -3,7 +3,7 @@ `File` 과 `Form` 을 사용하여 파일과 폼을 함께 정의할 수 있습니다. !!! info "정보" - 파일과 폼 데이터를 함께, 또는 각각 업로드하기 위해 먼저 `python-multipart`를 설치해야합니다. + 파일과 폼 데이터를 함께, 또는 각각 업로드하기 위해 먼저 `python-multipart`를 설치해야합니다. 예 ) `pip install python-multipart`. @@ -25,7 +25,7 @@ 어떤 파일들은 `bytes`로, 또 어떤 파일들은 `UploadFile`로 선언할 수 있습니다. -!!! warning "주의" +!!! warning "경고" 다수의 `File`과 `Form` 매개변수를 한 *경로 작동*에 선언하는 것이 가능하지만, 요청의 본문이 `application/json`가 아닌 `multipart/form-data`로 인코딩 되기 때문에 JSON으로 받아야하는 `Body` 필드를 함께 선언할 수는 없습니다. 이는 **FastAPI**의 한계가 아니라, HTTP 프로토콜에 의한 것입니다. diff --git a/docs/ko/docs/tutorial/response-model.md b/docs/ko/docs/tutorial/response-model.md new file mode 100644 index 0000000000000..feff88a4262d3 --- /dev/null +++ b/docs/ko/docs/tutorial/response-model.md @@ -0,0 +1,210 @@ +# 응답 모델 + +어떤 *경로 작동*이든 매개변수 `response_model`를 사용하여 응답을 위한 모델을 선언할 수 있습니다: + +* `@app.get()` +* `@app.post()` +* `@app.put()` +* `@app.delete()` +* 기타. + +```Python hl_lines="17" +{!../../../docs_src/response_model/tutorial001.py!} +``` + +!!! note "참고" + `response_model`은 "데코레이터" 메소드(`get`, `post`, 등)의 매개변수입니다. 모든 매개변수들과 본문(body)처럼 *경로 작동 함수*가 아닙니다. + +Pydantic 모델 어트리뷰트를 선언한 것과 동일한 타입을 수신하므로 Pydantic 모델이 될 수 있지만, `List[Item]`과 같이 Pydantic 모델들의 `list`일 수도 있습니다. + +FastAPI는 이 `response_model`를 사용하여: + +* 출력 데이터를 타입 선언으로 변환. +* 데이터 검증. +* OpenAPI *경로 작동*의 응답에 JSON 스키마 추가. +* 자동 생성 문서 시스템에 사용. + +하지만 가장 중요한 것은: + +* 해당 모델의 출력 데이터 제한. 이것이 얼마나 중요한지 아래에서 볼 것입니다. + +!!! note "기술 세부사항" + 응답 모델은 함수의 타입 어노테이션 대신 이 매개변수로 선언하는데, 경로 함수가 실제 응답 모델을 반환하지 않고 `dict`, 데이터베이스 객체나 기타 다른 모델을 `response_model`을 사용하여 필드 제한과 직렬화를 수행하고 반환할 수 있기 때문입니다 + +## 동일한 입력 데이터 반환 + +여기서 우리는 평문 비밀번호를 포함하는 `UserIn` 모델을 선언합니다: + +```Python hl_lines="9 11" +{!../../../docs_src/response_model/tutorial002.py!} +``` + +그리고 이 모델을 사용하여 입력을 선언하고 같은 모델로 출력을 선언합니다: + +```Python hl_lines="17-18" +{!../../../docs_src/response_model/tutorial002.py!} +``` + +이제 브라우저가 비밀번호로 사용자를 만들 때마다 API는 응답으로 동일한 비밀번호를 반환합니다. + +이 경우, 사용자가 스스로 비밀번호를 발신했기 때문에 문제가 되지 않을 수 있습니다. + +그러나 동일한 모델을 다른 *경로 작동*에서 사용할 경우, 모든 클라이언트에게 사용자의 비밀번호를 발신할 수 있습니다. + +!!! danger "위험" + 절대로 사용자의 평문 비밀번호를 저장하거나 응답으로 발신하지 마십시오. + +## 출력 모델 추가 + +대신 평문 비밀번호로 입력 모델을 만들고 해당 비밀번호 없이 출력 모델을 만들 수 있습니다: + +```Python hl_lines="9 11 16" +{!../../../docs_src/response_model/tutorial003.py!} +``` + +여기서 *경로 작동 함수*가 비밀번호를 포함하는 동일한 입력 사용자를 반환할지라도: + +```Python hl_lines="24" +{!../../../docs_src/response_model/tutorial003.py!} +``` + +...`response_model`을 `UserOut` 모델로 선언했기 때문에 비밀번호를 포함하지 않습니다: + +```Python hl_lines="22" +{!../../../docs_src/response_model/tutorial003.py!} +``` + +따라서 **FastAPI**는 출력 모델에서 선언하지 않은 모든 데이터를 (Pydantic을 사용하여) 필터링합니다. + +## 문서에서 보기 + +자동 생성 문서를 보면 입력 모델과 출력 모델이 각자의 JSON 스키마를 가지고 있음을 확인할 수 있습니다: + + + +그리고 두 모델 모두 대화형 API 문서에 사용됩니다: + + + +## 응답 모델 인코딩 매개변수 + +응답 모델은 아래와 같이 기본값을 가질 수 있습니다: + +```Python hl_lines="11 13-14" +{!../../../docs_src/response_model/tutorial004.py!} +``` + +* `description: Optional[str] = None`은 기본값으로 `None`을 갖습니다. +* `tax: float = 10.5`는 기본값으로 `10.5`를 갖습니다. +* `tags: List[str] = []` 빈 리스트의 기본값으로: `[]`. + +그러나 실제로 저장되지 않았을 경우 결과에서 값을 생략하고 싶을 수 있습니다. + +예를 들어, NoSQL 데이터베이스에 많은 선택적 속성이 있는 모델이 있지만, 기본값으로 가득 찬 매우 긴 JSON 응답을 보내고 싶지 않습니다. + +### `response_model_exclude_unset` 매개변수 사용 + +*경로 작동 데코레이터* 매개변수를 `response_model_exclude_unset=True`로 설정 할 수 있습니다: + +```Python hl_lines="24" +{!../../../docs_src/response_model/tutorial004.py!} +``` + +이러한 기본값은 응답에 포함되지 않고 실제로 설정된 값만 포함됩니다. + +따라서 해당 *경로 작동*에 ID가 `foo`인 항목(items)을 요청으로 보내면 (기본값을 제외한) 응답은 다음과 같습니다: + +```JSON +{ + "name": "Foo", + "price": 50.2 +} +``` + +!!! info "정보" + FastAPI는 이를 위해 Pydantic 모델의 `.dict()`의 `exclude_unset` 매개변수를 사용합니다. + +!!! info "정보" + 아래 또한 사용할 수 있습니다: + + * `response_model_exclude_defaults=True` + * `response_model_exclude_none=True` + + Pydantic 문서에서 `exclude_defaults` 및 `exclude_none`에 대해 설명한 대로 사용할 수 있습니다. + +#### 기본값이 있는 필드를 갖는 값의 데이터 + +하지만 모델의 필드가 기본값이 있어도 ID가 `bar`인 항목(items)처럼 데이터가 값을 갖는다면: + +```Python hl_lines="3 5" +{ + "name": "Bar", + "description": "The bartenders", + "price": 62, + "tax": 20.2 +} +``` + +응답에 해당 값들이 포함됩니다. + +#### 기본값과 동일한 값을 갖는 데이터 + +If the data has the same values as the default ones, like the item with ID `baz`: +ID가 `baz`인 항목(items)처럼 기본값과 동일한 값을 갖는다면: + +```Python hl_lines="3 5-6" +{ + "name": "Baz", + "description": None, + "price": 50.2, + "tax": 10.5, + "tags": [] +} +``` + +`description`, `tax` 그리고 `tags`가 기본값과 같더라도 (기본값에서 가져오는 대신) 값들이 명시적으로 설정되었다는 것을 인지할 정도로 FastAPI는 충분히 똑똑합니다(사실, Pydantic이 충분히 똑똑합니다). + +따라서 JSON 스키마에 포함됩니다. + +!!! tip "팁" + `None` 뿐만 아니라 다른 어떤 것도 기본값이 될 수 있습니다. + + 리스트(`[]`), `float`인 `10.5` 등이 될 수 있습니다. + +### `response_model_include` 및 `response_model_exclude` + +*경로 작동 데코레이터* 매개변수 `response_model_include` 및 `response_model_exclude`를 사용할 수 있습니다. + +이들은 포함(나머지 생략)하거나 제외(나머지 포함) 할 어트리뷰트의 이름과 `str`의 `set`을 받습니다. + +Pydantic 모델이 하나만 있고 출력에서 ​​일부 데이터를 제거하려는 경우 빠른 지름길로 사용할 수 있습니다. + +!!! tip "팁" + 하지만 이러한 매개변수 대신 여러 클래스를 사용하여 위 아이디어를 사용하는 것을 추천합니다. + + 이는 일부 어트리뷰트를 생략하기 위해 `response_model_include` 또는 `response_model_exclude`를 사용하더라도 앱의 OpenAPI(및 문서)가 생성한 JSON 스키마가 여전히 전체 모델에 대한 스키마이기 때문입니다. + + 비슷하게 작동하는 `response_model_by_alias` 역시 마찬가지로 적용됩니다. + +```Python hl_lines="31 37" +{!../../../docs_src/response_model/tutorial005.py!} +``` + +!!! tip "팁" + 문법 `{"name", "description"}`은 두 값을 갖는 `set`을 만듭니다. + + 이는 `set(["name", "description"])`과 동일합니다. + +#### `set` 대신 `list` 사용하기 + +`list` 또는 `tuple` 대신 `set`을 사용하는 법을 잊었더라도, FastAPI는 `set`으로 변환하고 정상적으로 작동합니다: + +```Python hl_lines="31 37" +{!../../../docs_src/response_model/tutorial006.py!} +``` + +## 요약 + +응답 모델을 정의하고 개인정보가 필터되는 것을 보장하기 위해 *경로 작동 데코레이터*의 매개변수 `response_model`을 사용하세요. + +명시적으로 설정된 값만 반환하려면 `response_model_exclude_unset`을 사용하세요. diff --git a/docs/ko/docs/tutorial/schema-extra-example.md b/docs/ko/docs/tutorial/schema-extra-example.md new file mode 100644 index 0000000000000..4e319e07554dc --- /dev/null +++ b/docs/ko/docs/tutorial/schema-extra-example.md @@ -0,0 +1,326 @@ +# 요청 예제 데이터 선언 + +여러분의 앱이 받을 수 있는 데이터 예제를 선언할 수 있습니다. + +여기 이를 위한 몇가지 방식이 있습니다. + +## Pydantic 모델 속 추가 JSON 스키마 데이터 + +생성된 JSON 스키마에 추가될 Pydantic 모델을 위한 `examples`을 선언할 수 있습니다. + +=== "Python 3.10+ Pydantic v2" + + ```Python hl_lines="13-24" + {!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!} + ``` + +=== "Python 3.10+ Pydantic v1" + + ```Python hl_lines="13-23" + {!> ../../../docs_src/schema_extra_example/tutorial001_py310_pv1.py!} + ``` + +=== "Python 3.8+ Pydantic v2" + + ```Python hl_lines="15-26" + {!> ../../../docs_src/schema_extra_example/tutorial001.py!} + ``` + +=== "Python 3.8+ Pydantic v1" + + ```Python hl_lines="15-25" + {!> ../../../docs_src/schema_extra_example/tutorial001_pv1.py!} + ``` + +추가 정보는 있는 그대로 해당 모델의 **JSON 스키마** 결과에 추가되고, API 문서에서 사용합니다. + +=== "Pydantic v2" + + Pydantic 버전 2에서 Pydantic 공식 문서: Model Config에 나와 있는 것처럼 `dict`를 받는 `model_config` 어트리뷰트를 사용할 것입니다. + + `"json_schema_extra"`를 생성된 JSON 스키마에서 보여주고 싶은 별도의 데이터와 `examples`를 포함하는 `dict`으로 설정할 수 있습니다. + +=== "Pydantic v1" + + Pydantic v1에서 Pydantic 공식 문서: Schema customization에서 설명하는 것처럼, 내부 클래스인 `Config`와 `schema_extra`를 사용할 것입니다. + + `schema_extra`를 생성된 JSON 스키마에서 보여주고 싶은 별도의 데이터와 `examples`를 포함하는 `dict`으로 설정할 수 있습니다. + +!!! tip "팁" + JSON 스키마를 확장하고 여러분의 별도의 자체 데이터를 추가하기 위해 같은 기술을 사용할 수 있습니다. + + 예를 들면, 프론트엔드 사용자 인터페이스에 메타데이터를 추가하는 등에 사용할 수 있습니다. + +!!! info "정보" + (FastAPI 0.99.0부터 쓰이기 시작한) OpenAPI 3.1.0은 **JSON 스키마** 표준의 일부인 `examples`에 대한 지원을 추가했습니다. + + 그 전에는, 하나의 예제만 가능한 `example` 키워드만 지원했습니다. 이는 아직 OpenAPI 3.1.0에서 지원하지만, 지원이 종료될 것이며 JSON 스키마 표준에 포함되지 않습니다. 그렇기에 `example`을 `examples`으로 이전하는 것을 추천합니다. 🤓 + + 이 문서 끝에 더 많은 읽을거리가 있습니다. + +## `Field` 추가 인자 + +Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 선언할 수 있습니다: + +=== "Python 3.10+" + + ```Python hl_lines="2 8-11" + {!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="4 10-13" + {!> ../../../docs_src/schema_extra_example/tutorial002.py!} + ``` + +## JSON Schema에서의 `examples` - OpenAPI + +이들 중에서 사용합니다: + +* `Path()` +* `Query()` +* `Header()` +* `Cookie()` +* `Body()` +* `Form()` +* `File()` + +**OpenAPI**의 **JSON 스키마**에 추가될 부가적인 정보를 포함한 `examples` 모음을 선언할 수 있습니다. + +### `examples`를 포함한 `Body` + +여기, `Body()`에 예상되는 예제 데이터 하나를 포함한 `examples`를 넘겼습니다: + +=== "Python 3.10+" + + ```Python hl_lines="22-29" + {!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="22-29" + {!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="23-30" + {!> ../../../docs_src/schema_extra_example/tutorial003_an.py!} + ``` + +=== "Python 3.10+ Annotated가 없는 경우" + + !!! tip "팁" + 가능하다면 `Annotated`가 달린 버전을 권장합니다. + + ```Python hl_lines="18-25" + {!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!} + ``` + +=== "Python 3.8+ Annotated가 없는 경우" + + !!! tip "팁" + 가능하다면 `Annotated`가 달린 버전을 권장합니다. + + ```Python hl_lines="20-27" + {!> ../../../docs_src/schema_extra_example/tutorial003.py!} + ``` + +### 문서 UI 예시 + +위의 어느 방법과 함께라면 `/docs`에서 다음과 같이 보일 것입니다: + + + +### 다중 `examples`를 포함한 `Body` + +물론 여러 `examples`를 넘길 수 있습니다: + +=== "Python 3.10+" + + ```Python hl_lines="23-38" + {!> ../../../docs_src/schema_extra_example/tutorial004_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="23-38" + {!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="24-39" + {!> ../../../docs_src/schema_extra_example/tutorial004_an.py!} + ``` + +=== "Python 3.10+ Annotated가 없는 경우" + + !!! tip "팁" + 가능하다면 `Annotated`가 달린 버전을 권장합니다. + + ```Python hl_lines="19-34" + {!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!} + ``` + +=== "Python 3.8+ Annotated가 없는 경우" + + !!! tip "팁" + 가능하다면 `Annotated`가 달린 버전을 권장합니다. + + ```Python hl_lines="21-36" + {!> ../../../docs_src/schema_extra_example/tutorial004.py!} + ``` + +이와 같이 하면 이 예제는 그 본문 데이터를 위한 내부 **JSON 스키마**의 일부가 될 것입니다. + +그럼에도 불구하고, 지금 이 문서를 작성하는 시간에, 문서 UI를 보여주는 역할을 맡은 Swagger UI는 **JSON 스키마** 속 데이터를 위한 여러 예제의 표현을 지원하지 않습니다. 하지만 해결 방안을 밑에서 읽어보세요. + +### OpenAPI-특화 `examples` + +**JSON 스키마**가 `examples`를 지원하기 전 부터, OpenAPI는 `examples`이라 불리는 다른 필드를 지원해 왔습니다. + +이 **OpenAPI-특화** `examples`는 OpenAPI 명세서의 다른 구역으로 들어갑니다. 각 JSON 스키마 내부가 아니라 **각 *경로 작동* 세부 정보**에 포함됩니다. + +그리고 Swagger UI는 이 특정한 `examples` 필드를 한동안 지원했습니다. 그래서, 이를 다른 **문서 UI에 있는 예제**를 **표시**하기 위해 사용할 수 있습니다. + +이 OpenAPI-특화 필드인 `examples`의 형태는 (`list`대신에) **다중 예제**가 포함된 `dict`이며, 각각의 별도 정보 또한 **OpenAPI**에 추가될 것입니다. + +이는 OpenAPI에 포함된 JSON 스키마 안으로 포함되지 않으며, *경로 작동*에 직접적으로 포함됩니다. + +### `openapi_examples` 매개변수 사용하기 + +다음 예시 속에 OpenAPI-특화 `examples`를 FastAPI 안에서 매개변수 `openapi_examples` 매개변수와 함께 선언할 수 있습니다: + +* `Path()` +* `Query()` +* `Header()` +* `Cookie()` +* `Body()` +* `Form()` +* `File()` + +`dict`의 키가 또 다른 `dict`인 각 예제와 값을 구별합니다. + +각각의 특정 `examples` 속 `dict` 예제는 다음을 포함할 수 있습니다: + +* `summary`: 예제에 대한 짧은 설명문. +* `description`: 마크다운 텍스트를 포함할 수 있는 긴 설명문. +* `value`: 실제로 보여지는 예시, 예를 들면 `dict`. +* `externalValue`: `value`의 대안이며 예제를 가르키는 URL. 비록 `value`처럼 많은 도구를 지원하지 못할 수 있습니다. + +이를 다음과 같이 사용할 수 있습니다: + +=== "Python 3.10+" + + ```Python hl_lines="23-49" + {!> ../../../docs_src/schema_extra_example/tutorial005_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="23-49" + {!> ../../../docs_src/schema_extra_example/tutorial005_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="24-50" + {!> ../../../docs_src/schema_extra_example/tutorial005_an.py!} + ``` + +=== "Python 3.10+ Annotated가 없는 경우" + + !!! tip "팁" + 가능하다면 `Annotated`가 달린 버전을 권장합니다. + + ```Python hl_lines="19-45" + {!> ../../../docs_src/schema_extra_example/tutorial005_py310.py!} + ``` + +=== "Python 3.8+ Annotated가 없는 경우" + + !!! tip "팁" + 가능하다면 `Annotated`가 달린 버전을 권장합니다. + + ```Python hl_lines="21-47" + {!> ../../../docs_src/schema_extra_example/tutorial005.py!} + ``` + +### 문서 UI에서의 OpenAPI 예시 + +`Body()`에 추가된 `openapi_examples`를 포함한 `/docs`는 다음과 같이 보일 것입니다: + + + +## 기술적 세부 사항 + +!!! tip "팁" + 이미 **FastAPI**의 **0.99.0 혹은 그 이상** 버전을 사용하고 있다면, 이 세부 사항을 **스킵**해도 상관 없을 것입니다. + + 세부 사항은 OpenAPI 3.1.0이 사용가능하기 전, 예전 버전과 더 관련있습니다. + + 간략한 OpenAPI와 JSON 스키마 **역사 강의**로 생각할 수 있습니다. 🤓 + +!!! warning "경고" + 표준 **JSON 스키마**와 **OpenAPI**에 대한 아주 기술적인 세부사항입니다. + + 만약 위의 생각이 작동한다면, 그것으로 충분하며 이 세부 사항은 필요없을 것이니, 마음 편하게 스킵하셔도 됩니다. + +OpenAPI 3.1.0 전에 OpenAPI는 오래된 **JSON 스키마**의 수정된 버전을 사용했습니다. + +JSON 스키마는 `examples`를 가지고 있지 않았고, 따라서 OpenAPI는 그들만의 `example` 필드를 수정된 버전에 추가했습니다. + +OpenAPI는 또한 `example`과 `examples` 필드를 명세서의 다른 부분에 추가했습니다: + +* `(명세서에 있는) Parameter Object`는 FastAPI의 다음 기능에서 쓰였습니다: + * `Path()` + * `Query()` + * `Header()` + * `Cookie()` +* (명세서에 있는)`Media Type Object`속 `content`에 있는 `Request Body Object`는 FastAPI의 다음 기능에서 쓰였습니다: + * `Body()` + * `File()` + * `Form()` + +!!! info "정보" + 이 예전 OpenAPI-특화 `examples` 매개변수는 이제 FastAPI `0.103.0`부터 `openapi_examples`입니다. + +### JSON 스키마의 `examples` 필드 + +하지만, 후에 JSON 스키마는 `examples`필드를 명세서의 새 버전에 추가했습니다. + +그리고 새로운 OpenAPI 3.1.0은 이 새로운 `examples` 필드가 포함된 최신 버전 (JSON 스키마 2020-12)을 기반으로 했습니다. + +이제 새로운 `examples` 필드는 이전의 단일 (그리고 커스텀) `example` 필드보다 우선되며, `example`은 사용하지 않는 것이 좋습니다. + +JSON 스키마의 새로운 `examples` 필드는 예제 속 **단순한 `list`**이며, (위에서 상술한 것처럼) OpenAPI의 다른 곳에 존재하는 dict으로 된 추가적인 메타데이터가 아닙니다. + +!!! info "정보" + 더 쉽고 새로운 JSON 스키마와의 통합과 함께 OpenAPI 3.1.0가 배포되었지만, 잠시동안 자동 문서 생성을 제공하는 도구인 Swagger UI는 OpenAPI 3.1.0을 지원하지 않았습니다 (5.0.0 버전부터 지원합니다 🎉). + + 이로인해, FastAPI 0.99.0 이전 버전은 아직 OpenAPI 3.1.0 보다 낮은 버전을 사용했습니다. + +### Pydantic과 FastAPI `examples` + +`examples`를 Pydantic 모델 속에 추가할 때, `schema_extra` 혹은 `Field(examples=["something"])`를 사용하면 Pydantic 모델의 **JSON 스키마**에 해당 예시가 추가됩니다. + +그리고 Pydantic 모델의 **JSON 스키마**는 API의 **OpenAPI**에 포함되고, 그 후 문서 UI 속에서 사용됩니다. + +FastAPI 0.99.0 이전 버전에서 (0.99.0 이상 버전은 새로운 OpenAPI 3.1.0을 사용합니다), `example` 혹은 `examples`를 다른 유틸리티(`Query()`, `Body()` 등)와 함께 사용했을 때, 저러한 예시는 데이터를 설명하는 JSON 스키마에 추가되지 않으며 (심지어 OpenAPI의 자체 JSON 스키마에도 포함되지 않습니다), OpenAPI의 *경로 작동* 선언에 직접적으로 추가됩니다 (JSON 스키마를 사용하는 OpenAPI 부분 외에도). + +하지만 지금은 FastAPI 0.99.0 및 이후 버전에서는 JSON 스키마 2020-12를 사용하는 OpenAPI 3.1.0과 Swagger UI 5.0.0 및 이후 버전을 사용하며, 모든 것이 더 일관성을 띄고 예시는 JSON 스키마에 포함됩니다. + +### Swagger UI와 OpenAPI-특화 `examples` + +현재 (2023-08-26), Swagger UI가 다중 JSON 스키마 예시를 지원하지 않으며, 사용자는 다중 예시를 문서에 표시하는 방법이 없었습니다. + +이를 해결하기 위해, FastAPI `0.103.0`은 새로운 매개변수인 `openapi_examples`를 포함하는 예전 **OpenAPI-특화** `examples` 필드를 선언하기 위한 **지원을 추가**했습니다. 🤓 + +### 요약 + +저는 역사를 그다지 좋아하는 편이 아니라고 말하고는 했지만... "기술 역사" 강의를 가르치는 지금의 저를 보세요. + +요약하자면 **FastAPI 0.99.0 혹은 그 이상의 버전**으로 업그레이드하는 것은 많은 것들이 더 **쉽고, 일관적이며 직관적이게** 되며, 여러분은 이 모든 역사적 세부 사항을 알 필요가 없습니다. 😎 diff --git a/docs/ko/docs/tutorial/security/get-current-user.md b/docs/ko/docs/tutorial/security/get-current-user.md new file mode 100644 index 0000000000000..5bc2cee7a0dee --- /dev/null +++ b/docs/ko/docs/tutorial/security/get-current-user.md @@ -0,0 +1,151 @@ +# 현재 사용자 가져오기 + +이전 장에서 (의존성 주입 시스템을 기반으로 한)보안 시스템은 *경로 작동 함수*에서 `str`로 `token`을 제공했습니다: + +```Python hl_lines="10" +{!../../../docs_src/security/tutorial001.py!} +``` + +그러나 아직도 유용하지 않습니다. + +현재 사용자를 제공하도록 합시다. + +## 유저 모델 생성하기 + +먼저 Pydantic 유저 모델을 만들어 보겠습니다. + +Pydantic을 사용하여 본문을 선언하는 것과 같은 방식으로 다른 곳에서 사용할 수 있습니다. + +=== "파이썬 3.7 이상" + + ```Python hl_lines="5 12-16" + {!> ../../../docs_src/security/tutorial002.py!} + ``` + +=== "파이썬 3.10 이상" + + ```Python hl_lines="3 10-14" + {!> ../../../docs_src/security/tutorial002_py310.py!} + ``` + +## `get_current_user` 의존성 생성하기 + +의존성 `get_current_user`를 만들어 봅시다. + +의존성이 하위 의존성을 가질 수 있다는 것을 기억하십니까? + +`get_current_user`는 이전에 생성한 것과 동일한 `oauth2_scheme`과 종속성을 갖게 됩니다. + +이전에 *경로 작동*에서 직접 수행했던 것과 동일하게 새 종속성 `get_current_user`는 하위 종속성 `oauth2_scheme`에서 `str`로 `token`을 수신합니다. + +=== "파이썬 3.7 이상" + + ```Python hl_lines="25" + {!> ../../../docs_src/security/tutorial002.py!} + ``` + +=== "파이썬 3.10 이상" + + ```Python hl_lines="23" + {!> ../../../docs_src/security/tutorial002_py310.py!} + ``` + +## 유저 가져오기 + +`get_current_user`는 토큰을 `str`로 취하고 Pydantic `User` 모델을 반환하는 우리가 만든 (가짜) 유틸리티 함수를 사용합니다. + +=== "파이썬 3.7 이상" + + ```Python hl_lines="19-22 26-27" + {!> ../../../docs_src/security/tutorial002.py!} + ``` + +=== "파이썬 3.10 이상" + + ```Python hl_lines="17-20 24-25" + {!> ../../../docs_src/security/tutorial002_py310.py!} + ``` + +## 현재 유저 주입하기 + +이제 *경로 작동*에서 `get_current_user`와 동일한 `Depends`를 사용할 수 있습니다. + +=== "파이썬 3.7 이상" + + ```Python hl_lines="31" + {!> ../../../docs_src/security/tutorial002.py!} + ``` + +=== "파이썬 3.10 이상" + + ```Python hl_lines="29" + {!> ../../../docs_src/security/tutorial002_py310.py!} + ``` + +Pydantic 모델인 `User`로 `current_user`의 타입을 선언하는 것을 알아야 합니다. + +이것은 모든 완료 및 타입 검사를 통해 함수 내부에서 우리를 도울 것입니다. + +!!! 팁 + 요청 본문도 Pydantic 모델로 선언된다는 것을 기억할 것입니다. + + 여기서 **FastAPI**는 `Depends`를 사용하고 있기 때문에 혼동되지 않습니다. + +!!! 확인 + 이 의존성 시스템이 설계된 방식은 모두 `User` 모델을 반환하는 다양한 의존성(다른 "의존적인")을 가질 수 있도록 합니다. + + 해당 타입의 데이터를 반환할 수 있는 의존성이 하나만 있는 것으로 제한되지 않습니다. + +## 다른 모델 + +이제 *경로 작동 함수*에서 현재 사용자를 직접 가져올 수 있으며 `Depends`를 사용하여 **의존성 주입** 수준에서 보안 메커니즘을 처리할 수 있습니다. + +그리고 보안 요구 사항에 대한 모든 모델 또는 데이터를 사용할 수 있습니다(이 경우 Pydantic 모델 `User`). + +그러나 일부 특정 데이터 모델, 클래스 또는 타입을 사용하도록 제한되지 않습니다. + +모델에 `id`와 `email`이 있고 `username`이 없길 원하십니까? 맞습니다. 이들은 동일한 도구를 사용할 수 있습니다. + +`str`만 갖고 싶습니까? 아니면 그냥 `dict`를 갖고 싶습니까? 아니면 데이터베이스 클래스 모델 인스턴스를 직접 갖고 싶습니까? 그들은 모두 같은 방식으로 작동합니다. + +실제로 애플리케이션에 로그인하는 사용자가 없지만 액세스 토큰만 있는 로봇, 봇 또는 기타 시스템이 있습니까? 다시 말하지만 모두 동일하게 작동합니다. + +애플리케이션에 필요한 모든 종류의 모델, 모든 종류의 클래스, 모든 종류의 데이터베이스를 사용하십시오. **FastAPI**는 의존성 주입 시스템을 다루었습니다. + +## 코드 사이즈 + +이 예는 장황해 보일 수 있습니다. 동일한 파일에서 보안, 데이터 모델, 유틸리티 기능 및 *경로 작동*을 혼합하고 있음을 염두에 두십시오. + +그러나 이게 키포인트입니다. + +보안과 종속성 주입 항목을 한 번만 작성하면 됩니다. + +그리고 원하는 만큼 복잡하게 만들 수 있습니다. 그래도 유연성과 함께 한 곳에 한 번에 작성할 수 있습니다. + +그러나 동일한 보안 시스템을 사용하여 수천 개의 엔드포인트(*경로 작동*)를 가질 수 있습니다. + +그리고 그들 모두(또는 원하는 부분)는 이러한 의존성 또는 생성한 다른 의존성을 재사용하는 이점을 얻을 수 있습니다. + +그리고 이 수천 개의 *경로 작동*은 모두 3줄 정도로 줄일 수 있습니다. + +=== "파이썬 3.7 이상" + + ```Python hl_lines="30-32" + {!> ../../../docs_src/security/tutorial002.py!} + ``` + +=== "파이썬 3.10 이상" + + ```Python hl_lines="28-30" + {!> ../../../docs_src/security/tutorial002_py310.py!} + ``` + +## 요약 + +이제 *경로 작동 함수*에서 현재 사용자를 직접 가져올 수 있습니다. + +우리는 이미 이들 사이에 있습니다. + +사용자/클라이언트가 실제로 `username`과 `password`를 보내려면 *경로 작동*을 추가하기만 하면 됩니다. + +다음 장을 확인해 봅시다. diff --git a/docs/ko/docs/tutorial/static-files.md b/docs/ko/docs/tutorial/static-files.md new file mode 100644 index 0000000000000..fe1aa4e5e27fc --- /dev/null +++ b/docs/ko/docs/tutorial/static-files.md @@ -0,0 +1,40 @@ +# 정적 파일 + +'StaticFiles'를 사용하여 디렉토리에서 정적 파일을 자동으로 제공할 수 있습니다. + +## `StaticFiles` 사용 + +* `StaticFiles` 임포트합니다. +* 특정 경로에 `StaticFiles()` 인스턴스를 "마운트" 합니다. + +```Python hl_lines="2 6" +{!../../../docs_src/static_files/tutorial001.py!} +``` + +!!! note "기술적 세부사항" + `from starlette.staticfiles import StaticFiles` 를 사용할 수도 있습니다. + + **FastAPI**는 단지 개발자인, 당신에게 편의를 제공하기 위해 `fastapi.static files` 와 동일한 `starlett.static files`를 제공합니다. 하지만 사실 이것은 Starlett에서 직접 온 것입니다. + +### "마운팅" 이란 + +"마운팅"은 특정 경로에 완전히 "독립적인" 애플리케이션을 추가하는 것을 의미하는데, 그 후 모든 하위 경로에 대해서도 적용됩니다. + +마운트된 응용 프로그램은 완전히 독립적이기 때문에 `APIRouter`를 사용하는 것과는 다릅니다. OpenAPI 및 응용 프로그램의 문서는 마운트된 응용 프로그램 등에서 어떤 것도 포함하지 않습니다. + +자세한 내용은 **숙련된 사용자 안내서**에서 확인할 수 있습니다. + +## 세부사항 + +첫 번째 `"/static"`은 이 "하위 응용 프로그램"이 "마운트"될 하위 경로를 가리킵니다. 따라서 `"/static"`으로 시작하는 모든 경로는 `"/static"`으로 처리됩니다. + +`'directory="static"`은 정적 파일이 들어 있는 디렉토리의 이름을 나타냅니다. + +`name="static"`은 **FastAPI**에서 내부적으로 사용할 수 있는 이름을 제공합니다. + +이 모든 매개변수는 "`static`"과 다를 수 있으며, 사용자 응용 프로그램의 요구 사항 및 구체적인 세부 정보에 따라 매개변수를 조정할 수 있습니다. + + +## 추가 정보 + +자세한 내용과 선택 사항을 보려면 Starlette의 정적 파일에 관한 문서를 확인하십시오. diff --git a/docs/language_names.yml b/docs/language_names.yml new file mode 100644 index 0000000000000..c5a15ddd97a6d --- /dev/null +++ b/docs/language_names.yml @@ -0,0 +1,183 @@ +aa: Afaraf +ab: аҧсуа бызшәа +ae: avesta +af: Afrikaans +ak: Akan +am: አማርኛ +an: aragonés +ar: اللغة العربية +as: অসমীয়া +av: авар мацӀ +ay: aymar aru +az: azərbaycan dili +ba: башҡорт теле +be: беларуская мова +bg: български език +bh: भोजपुरी +bi: Bislama +bm: bamanankan +bn: বাংলা +bo: བོད་ཡིག +br: brezhoneg +bs: bosanski jezik +ca: Català +ce: нохчийн мотт +ch: Chamoru +co: corsu +cr: ᓀᐦᐃᔭᐍᐏᐣ +cs: čeština +cu: ѩзыкъ словѣньскъ +cv: чӑваш чӗлхи +cy: Cymraeg +da: dansk +de: Deutsch +dv: Dhivehi +dz: རྫོང་ཁ +ee: Eʋegbe +el: Ελληνικά +en: English +eo: Esperanto +es: español +et: eesti +eu: euskara +fa: فارسی +ff: Fulfulde +fi: suomi +fj: Vakaviti +fo: føroyskt +fr: français +fy: Frysk +ga: Gaeilge +gd: Gàidhlig +gl: galego +gu: ગુજરાતી +gv: Gaelg +ha: هَوُسَ +he: עברית +hi: हिन्दी +ho: Hiri Motu +hr: Hrvatski +ht: Kreyòl ayisyen +hu: magyar +hy: Հայերեն +hz: Otjiherero +ia: Interlingua +id: Bahasa Indonesia +ie: Interlingue +ig: Asụsụ Igbo +ii: ꆈꌠ꒿ Nuosuhxop +ik: Iñupiaq +io: Ido +is: Íslenska +it: italiano +iu: ᐃᓄᒃᑎᑐᑦ +ja: 日本語 +jv: basa Jawa +ka: ქართული +kg: Kikongo +ki: Gĩkũyũ +kj: Kuanyama +kk: қазақ тілі +kl: kalaallisut +km: ខេមរភាសា +kn: ಕನ್ನಡ +ko: 한국어 +kr: Kanuri +ks: कश्मीरी +ku: Kurdî +kv: коми кыв +kw: Kernewek +ky: Кыргызча +la: latine +lb: Lëtzebuergesch +lg: Luganda +li: Limburgs +ln: Lingála +lo: ພາສາ +lt: lietuvių kalba +lu: Tshiluba +lv: latviešu valoda +mg: fiteny malagasy +mh: Kajin M̧ajeļ +mi: te reo Māori +mk: македонски јазик +ml: മലയാളം +mn: Монгол хэл +mr: मराठी +ms: Bahasa Malaysia +mt: Malti +my: ဗမာစာ +na: Ekakairũ Naoero +nb: Norsk bokmål +nd: isiNdebele +ne: नेपाली +ng: Owambo +nl: Nederlands +nn: Norsk nynorsk +'no': Norsk +nr: isiNdebele +nv: Diné bizaad +ny: chiCheŵa +oc: occitan +oj: ᐊᓂᔑᓈᐯᒧᐎᓐ +om: Afaan Oromoo +or: ଓଡ଼ିଆ +os: ирон æвзаг +pa: ਪੰਜਾਬੀ +pi: पाऴि +pl: Polski +ps: پښتو +pt: português +qu: Runa Simi +rm: rumantsch grischun +rn: Ikirundi +ro: Română +ru: русский язык +rw: Ikinyarwanda +sa: संस्कृतम् +sc: sardu +sd: सिन्धी +se: Davvisámegiella +sg: yângâ tî sängö +si: සිංහල +sk: slovenčina +sl: slovenščina +sn: chiShona +so: Soomaaliga +sq: shqip +sr: српски језик +ss: SiSwati +st: Sesotho +su: Basa Sunda +sv: svenska +sw: Kiswahili +ta: தமிழ் +te: తెలుగు +tg: тоҷикӣ +th: ไทย +ti: ትግርኛ +tk: Türkmen +tl: Wikang Tagalog +tn: Setswana +to: faka Tonga +tr: Türkçe +ts: Xitsonga +tt: татар теле +tw: Twi +ty: Reo Tahiti +ug: ئۇيغۇرچە‎ +uk: українська мова +ur: اردو +uz: Ўзбек +ve: Tshivenḓa +vi: Tiếng Việt +vo: Volapük +wa: walon +wo: Wollof +xh: isiXhosa +yi: ייִדיש +yo: Yorùbá +za: Saɯ cueŋƅ +zh: 简体中文 +zh-hant: 繁體中文 +zu: isiZulu diff --git a/docs/pl/docs/features.md b/docs/pl/docs/features.md index 49d362dd985cf..a6435977c9cb2 100644 --- a/docs/pl/docs/features.md +++ b/docs/pl/docs/features.md @@ -25,7 +25,7 @@ Interaktywna dokumentacja i webowe interfejsy do eksploracji API. Z racji tego, ### Nowoczesny Python -Wszystko opiera się na standardowych deklaracjach typu **Python 3.6** (dzięki Pydantic). Brak nowej składni do uczenia. Po prostu standardowy, współczesny Python. +Wszystko opiera się na standardowych deklaracjach typu **Python 3.8** (dzięki Pydantic). Brak nowej składni do uczenia. Po prostu standardowy, współczesny Python. Jeśli potrzebujesz szybkiego przypomnienia jak używać deklaracji typów w Pythonie (nawet jeśli nie używasz FastAPI), sprawdź krótki samouczek: [Python Types](python-types.md){.internal-link target=_blank}. @@ -174,7 +174,7 @@ Dzięki **FastAPI** otrzymujesz wszystkie funkcje **Starlette** (ponieważ FastA ## Cechy Pydantic -**FastAPI** jest w pełni kompatybilny z (oraz bazuje na) Pydantic. Tak więc każdy dodatkowy kod Pydantic, który posiadasz, również będzie działał. +**FastAPI** jest w pełni kompatybilny z (oraz bazuje na) Pydantic. Tak więc każdy dodatkowy kod Pydantic, który posiadasz, również będzie działał. Wliczając w to zewnętrzne biblioteki, również oparte o Pydantic, takie jak ORM, ODM dla baz danych. @@ -189,8 +189,6 @@ Dzięki **FastAPI** otrzymujesz wszystkie funkcje **Pydantic** (ponieważ FastAP * Jeśli znasz adnotacje typów Pythona to wiesz jak używać Pydantic. * Dobrze współpracuje z Twoim **IDE/linterem/mózgiem**: * Ponieważ struktury danych Pydantic to po prostu instancje klas, które definiujesz; autouzupełnianie, linting, mypy i twoja intuicja powinny działać poprawnie z Twoimi zwalidowanymi danymi. -* **Szybkość**: - * w benchmarkach Pydantic jest szybszy niż wszystkie inne testowane biblioteki. * Walidacja **złożonych struktur**: * Wykorzystanie hierarchicznych modeli Pydantic, Pythonowego modułu `typing` zawierającego `List`, `Dict`, itp. * Walidatory umożliwiają jasne i łatwe definiowanie, sprawdzanie złożonych struktur danych oraz dokumentowanie ich jako JSON Schema. diff --git a/docs/pl/docs/help-fastapi.md b/docs/pl/docs/help-fastapi.md new file mode 100644 index 0000000000000..3d02a87410851 --- /dev/null +++ b/docs/pl/docs/help-fastapi.md @@ -0,0 +1,263 @@ +# Pomóż FastAPI - Uzyskaj pomoc + +Czy podoba Ci się **FastAPI**? + +Czy chciałbyś pomóc FastAPI, jego użytkownikom i autorowi? + +Może napotkałeś na trudności z **FastAPI** i potrzebujesz pomocy? + +Istnieje kilka bardzo łatwych sposobów, aby pomóc (czasami wystarczy jedno lub dwa kliknięcia). + +Istnieje również kilka sposobów uzyskania pomocy. + +## Zapisz się do newslettera + +Możesz zapisać się do rzadkiego [newslettera o **FastAPI i jego przyjaciołach**](/newsletter/){.internal-link target=_blank}, aby być na bieżąco z: + +* Aktualnościami o FastAPI i przyjaciołach 🚀 +* Przewodnikami 📝 +* Funkcjami ✨ +* Przełomowymi zmianami 🚨 +* Poradami i sztuczkami ✅ + +## Śledź FastAPI na Twitterze + +Śledź @fastapi na **Twitterze** aby być na bieżąco z najnowszymi wiadomościami o **FastAPI**. 🐦 + +## Dodaj gwiazdkę **FastAPI** na GitHubie + +Możesz "dodać gwiazdkę" FastAPI na GitHubie (klikając przycisk gwiazdki w prawym górnym rogu): https://github.com/tiangolo/fastapi. ⭐️ + +Dodając gwiazdkę, inni użytkownicy będą mogli łatwiej znaleźć projekt i zobaczyć, że był już przydatny dla innych. + +## Obserwuj repozytorium GitHub w poszukiwaniu nowych wydań + +Możesz "obserwować" FastAPI na GitHubie (klikając przycisk "obserwuj" w prawym górnym rogu): https://github.com/tiangolo/fastapi. 👀 + +Wybierz opcję "Tylko wydania". + +Dzięki temu będziesz otrzymywać powiadomienia (na swój adres e-mail) za każdym razem, gdy pojawi się nowe wydanie (nowa wersja) **FastAPI** z poprawkami błędów i nowymi funkcjami. + +## Skontaktuj się z autorem + +Możesz skontaktować się ze mną (Sebastián Ramírez / `tiangolo`), autorem. + +Możesz: + +* Śledzić mnie na **GitHubie**. + * Zobacz inne projekty open source, które stworzyłem, a mogą być dla Ciebie pomocne. + * Śledź mnie, aby dostać powiadomienie, gdy utworzę nowy projekt open source. +* Śledzić mnie na **Twitterze** lub na Mastodonie. + * Napisz mi, w jaki sposób korzystasz z FastAPI (uwielbiam o tym czytać). + * Dowiedz się, gdy ogłoszę coś nowego lub wypuszczę nowe narzędzia. + * Możesz także śledzić @fastapi na Twitterze (to oddzielne konto). +* Nawiąż ze mną kontakt na **Linkedinie**. + * Dowiedz się, gdy ogłoszę coś nowego lub wypuszczę nowe narzędzia (chociaż częściej korzystam z Twittera 🤷‍♂). +* Czytaj moje posty (lub śledź mnie) na **Dev.to** lub na **Medium**. + * Czytaj o innych pomysłach, artykułach i dowiedz się o narzędziach, które stworzyłem. + * Śledź mnie, by wiedzieć gdy opublikuję coś nowego. + +## Napisz tweeta o **FastAPI** + +Napisz tweeta o **FastAPI** i powiedz czemu Ci się podoba. 🎉 + +Uwielbiam czytać w jaki sposób **FastAPI** jest używane, co Ci się w nim podobało, w jakim projekcie/firmie go używasz itp. + +## Głosuj na FastAPI + +* Głosuj na **FastAPI** w Slant. +* Głosuj na **FastAPI** w AlternativeTo. +* Powiedz, że używasz **FastAPI** na StackShare. + +## Pomagaj innym, odpowiadając na ich pytania na GitHubie + +Możesz spróbować pomóc innym, odpowiadając w: + +* Dyskusjach na GitHubie +* Problemach na GitHubie + +W wielu przypadkach możesz już znać odpowiedź na te pytania. 🤓 + +Jeśli pomożesz wielu ludziom, możesz zostać oficjalnym [Ekspertem FastAPI](fastapi-people.md#experts){.internal-link target=_blank}. 🎉 + +Pamiętaj tylko o najważniejszym: bądź życzliwy. Ludzie przychodzą sfrustrowani i w wielu przypadkach nie zadają pytań w najlepszy sposób, ale mimo to postaraj się być dla nich jak najbardziej życzliwy. 🤗 + +Chciałbym, by społeczność **FastAPI** była życzliwa i przyjazna. Nie akceptuj prześladowania ani braku szacunku wobec innych. Dbajmy o siebie nawzajem. + +--- + +Oto, jak pomóc innym z pytaniami (w dyskusjach lub problemach): + +### Zrozum pytanie + +* Upewnij się, czy rozumiesz **cel** i przypadek użycia osoby pytającej. + +* Następnie sprawdź, czy pytanie (większość to pytania) jest **jasne**. + +* W wielu przypadkach zadane pytanie dotyczy rozwiązania wymyślonego przez użytkownika, ale może istnieć **lepsze** rozwiązanie. Jeśli dokładnie zrozumiesz problem i przypadek użycia, być może będziesz mógł zaproponować lepsze **alternatywne rozwiązanie**. + +* Jeśli nie rozumiesz pytania, poproś o więcej **szczegółów**. + +### Odtwórz problem + +W większości przypadków problem wynika z **autorskiego kodu** osoby pytającej. + +Często pytający umieszczają tylko fragment kodu, niewystarczający do **odtworzenia problemu**. + +* Możesz poprosić ich o dostarczenie minimalnego, odtwarzalnego przykładu, który możesz **skopiować i wkleić** i uruchomić lokalnie, aby zobaczyć ten sam błąd lub zachowanie, które widzą, lub lepiej zrozumieć ich przypadki użycia. + +* Jeśli jesteś wyjątkowo pomocny, możesz spróbować **stworzyć taki przykład** samodzielnie, opierając się tylko na opisie problemu. Miej na uwadze, że może to zająć dużo czasu i lepiej może być najpierw poprosić ich o wyjaśnienie problemu. + +### Proponuj rozwiązania + +* Po zrozumieniu pytania możesz podać im możliwą **odpowiedź**. + +* W wielu przypadkach lepiej zrozumieć ich **podstawowy problem lub przypadek użycia**, ponieważ może istnieć lepszy sposób rozwiązania niż to, co próbują zrobić. + +### Poproś o zamknięcie + +Jeśli odpowiedzą, jest duża szansa, że rozwiązałeś ich problem, gratulacje, **jesteś bohaterem**! 🦸 + +* Jeśli Twoja odpowiedź rozwiązała problem, możesz poprosić o: + + * W Dyskusjach na GitHubie: oznaczenie komentarza jako **odpowiedź**. + * W Problemach na GitHubie: **zamknięcie** problemu. + +## Obserwuj repozytorium na GitHubie + +Możesz "obserwować" FastAPI na GitHubie (klikając przycisk "obserwuj" w prawym górnym rogu): https://github.com/tiangolo/fastapi. 👀 + +Jeśli wybierzesz "Obserwuj" zamiast "Tylko wydania", otrzymasz powiadomienia, gdy ktoś utworzy nowy problem lub pytanie. Możesz również określić, że chcesz być powiadamiany tylko o nowych problemach, dyskusjach, PR-ach itp. + +Następnie możesz spróbować pomóc rozwiązać te problemy. + +## Zadawaj pytania + +Możesz utworzyć nowe pytanie w repozytorium na GitHubie, na przykład aby: + +* Zadać **pytanie** lub zapytać o **problem**. +* Zaproponować nową **funkcję**. + +**Uwaga**: jeśli to zrobisz, poproszę Cię również o pomoc innym. 😉 + +## Przeglądaj Pull Requesty + +Możesz pomóc mi w przeglądaniu pull requestów autorstwa innych osób. + +Jak wcześniej wspomniałem, postaraj się być jak najbardziej życzliwy. 🤗 + +--- + +Oto, co warto mieć na uwadze podczas oceny pull requestu: + +### Zrozum problem + +* Najpierw upewnij się, że **rozumiesz problem**, który próbuje rozwiązać pull request. Może być osadzony w większym kontekście w GitHubowej dyskusji lub problemie. + +* Jest też duża szansa, że pull request nie jest konieczny, ponieważ problem można rozwiązać w **inny sposób**. Wtedy możesz to zasugerować lub o to zapytać. + +### Nie martw się stylem + +* Nie przejmuj się zbytnio rzeczami takimi jak style wiadomości commitów, przy wcielaniu pull requesta łączę commity i modyfikuję opis sumarycznego commita ręcznie. + +* Nie przejmuj się również stylem kodu, automatyczne narzędzia w repozytorium sprawdzają to samodzielnie. + +A jeśli istnieje jakaś konkretna potrzeba dotycząca stylu lub spójności, sam poproszę o zmiany lub dodam commity z takimi zmianami. + +### Sprawdź kod + +* Przeczytaj kod, zastanów się czy ma sens, **uruchom go lokalnie** i potwierdź czy faktycznie rozwiązuje problem. + +* Następnie dodaj **komentarz** z informacją o tym, że sprawdziłeś kod, dzięki temu będę miał pewność, że faktycznie go sprawdziłeś. + +!!! info + Niestety, nie mogę ślepo ufać PR-om, nawet jeśli mają kilka zatwierdzeń. + + Kilka razy zdarzyło się, że PR-y miały 3, 5 lub więcej zatwierdzeń (prawdopodobnie dlatego, że opis obiecuje rozwiązanie ważnego problemu), ale gdy sam sprawdziłem danego PR-a, okazał się być zbugowany lub nie rozwiązywał problemu, który rzekomo miał rozwiązywać. 😅 + + Dlatego tak ważne jest, abyś faktycznie przeczytał i uruchomił kod oraz napisał w komentarzu, że to zrobiłeś. 🤓 + +* Jeśli PR można uprościć w jakiś sposób, możesz o to poprosić, ale nie ma potrzeby być zbyt wybrednym, może być wiele subiektywnych punktów widzenia (a ja też będę miał swój 🙈), więc lepiej żebyś skupił się na kluczowych rzeczach. + +### Testy + +* Pomóż mi sprawdzić, czy PR ma **testy**. + +* Sprawdź, czy testy **nie przechodzą** przed PR. 🚨 + +* Następnie sprawdź, czy testy **przechodzą** po PR. ✅ + +* Wiele PR-ów nie ma testów, możesz **przypomnieć** im o dodaniu testów, a nawet **zaproponować** samemu jakieś testy. To jedna z rzeczy, które pochłaniają najwięcej czasu i możesz w tym bardzo pomóc. + +* Następnie skomentuj również to, czego spróbowałeś, wtedy będę wiedział, że to sprawdziłeś. 🤓 + +## Utwórz Pull Request + +Możesz [wnieść wkład](contributing.md){.internal-link target=_blank} do kodu źródłowego za pomocą Pull Requestu, na przykład: + +* Naprawić literówkę, którą znalazłeś w dokumentacji. +* Podzielić się artykułem, filmem lub podcastem, który stworzyłeś lub znalazłeś na temat FastAPI, edytując ten plik. + * Upewnij się, że dodajesz swój link na początku odpowiedniej sekcji. +* Pomóc w [tłumaczeniu dokumentacji](contributing.md#translations){.internal-link target=_blank} na Twój język. + * Możesz również pomóc w weryfikacji tłumaczeń stworzonych przez innych. +* Zaproponować nowe sekcje dokumentacji. +* Naprawić istniejący problem/błąd. + * Upewnij się, że dodajesz testy. +* Dodać nową funkcję. + * Upewnij się, że dodajesz testy. + * Upewnij się, że dodajesz dokumentację, jeśli jest to istotne. + +## Pomóż w utrzymaniu FastAPI + +Pomóż mi utrzymać **FastAPI**! 🤓 + +Jest wiele pracy do zrobienia, a w większości przypadków **TY** możesz to zrobić. + +Główne zadania, które możesz wykonać teraz to: + +* [Pomóc innym z pytaniami na GitHubie](#help-others-with-questions-in-github){.internal-link target=_blank} (zobacz sekcję powyżej). +* [Oceniać Pull Requesty](#review-pull-requests){.internal-link target=_blank} (zobacz sekcję powyżej). + +Te dwie czynności **zajmują najwięcej czasu**. To główna praca związana z utrzymaniem FastAPI. + +Jeśli możesz mi w tym pomóc, **pomożesz mi utrzymać FastAPI** i zapewnisz że będzie **rozwijać się szybciej i lepiej**. 🚀 + +## Dołącz do czatu + +Dołącz do 👥 serwera czatu na Discordzie 👥 i spędzaj czas z innymi w społeczności FastAPI. + +!!! wskazówka + Jeśli masz pytania, zadaj je w Dyskusjach na GitHubie, jest dużo większa szansa, że otrzymasz pomoc od [Ekspertów FastAPI](fastapi-people.md#experts){.internal-link target=_blank}. + + Używaj czatu tylko do innych ogólnych rozmów. + +### Nie zadawaj pytań na czacie + +Miej na uwadze, że ponieważ czaty pozwalają na bardziej "swobodną rozmowę", łatwo jest zadawać pytania, które są zbyt ogólne i trudniejsze do odpowiedzi, więc możesz nie otrzymać odpowiedzi. + +Na GitHubie szablon poprowadzi Cię do napisania odpowiedniego pytania, dzięki czemu łatwiej uzyskasz dobrą odpowiedź, a nawet rozwiążesz problem samodzielnie, zanim zapytasz. Ponadto na GitHubie mogę się upewnić, że zawsze odpowiadam na wszystko, nawet jeśli zajmuje to trochę czasu. Osobiście nie mogę tego zrobić z systemami czatu. 😅 + +Rozmów w systemach czatu nie można tak łatwo przeszukiwać, jak na GitHubie, więc pytania i odpowiedzi mogą zaginąć w rozmowie. A tylko te na GitHubie liczą się do zostania [Ekspertem FastAPI](fastapi-people.md#experts){.internal-link target=_blank}, więc najprawdopodobniej otrzymasz więcej uwagi na GitHubie. + +Z drugiej strony w systemach czatu są tysiące użytkowników, więc jest duża szansa, że znajdziesz tam kogoś do rozmowy, prawie w każdej chwili. 😄 + +## Wspieraj autora + +Możesz również finansowo wesprzeć autora (mnie) poprzez sponsoring na GitHubie. + +Tam możesz postawić mi kawę ☕️ aby podziękować. 😄 + +Możesz także zostać srebrnym lub złotym sponsorem FastAPI. 🏅🎉 + +## Wspieraj narzędzia, które napędzają FastAPI + +Jak widziałeś w dokumentacji, FastAPI stoi na ramionach gigantów, Starlette i Pydantic. + +Możesz również wesprzeć: + +* Samuel Colvin (Pydantic) +* Encode (Starlette, Uvicorn) + +--- + +Dziękuję! 🚀 diff --git a/docs/pl/docs/index.md b/docs/pl/docs/index.md index bade7a88cb587..ab33bfb9c80b3 100644 --- a/docs/pl/docs/index.md +++ b/docs/pl/docs/index.md @@ -24,7 +24,7 @@ --- -FastAPI to nowoczesny, wydajny framework webowy do budowania API z użyciem Pythona 3.6+ bazujący na standardowym typowaniu Pythona. +FastAPI to nowoczesny, wydajny framework webowy do budowania API z użyciem Pythona 3.8+ bazujący na standardowym typowaniu Pythona. Kluczowe cechy: @@ -106,12 +106,12 @@ Jeżeli tworzysz aplikacje CLI< ## Wymagania -Python 3.7+ +Python 3.8+ FastAPI oparty jest na: * Starlette dla części webowej. -* Pydantic dla części obsługujących dane. +* Pydantic dla części obsługujących dane. ## Instalacja @@ -321,7 +321,7 @@ Robisz to tak samo jak ze standardowymi typami w Pythonie. Nie musisz sie uczyć żadnej nowej składni, metod lub klas ze specyficznych bibliotek itp. -Po prostu standardowy **Python 3.6+**. +Po prostu standardowy **Python 3.8+**. Na przykład, dla danych typu `int`: @@ -442,7 +442,7 @@ Używane przez Starlette: * httpx - Wymagane jeżeli chcesz korzystać z `TestClient`. * aiofiles - Wymagane jeżeli chcesz korzystać z `FileResponse` albo `StaticFiles`. * jinja2 - Wymagane jeżeli chcesz używać domyślnej konfiguracji szablonów. -* python-multipart - Wymagane jeżelich chcesz wsparcie "parsowania" formularzy, używając `request.form()`. +* python-multipart - Wymagane jeżelich chcesz wsparcie "parsowania" formularzy, używając `request.form()`. * itsdangerous - Wymagany dla wsparcia `SessionMiddleware`. * pyyaml - Wymagane dla wsparcia `SchemaGenerator` z Starlette (z FastAPI prawdopodobnie tego nie potrzebujesz). * graphene - Wymagane dla wsparcia `GraphQLApp`. diff --git a/docs/pt/docs/advanced/templates.md b/docs/pt/docs/advanced/templates.md new file mode 100644 index 0000000000000..3bada5e432891 --- /dev/null +++ b/docs/pt/docs/advanced/templates.md @@ -0,0 +1,119 @@ +# Templates + +Você pode usar qualquer template engine com o **FastAPI**. + +Uma escolha comum é o Jinja2, o mesmo usado pelo Flask e outras ferramentas. + +Existem utilitários para configurá-lo facilmente que você pode usar diretamente em sua aplicação **FastAPI** (fornecidos pelo Starlette). + +## Instalação de dependências + +Para instalar o `jinja2`, siga o código abaixo: + +
+ +```console +$ pip install jinja2 +``` + +
+ +## Usando `Jinja2Templates` + +* Importe `Jinja2Templates`. +* Crie um `templates` que você possa reutilizar posteriormente. +* Declare um parâmetro `Request` no *path operation* que retornará um template. +* Use o `template` que você criou para renderizar e retornar uma `TemplateResponse`, passe o nome do template, o request object, e um "context" dict com pares chave-valor a serem usados dentro do template do Jinja2. + +```Python hl_lines="4 11 15-18" +{!../../../docs_src/templates/tutorial001.py!} +``` + +!!! note + Antes do FastAPI 0.108.0, Starlette 0.29.0, `name` era o primeiro parâmetro. + + Além disso, em versões anteriores, o objeto `request` era passado como parte dos pares chave-valor no "context" dict para o Jinja2. + + +!!! tip "Dica" + Ao declarar `response_class=HTMLResponse`, a documentação entenderá que a resposta será HTML. + + +!!! note "Detalhes Técnicos" + Você também poderia usar `from starlette.templating import Jinja2Templates`. + + **FastAPI** fornece o mesmo `starlette.templating` como `fastapi.templating` apenas como uma conveniência para você, o desenvolvedor. Mas a maioria das respostas disponíveis vêm diretamente do Starlette. O mesmo acontece com `Request` e `StaticFiles`. + +## Escrevendo Templates + +Então você pode escrever um template em `templates/item.html`, por exemplo: + +```jinja hl_lines="7" +{!../../../docs_src/templates/templates/item.html!} +``` + +### Interpolação de Valores no Template + +No código HTML que contém: + +{% raw %} + +```jinja +Item ID: {{ id }} +``` + +{% endraw %} + +...aparecerá o `id` obtido do "context" `dict` que você passou: + +```Python +{"id": id} +``` + +Por exemplo, dado um ID de valor `42`, aparecerá: + +```html +Item ID: 42 +``` + +### Argumentos do `url_for` + +Você também pode usar `url_for()` dentro do template, ele recebe como argumentos os mesmos argumentos que seriam usados pela sua *path operation function*. + +Logo, a seção com: + +{% raw %} + +```jinja + +``` + +{% endraw %} + +...irá gerar um link para a mesma URL que será tratada pela *path operation function* `read_item(id=id)`. + +Por exemplo, com um ID de `42`, isso renderizará: + +```html + +``` + +## Templates e Arquivos Estáticos + +Você também pode usar `url_for()` dentro do template e usá-lo, por examplo, com o `StaticFiles` que você montou com o `name="static"`. + +```jinja hl_lines="4" +{!../../../docs_src/templates/templates/item.html!} +``` + +Neste exemplo, ele seria vinculado a um arquivo CSS em `static/styles.css` com: + +```CSS hl_lines="4" +{!../../../docs_src/templates/static/styles.css!} +``` + +E como você está usando `StaticFiles`, este arquivo CSS será automaticamente servido pela sua aplicação FastAPI na URL `/static/styles.css`. + +## Mais detalhes + +Para obter mais detalhes, incluindo como testar templates, consulte a documentação da Starlette sobre templates. diff --git a/docs/pt/docs/alternatives.md b/docs/pt/docs/alternatives.md index 61ee4f9000e10..ba721536ff0aa 100644 --- a/docs/pt/docs/alternatives.md +++ b/docs/pt/docs/alternatives.md @@ -340,7 +340,7 @@ Agora APIStar é um conjunto de ferramentas para validar especificações OpenAP ## Usados por **FastAPI** -### Pydantic +### Pydantic Pydantic é uma biblioteca para definir validação de dados, serialização e documentação (usando JSON Schema) baseado nos Python _type hints_. diff --git a/docs/pt/docs/deployment/deta.md b/docs/pt/docs/deployment/deta.md deleted file mode 100644 index 9271bba42ea85..0000000000000 --- a/docs/pt/docs/deployment/deta.md +++ /dev/null @@ -1,258 +0,0 @@ -# Implantação FastAPI na Deta - -Nessa seção você aprenderá sobre como realizar a implantação de uma aplicação **FastAPI** na Deta utilizando o plano gratuito. 🎁 - -Isso tudo levará aproximadamente **10 minutos**. - -!!! info "Informação" - Deta é uma patrocinadora do **FastAPI**. 🎉 - -## Uma aplicação **FastAPI** simples - -* Crie e entre em um diretório para a sua aplicação, por exemplo, `./fastapideta/`. - -### Código FastAPI - -* Crie o arquivo `main.py` com: - -```Python -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): - return {"item_id": item_id} -``` - -### Requisitos - -Agora, no mesmo diretório crie o arquivo `requirements.txt` com: - -```text -fastapi -``` - -!!! tip "Dica" - Você não precisa instalar Uvicorn para realizar a implantação na Deta, embora provavelmente queira instalá-lo para testar seu aplicativo localmente. - -### Estrutura de diretório - -Agora você terá o diretório `./fastapideta/` com dois arquivos: - -``` -. -└── main.py -└── requirements.txt -``` - -## Crie uma conta gratuita na Deta - -Agora crie uma conta gratuita na Deta, você precisará apenas de um email e senha. - -Você nem precisa de um cartão de crédito. - -## Instale a CLI - -Depois de ter sua conta criada, instale Deta CLI: - -=== "Linux, macOS" - -
- - ```console - $ curl -fsSL https://get.deta.dev/cli.sh | sh - ``` - -
- -=== "Windows PowerShell" - -
- - ```console - $ iwr https://get.deta.dev/cli.ps1 -useb | iex - ``` - -
- -Após a instalação, abra um novo terminal para que a CLI seja detectada. - -Em um novo terminal, confirme se foi instalado corretamente com: - -
- -```console -$ deta --help - -Deta command line interface for managing deta micros. -Complete documentation available at https://docs.deta.sh - -Usage: - deta [flags] - deta [command] - -Available Commands: - auth Change auth settings for a deta micro - -... -``` - -
- -!!! tip "Dica" - Se você tiver problemas ao instalar a CLI, verifique a documentação oficial da Deta. - -## Login pela CLI - -Agora faça login na Deta pela CLI com: - -
- -```console -$ deta login - -Please, log in from the web page. Waiting.. -Logged in successfully. -``` - -
- -Isso abrirá um navegador da Web e autenticará automaticamente. - -## Implantação com Deta - -Em seguida, implante seu aplicativo com a Deta CLI: - -
- -```console -$ deta new - -Successfully created a new micro - -// Notice the "endpoint" 🔍 - -{ - "name": "fastapideta", - "runtime": "python3.7", - "endpoint": "https://qltnci.deta.dev", - "visor": "enabled", - "http_auth": "enabled" -} - -Adding dependencies... - - ----> 100% - - -Successfully installed fastapi-0.61.1 pydantic-1.7.2 starlette-0.13.6 -``` - -
- -Você verá uma mensagem JSON semelhante a: - -```JSON hl_lines="4" -{ - "name": "fastapideta", - "runtime": "python3.7", - "endpoint": "https://qltnci.deta.dev", - "visor": "enabled", - "http_auth": "enabled" -} -``` - -!!! tip "Dica" - Sua implantação terá um URL `"endpoint"` diferente. - -## Confira - -Agora, abra seu navegador na URL do `endpoint`. No exemplo acima foi `https://qltnci.deta.dev`, mas o seu será diferente. - -Você verá a resposta JSON do seu aplicativo FastAPI: - -```JSON -{ - "Hello": "World" -} -``` - -Agora vá para o `/docs` da sua API, no exemplo acima seria `https://qltnci.deta.dev/docs`. - -Ele mostrará sua documentação como: - - - -## Permitir acesso público - -Por padrão, a Deta lidará com a autenticação usando cookies para sua conta. - -Mas quando estiver pronto, você pode torná-lo público com: - -
- -```console -$ deta auth disable - -Successfully disabled http auth -``` - -
- -Agora você pode compartilhar essa URL com qualquer pessoa e elas conseguirão acessar sua API. 🚀 - -## HTTPS - -Parabéns! Você realizou a implantação do seu app FastAPI na Deta! 🎉 🍰 - -Além disso, observe que a Deta lida corretamente com HTTPS para você, para que você não precise cuidar disso e tenha a certeza de que seus clientes terão uma conexão criptografada segura. ✅ 🔒 - -## Verifique o Visor - -Na UI da sua documentação (você estará em um URL como `https://qltnci.deta.dev/docs`) envie um request para *operação de rota* `/items/{item_id}`. - -Por exemplo com ID `5`. - -Agora vá para https://web.deta.sh. - -Você verá que há uma seção à esquerda chamada "Micros" com cada um dos seus apps. - -Você verá uma aba com "Detalhes", e também a aba "Visor", vá para "Visor". - -Lá você pode inspecionar as solicitações recentes enviadas ao seu aplicativo. - -Você também pode editá-los e reproduzi-los novamente. - - - -## Saiba mais - -Em algum momento, você provavelmente desejará armazenar alguns dados para seu aplicativo de uma forma que persista ao longo do tempo. Para isso você pode usar Deta Base, que também tem um generoso **nível gratuito**. - -Você também pode ler mais na documentação da Deta. - -## Conceitos de implantação - -Voltando aos conceitos que discutimos em [Deployments Concepts](./concepts.md){.internal-link target=_blank}, veja como cada um deles seria tratado com a Deta: - -* **HTTPS**: Realizado pela Deta, eles fornecerão um subdomínio e lidarão com HTTPS automaticamente. -* **Executando na inicialização**: Realizado pela Deta, como parte de seu serviço. -* **Reinicialização**: Realizado pela Deta, como parte de seu serviço. -* **Replicação**: Realizado pela Deta, como parte de seu serviço. -* **Memória**: Limite predefinido pela Deta, você pode contatá-los para aumentá-lo. -* **Etapas anteriores a inicialização**: Não suportado diretamente, você pode fazê-lo funcionar com o sistema Cron ou scripts adicionais. - -!!! note "Nota" - O Deta foi projetado para facilitar (e gratuitamente) a implantação rápida de aplicativos simples. - - Ele pode simplificar vários casos de uso, mas, ao mesmo tempo, não suporta outros, como o uso de bancos de dados externos (além do próprio sistema de banco de dados NoSQL da Deta), máquinas virtuais personalizadas, etc. - - Você pode ler mais detalhes na documentação da Deta para ver se é a escolha certa para você. diff --git a/docs/pt/docs/external-links.md b/docs/pt/docs/external-links.md index 6ec6c3a27cbed..77ec323511309 100644 --- a/docs/pt/docs/external-links.md +++ b/docs/pt/docs/external-links.md @@ -9,70 +9,21 @@ Aqui tem uma lista, incompleta, de algumas delas. !!! tip "Dica" Se você tem um artigo, projeto, ferramenta ou qualquer coisa relacionada ao **FastAPI** que ainda não está listada aqui, crie um _Pull Request_ adicionando ele. -## Artigos +{% for section_name, section_content in external_links.items() %} -### Inglês +## {{ section_name }} -{% if external_links %} -{% for article in external_links.articles.english %} +{% for lang_name, lang_content in section_content.items() %} -* {{ article.title }} by {{ article.author }}. -{% endfor %} -{% endif %} - -### Japonês - -{% if external_links %} -{% for article in external_links.articles.japanese %} - -* {{ article.title }} by {{ article.author }}. -{% endfor %} -{% endif %} +### {{ lang_name }} -### Vietnamita +{% for item in lang_content %} -{% if external_links %} -{% for article in external_links.articles.vietnamese %} +* {{ item.title }} by {{ item.author }}. -* {{ article.title }} by {{ article.author }}. {% endfor %} -{% endif %} - -### Russo - -{% if external_links %} -{% for article in external_links.articles.russian %} - -* {{ article.title }} by {{ article.author }}. {% endfor %} -{% endif %} - -### Alemão - -{% if external_links %} -{% for article in external_links.articles.german %} - -* {{ article.title }} by {{ article.author }}. -{% endfor %} -{% endif %} - -## Podcasts - -{% if external_links %} -{% for article in external_links.podcasts.english %} - -* {{ article.title }} by {{ article.author }}. -{% endfor %} -{% endif %} - -## Palestras - -{% if external_links %} -{% for article in external_links.talks.english %} - -* {{ article.title }} by {{ article.author }}. {% endfor %} -{% endif %} ## Projetos diff --git a/docs/pt/docs/fastapi-people.md b/docs/pt/docs/fastapi-people.md index 964cac68f1cd5..20061bfd938ba 100644 --- a/docs/pt/docs/fastapi-people.md +++ b/docs/pt/docs/fastapi-people.md @@ -40,7 +40,7 @@ Estes são os usuários que estão [helping others the most with issues (questio {% if people %}
-{% for user in people.last_month_active %} +{% for user in people.last_month_experts[:10] %}
@{{ user.login }}
Issues respondidas: {{ user.count }}
{% endfor %} @@ -59,7 +59,7 @@ Eles provaram ser especialistas ajudando muitos outros. ✨ {% if people %}
-{% for user in people.experts %} +{% for user in people.experts[:50] %}
@{{ user.login }}
Issues respondidas: {{ user.count }}
{% endfor %} @@ -77,7 +77,7 @@ Eles contribuíram com o código-fonte, documentação, traduções, etc. 📦 {% if people %}
-{% for user in people.top_contributors %} +{% for user in people.top_contributors[:50] %}
@{{ user.login }}
Pull Requests: {{ user.count }}
{% endfor %} @@ -101,7 +101,7 @@ Os **Top Revisores** 🕵️ revisaram a maior parte de Pull Requests de outros, {% if people %}
-{% for user in people.top_reviewers %} +{% for user in people.top_translations_reviewers[:50] %}
@{{ user.login }}
Revisões: {{ user.count }}
{% endfor %} diff --git a/docs/pt/docs/features.md b/docs/pt/docs/features.md index bd0db8e762852..64efeeae1baa7 100644 --- a/docs/pt/docs/features.md +++ b/docs/pt/docs/features.md @@ -25,7 +25,7 @@ Documentação interativa da API e navegação _web_ da interface de usuário. C ### Apenas Python moderno -Tudo é baseado no padrão das declarações de **tipos do Python 3.6** (graças ao Pydantic). Nenhuma sintaxe nova para aprender. Apenas o padrão moderno do Python. +Tudo é baseado no padrão das declarações de **tipos do Python 3.8** (graças ao Pydantic). Nenhuma sintaxe nova para aprender. Apenas o padrão moderno do Python. Se você precisa refrescar a memória rapidamente sobre como usar tipos do Python (mesmo que você não use o FastAPI), confira esse rápido tutorial: [Tipos do Python](python-types.md){.internal-link target=_blank}. @@ -175,7 +175,7 @@ Com **FastAPI**, você terá todos os recursos do **Starlette** (já que FastAPI ## Recursos do Pydantic -**FastAPI** é totalmente compatível com (e baseado no) Pydantic. Então, qualquer código Pydantic adicional que você tiver, também funcionará. +**FastAPI** é totalmente compatível com (e baseado no) Pydantic. Então, qualquer código Pydantic adicional que você tiver, também funcionará. Incluindo bibliotecas externas também baseadas no Pydantic, como ORMs e ODMs para bancos de dados. @@ -190,8 +190,6 @@ Com **FastAPI** você terá todos os recursos do **Pydantic** (já que FastAPI u * Se você conhece os tipos do Python, você sabe como usar o Pydantic. * Vai bem com o/a seu/sua **IDE/linter/cérebro**: * Como as estruturas de dados do Pydantic são apenas instâncias de classes que você define, a auto completação, _linting_, _mypy_ e a sua intuição devem funcionar corretamente com seus dados validados. -* **Rápido**: - * em _benchmarks_, o Pydantic é mais rápido que todas as outras bibliotecas testadas. * Valida **estruturas complexas**: * Use modelos hierárquicos do Pydantic, `List` e `Dict` do `typing` do Python, etc. * Validadores permitem que esquemas de dados complexos sejam limpos e facilmente definidos, conferidos e documentados como JSON Schema. diff --git a/docs/pt/docs/help-fastapi.md b/docs/pt/docs/help-fastapi.md index d82ce3414a7a0..d04905197deec 100644 --- a/docs/pt/docs/help-fastapi.md +++ b/docs/pt/docs/help-fastapi.md @@ -114,8 +114,6 @@ do FastAPI. Use o chat apenas para outro tipo de assunto. -Também existe o chat do Gitter, porém ele não possuí canais e recursos avançados, conversas são mais engessadas, por isso o Discord é mais recomendado. - ### Não faça perguntas no chat Tenha em mente que os chats permitem uma "conversa mais livre", dessa forma é muito fácil fazer perguntas que são muito genéricas e dificeís de responder, assim você pode acabar não sendo respondido. diff --git a/docs/pt/docs/history-design-future.md b/docs/pt/docs/history-design-future.md index 45427ec630735..a7a1776601a2e 100644 --- a/docs/pt/docs/history-design-future.md +++ b/docs/pt/docs/history-design-future.md @@ -54,7 +54,7 @@ Tudo de uma forma que oferecesse a melhor experiência de desenvolvimento para t ## Requisitos -Após testar várias alternativas, eu decidi que usaria o **Pydantic** por suas vantagens. +Após testar várias alternativas, eu decidi que usaria o **Pydantic** por suas vantagens. Então eu contribuí com ele, para deixá-lo completamente de acordo com o JSON Schema, para dar suporte a diferentes maneiras de definir declarações de restrições, e melhorar o suporte a editores (conferências de tipos, auto completações) baseado nos testes em vários editores. diff --git a/docs/pt/docs/index.md b/docs/pt/docs/index.md index 591e7f3d4f69c..05786a0aa112b 100644 --- a/docs/pt/docs/index.md +++ b/docs/pt/docs/index.md @@ -24,7 +24,7 @@ --- -FastAPI é um moderno e rápido (alta performance) _framework web_ para construção de APIs com Python 3.6 ou superior, baseado nos _type hints_ padrões do Python. +FastAPI é um moderno e rápido (alta performance) _framework web_ para construção de APIs com Python 3.8 ou superior, baseado nos _type hints_ padrões do Python. Os recursos chave são: @@ -100,12 +100,12 @@ Se você estiver construindo uma aplicação Starlette para as partes web. -* Pydantic para a parte de dados. +* Pydantic para a parte de dados. ## Instalação @@ -316,7 +316,7 @@ Você faz com tipos padrão do Python moderno. Você não terá que aprender uma nova sintaxe, métodos ou classes de uma biblioteca específica etc. -Apenas **Python 3.6+** padrão. +Apenas **Python 3.8+** padrão. Por exemplo, para um `int`: @@ -436,7 +436,7 @@ Usados por Starlette: * httpx - Necessário se você quiser utilizar o `TestClient`. * jinja2 - Necessário se você quiser utilizar a configuração padrão de templates. -* python-multipart - Necessário se você quiser suporte com "parsing" de formulário, com `request.form()`. +* python-multipart - Necessário se você quiser suporte com "parsing" de formulário, com `request.form()`. * itsdangerous - Necessário para suporte a `SessionMiddleware`. * pyyaml - Necessário para suporte a `SchemaGenerator` da Starlette (você provavelmente não precisará disso com o FastAPI). * graphene - Necessário para suporte a `GraphQLApp`. diff --git a/docs/pt/docs/python-types.md b/docs/pt/docs/python-types.md index 9f12211c74010..52b2dad8efbb7 100644 --- a/docs/pt/docs/python-types.md +++ b/docs/pt/docs/python-types.md @@ -266,7 +266,7 @@ E então, novamente, você recebe todo o suporte do editor: ## Modelos Pydantic - Pydantic é uma biblioteca Python para executar a validação de dados. + Pydantic é uma biblioteca Python para executar a validação de dados. Você declara a "forma" dos dados como classes com atributos. @@ -283,7 +283,7 @@ Retirado dos documentos oficiais dos Pydantic: ``` !!! info "Informação" - Para saber mais sobre o Pydantic, verifique seus documentos . + Para saber mais sobre o Pydantic, verifique seus documentos . **FastAPI** é todo baseado em Pydantic. diff --git a/docs/pt/docs/tutorial/body-multiple-params.md b/docs/pt/docs/tutorial/body-multiple-params.md index 22f5856a69cce..0eaa9664c0799 100644 --- a/docs/pt/docs/tutorial/body-multiple-params.md +++ b/docs/pt/docs/tutorial/body-multiple-params.md @@ -14,7 +14,7 @@ E você também pode declarar parâmetros de corpo como opcionais, definindo o v {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="19-21" {!> ../../../docs_src/body_multiple_params/tutorial001.py!} @@ -44,7 +44,7 @@ Mas você pode também declarar múltiplos parâmetros de corpo, por exemplo, `i {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="22" {!> ../../../docs_src/body_multiple_params/tutorial002.py!} @@ -87,7 +87,7 @@ Se você declará-lo como é, porque é um valor singular, o **FastAPI** assumir Mas você pode instruir o **FastAPI** para tratá-lo como outra chave do corpo usando `Body`: -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="22" {!> ../../../docs_src/body_multiple_params/tutorial003.py!} @@ -143,7 +143,7 @@ Por exemplo: {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="27" {!> ../../../docs_src/body_multiple_params/tutorial004.py!} @@ -172,7 +172,7 @@ como em: {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="17" {!> ../../../docs_src/body_multiple_params/tutorial005.py!} diff --git a/docs/pt/docs/tutorial/body-nested-models.md b/docs/pt/docs/tutorial/body-nested-models.md index 8ab77173e96d0..e039b09b2d8d7 100644 --- a/docs/pt/docs/tutorial/body-nested-models.md +++ b/docs/pt/docs/tutorial/body-nested-models.md @@ -121,7 +121,7 @@ Novamente, apenas fazendo essa declaração, com o **FastAPI**, você ganha: Além dos tipos singulares normais como `str`, `int`, `float`, etc. Você também pode usar tipos singulares mais complexos que herdam de `str`. -Para ver todas as opções possíveis, cheque a documentação para ostipos exoticos do Pydantic. Você verá alguns exemplos no próximo capitulo. +Para ver todas as opções possíveis, 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`: diff --git a/docs/pt/docs/tutorial/body.md b/docs/pt/docs/tutorial/body.md index 99e05ab77e95f..5901b84148d01 100644 --- a/docs/pt/docs/tutorial/body.md +++ b/docs/pt/docs/tutorial/body.md @@ -6,7 +6,7 @@ O corpo da **requisição** é a informação enviada pelo cliente para sua API. Sua API quase sempre irá enviar um corpo na **resposta**. Mas os clientes não necessariamente precisam enviar um corpo em toda **requisição**. -Para declarar um corpo da **requisição**, você utiliza os modelos do Pydantic com todos os seus poderes e benefícios. +Para declarar um corpo da **requisição**, você utiliza os modelos do Pydantic com todos os seus poderes e benefícios. !!! info "Informação" Para enviar dados, você deve usar utilizar um dos métodos: `POST` (Mais comum), `PUT`, `DELETE` ou `PATCH`. diff --git a/docs/pt/docs/tutorial/encoder.md b/docs/pt/docs/tutorial/encoder.md index bb4483fdc8f0f..b9bfbf63bfb3f 100644 --- a/docs/pt/docs/tutorial/encoder.md +++ b/docs/pt/docs/tutorial/encoder.md @@ -26,7 +26,7 @@ A função recebe um objeto, como um modelo Pydantic e retorna uma versão compa {!> ../../../docs_src/encoder/tutorial001_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="5 22" {!> ../../../docs_src/encoder/tutorial001.py!} diff --git a/docs/pt/docs/tutorial/extra-data-types.md b/docs/pt/docs/tutorial/extra-data-types.md index e4b9913dc3387..5d50d89424ac5 100644 --- a/docs/pt/docs/tutorial/extra-data-types.md +++ b/docs/pt/docs/tutorial/extra-data-types.md @@ -36,7 +36,7 @@ Aqui estão alguns dos tipos de dados adicionais que você pode usar: * `datetime.timedelta`: * O `datetime.timedelta` do Python. * Em requisições e respostas será representado como um `float` de segundos totais. - * O Pydantic também permite representá-lo como uma "codificação ISO 8601 diferença de tempo", cheque a documentação para mais informações. + * O Pydantic também permite representá-lo como uma "codificação ISO 8601 diferença de tempo", cheque a documentação para mais informações. * `frozenset`: * Em requisições e respostas, será tratado da mesma forma que um `set`: * Nas requisições, uma lista será lida, eliminando duplicadas e convertendo-a em um `set`. @@ -49,7 +49,7 @@ Aqui estão alguns dos tipos de dados adicionais que você pode usar: * `Decimal`: * O `Decimal` padrão do Python. * Em requisições e respostas será representado como um `float`. -* Você pode checar todos os tipos de dados válidos do Pydantic aqui: Tipos de dados do Pydantic. +* Você pode checar todos os tipos de dados válidos do Pydantic aqui: Tipos de dados do Pydantic. ## Exemplo diff --git a/docs/pt/docs/tutorial/extra-models.md b/docs/pt/docs/tutorial/extra-models.md index dd5407eb2d13e..3b1f6ee54b5ae 100644 --- a/docs/pt/docs/tutorial/extra-models.md +++ b/docs/pt/docs/tutorial/extra-models.md @@ -17,7 +17,7 @@ Isso é especialmente o caso para modelos de usuários, porque: 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 3.8 and above" ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" {!> ../../../docs_src/extra_models/tutorial001.py!} @@ -158,7 +158,7 @@ Toda conversão de dados, validação, documentação, etc. ainda funcionará no Dessa forma, podemos declarar apenas as diferenças entre os modelos (com `password` em texto claro, com `hashed_password` e sem senha): -=== "Python 3.6 and above" +=== "Python 3.8 and above" ```Python hl_lines="9 15-16 19-20 23-24" {!> ../../../docs_src/extra_models/tutorial002.py!} @@ -179,9 +179,9 @@ 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]`. + 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 3.8 and above" ```Python hl_lines="1 14-15 18-20 33" {!> ../../../docs_src/extra_models/tutorial003.py!} @@ -213,7 +213,7 @@ 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 3.8 and above" ```Python hl_lines="1 20" {!> ../../../docs_src/extra_models/tutorial004.py!} @@ -233,7 +233,7 @@ Isso é útil se você não souber os nomes de campo / atributo válidos (que se Neste caso, você pode usar `typing.Dict` (ou simplesmente dict no Python 3.9 e superior): -=== "Python 3.6 and above" +=== "Python 3.8 and above" ```Python hl_lines="1 8" {!> ../../../docs_src/extra_models/tutorial005.py!} diff --git a/docs/pt/docs/tutorial/handling-errors.md b/docs/pt/docs/tutorial/handling-errors.md index 97a2e3eac9531..d9f3d67821b61 100644 --- a/docs/pt/docs/tutorial/handling-errors.md +++ b/docs/pt/docs/tutorial/handling-errors.md @@ -160,7 +160,7 @@ path -> item_id !!! warning "Aviso" Você pode pular estes detalhes técnicos caso eles não sejam importantes para você neste momento. -`RequestValidationError` é uma subclasse do `ValidationError` existente no Pydantic. +`RequestValidationError` é uma subclasse do `ValidationError` existente no Pydantic. **FastAPI** faz uso dele para que você veja o erro no seu log, caso você utilize um modelo de Pydantic em `response_model`, e seus dados tenham erro. diff --git a/docs/pt/docs/tutorial/header-params.md b/docs/pt/docs/tutorial/header-params.md index bc8843327fb01..4bdfb7e9cd62f 100644 --- a/docs/pt/docs/tutorial/header-params.md +++ b/docs/pt/docs/tutorial/header-params.md @@ -12,7 +12,7 @@ Primeiro importe `Header`: {!> ../../../docs_src/header_params/tutorial001_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="3" {!> ../../../docs_src/header_params/tutorial001.py!} @@ -30,7 +30,7 @@ O primeiro valor é o valor padrão, você pode passar todas as validações adi {!> ../../../docs_src/header_params/tutorial001_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9" {!> ../../../docs_src/header_params/tutorial001.py!} @@ -66,7 +66,7 @@ Se por algum motivo você precisar desabilitar a conversão automática de subli {!> ../../../docs_src/header_params/tutorial002_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="10" {!> ../../../docs_src/header_params/tutorial002.py!} @@ -97,7 +97,7 @@ Por exemplo, para declarar um cabeçalho de `X-Token` que pode aparecer mais de {!> ../../../docs_src/header_params/tutorial003_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9" {!> ../../../docs_src/header_params/tutorial003.py!} diff --git a/docs/pt/docs/tutorial/path-operation-configuration.md b/docs/pt/docs/tutorial/path-operation-configuration.md index e0a23f6655e39..13a87240f1b84 100644 --- a/docs/pt/docs/tutorial/path-operation-configuration.md +++ b/docs/pt/docs/tutorial/path-operation-configuration.md @@ -13,7 +13,7 @@ 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 3.8 and above" ```Python hl_lines="3 17" {!> ../../../docs_src/path_operation_configuration/tutorial001.py!} @@ -42,7 +42,7 @@ Esse código de status será usado na resposta e será adicionado ao esquema Ope 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 3.8 and above" ```Python hl_lines="17 22 27" {!> ../../../docs_src/path_operation_configuration/tutorial002.py!} @@ -80,7 +80,7 @@ Nestes casos, pode fazer sentido armazenar as tags em um `Enum`. Você pode adicionar um `summary` e uma `description`: -=== "Python 3.6 and above" +=== "Python 3.8 and above" ```Python hl_lines="20-21" {!> ../../../docs_src/path_operation_configuration/tutorial003.py!} @@ -104,7 +104,7 @@ Como as descrições tendem a ser longas e cobrir várias linhas, você pode dec 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 3.8 and above" ```Python hl_lines="19-27" {!> ../../../docs_src/path_operation_configuration/tutorial004.py!} @@ -131,7 +131,7 @@ Ela será usada nas documentações interativas: Você pode especificar a descrição da resposta com o parâmetro `response_description`: -=== "Python 3.6 and above" +=== "Python 3.8 and above" ```Python hl_lines="21" {!> ../../../docs_src/path_operation_configuration/tutorial005.py!} diff --git a/docs/pt/docs/tutorial/path-params-numeric-validations.md b/docs/pt/docs/tutorial/path-params-numeric-validations.md index ec9b74b300d2b..eb0d31dc34ecc 100644 --- a/docs/pt/docs/tutorial/path-params-numeric-validations.md +++ b/docs/pt/docs/tutorial/path-params-numeric-validations.md @@ -12,7 +12,7 @@ Primeiro, importe `Path` de `fastapi`: {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="3" {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} @@ -30,7 +30,7 @@ Por exemplo para declarar um valor de metadado `title` para o parâmetro de rota {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="10" {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} diff --git a/docs/pt/docs/tutorial/path-params.md b/docs/pt/docs/tutorial/path-params.md index 5de3756ed6cb6..be2b7f7a45309 100644 --- a/docs/pt/docs/tutorial/path-params.md +++ b/docs/pt/docs/tutorial/path-params.md @@ -93,7 +93,7 @@ Da mesma forma, existem muitas ferramentas compatíveis. Incluindo ferramentas d ## Pydantic -Toda a validação de dados é feita por baixo dos panos pelo Pydantic, então você tem todos os benefícios disso. E assim você sabe que está em boas mãos. +Toda a validação de dados é feita por baixo dos panos pelo Pydantic, então você tem todos os benefícios disso. E assim você sabe que está em boas mãos. Você pode usar as mesmas declarações de tipo com `str`, `float`, `bool` e muitos outros tipos complexos de dados. @@ -236,7 +236,6 @@ Então, você poderia usar ele com: Com o **FastAPI**, usando as declarações de tipo do Python, você obtém: * Suporte no editor: verificação de erros, e opção de autocompletar, etc. -* Parsing de dados * "Parsing" de dados * Validação de dados * Anotação da API e documentação automática diff --git a/docs/pt/docs/tutorial/query-params.md b/docs/pt/docs/tutorial/query-params.md index 3ada4fd213cb5..08bb99dbc80c9 100644 --- a/docs/pt/docs/tutorial/query-params.md +++ b/docs/pt/docs/tutorial/query-params.md @@ -69,7 +69,7 @@ Da mesma forma, você pode declarar parâmetros de consulta opcionais, definindo {!> ../../../docs_src/query_params/tutorial002_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9" {!> ../../../docs_src/query_params/tutorial002.py!} @@ -91,7 +91,7 @@ Você também pode declarar tipos `bool`, e eles serão convertidos: {!> ../../../docs_src/query_params/tutorial003_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9" {!> ../../../docs_src/query_params/tutorial003.py!} @@ -143,7 +143,7 @@ Eles serão detectados pelo nome: {!> ../../../docs_src/query_params/tutorial004_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="8 10" {!> ../../../docs_src/query_params/tutorial004.py!} @@ -209,7 +209,7 @@ E claro, você pode definir alguns parâmetros como obrigatórios, alguns possui {!> ../../../docs_src/query_params/tutorial006_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="10" {!> ../../../docs_src/query_params/tutorial006.py!} diff --git a/docs/pt/docs/tutorial/request-forms-and-files.md b/docs/pt/docs/tutorial/request-forms-and-files.md index 259f262f443fa..22954761b789b 100644 --- a/docs/pt/docs/tutorial/request-forms-and-files.md +++ b/docs/pt/docs/tutorial/request-forms-and-files.md @@ -3,7 +3,7 @@ Você pode definir arquivos e campos de formulário ao mesmo tempo usando `File` e `Form`. !!! info "Informação" - Para receber arquivos carregados e/ou dados de formulário, primeiro instale `python-multipart`. + Para receber arquivos carregados e/ou dados de formulário, primeiro instale `python-multipart`. Por exemplo: `pip install python-multipart`. diff --git a/docs/pt/docs/tutorial/request-forms.md b/docs/pt/docs/tutorial/request-forms.md index b6c1b0e753316..0eb67391be34f 100644 --- a/docs/pt/docs/tutorial/request-forms.md +++ b/docs/pt/docs/tutorial/request-forms.md @@ -3,7 +3,7 @@ Quando você precisar receber campos de formulário ao invés de JSON, você pode usar `Form`. !!! info "Informação" - Para usar formulários, primeiro instale `python-multipart`. + Para usar formulários, primeiro instale `python-multipart`. Ex: `pip install python-multipart`. diff --git a/docs/pt/docs/tutorial/schema-extra-example.md b/docs/pt/docs/tutorial/schema-extra-example.md new file mode 100644 index 0000000000000..d04dc1a26314b --- /dev/null +++ b/docs/pt/docs/tutorial/schema-extra-example.md @@ -0,0 +1,109 @@ +# Declare um exemplo dos dados da requisição + +Você pode declarar exemplos dos dados que a sua aplicação pode receber. + +Aqui estão várias formas de se fazer isso. + +## `schema_extra` do Pydantic + +Você pode declarar um `example` para um modelo Pydantic usando `Config` e `schema_extra`, conforme descrito em Documentação do Pydantic: Schema customization: + +```Python hl_lines="15-23" +{!../../../docs_src/schema_extra_example/tutorial001.py!} +``` + +Essas informações extras serão adicionadas como se encontram no **JSON Schema** de resposta desse modelo e serão usadas na documentação da API. + +!!! tip "Dica" + Você pode usar a mesma técnica para estender o JSON Schema e adicionar suas próprias informações extras de forma personalizada. + + Por exemplo, você pode usar isso para adicionar metadados para uma interface de usuário de front-end, etc. + +## `Field` de argumentos adicionais + +Ao usar `Field ()` com modelos Pydantic, você também pode declarar informações extras para o **JSON Schema** passando quaisquer outros argumentos arbitrários para a função. + +Você pode usar isso para adicionar um `example` para cada campo: + +```Python hl_lines="4 10-13" +{!../../../docs_src/schema_extra_example/tutorial002.py!} +``` + +!!! warning "Atenção" + Lembre-se de que esses argumentos extras passados ​​não adicionarão nenhuma validação, apenas informações extras, para fins de documentação. + +## `example` e `examples` no OpenAPI + +Ao usar quaisquer dos: + +* `Path()` +* `Query()` +* `Header()` +* `Cookie()` +* `Body()` +* `Form()` +* `File()` + +você também pode declarar um dado `example` ou um grupo de `examples` com informações adicionais que serão adicionadas ao **OpenAPI**. + +### `Body` com `example` + +Aqui nós passamos um `example` dos dados esperados por `Body()`: + +```Python hl_lines="21-26" +{!../../../docs_src/schema_extra_example/tutorial003.py!} +``` + +### Exemplo na UI da documentação + +Com qualquer um dos métodos acima, os `/docs` vão ficar assim: + + + +### `Body` com vários `examples` + +Alternativamente ao único `example`, você pode passar `examples` usando um `dict` com **vários examples**, cada um com informações extras que serão adicionadas no **OpenAPI** também. + +As chaves do `dict` identificam cada exemplo, e cada valor é outro `dict`. + +Cada `dict` de exemplo específico em `examples` pode conter: + +* `summary`: Pequena descrição do exemplo. +* `description`: Uma descrição longa que pode conter texto em Markdown. +* `value`: O próprio exemplo mostrado, ex: um `dict`. +* `externalValue`: alternativa ao `value`, uma URL apontando para o exemplo. Embora isso possa não ser suportado por tantas ferramentas quanto `value`. + +```Python hl_lines="22-48" +{!../../../docs_src/schema_extra_example/tutorial004.py!} +``` + +### Exemplos na UI da documentação + +Com `examples` adicionado a `Body()`, os `/docs` vão ficar assim: + + + +## Detalhes técnicos + +!!! warning "Atenção" + Esses são detalhes muito técnicos sobre os padrões **JSON Schema** e **OpenAPI**. + + Se as ideias explicadas acima já funcionam para você, isso pode ser o suficiente, e você provavelmente não precisa desses detalhes, fique à vontade para pular. + +Quando você adiciona um exemplo dentro de um modelo Pydantic, usando `schema_extra` ou` Field(example="something") `esse exemplo é adicionado ao **JSON Schema** para esse modelo Pydantic. + +E esse **JSON Schema** do modelo Pydantic está incluído no **OpenAPI** da sua API e, em seguida, é usado na UI da documentação. + +O **JSON Schema** na verdade não tem um campo `example` nos padrões. Versões recentes do JSON Schema definem um campo `examples`, mas o OpenAPI 3.0.3 é baseado numa versão mais antiga do JSON Schema que não tinha `examples`. + +Por isso, o OpenAPI 3.0.3 definiu o seu próprio `example` para a versão modificada do **JSON Schema** que é usada, para o mesmo próposito (mas é apenas `example` no singular, não `examples`), e é isso que é usado pela UI da documentação da API(usando o Swagger UI). + +Portanto, embora `example` não seja parte do JSON Schema, é parte da versão customizada do JSON Schema usada pelo OpenAPI, e é isso que vai ser usado dentro da UI de documentação. + +Mas quando você usa `example` ou `examples` com qualquer um dos outros utilitários (`Query()`, `Body()`, etc.) esses exemplos não são adicionados ao JSON Schema que descreve esses dados (nem mesmo para versão própria do OpenAPI do JSON Schema), eles são adicionados diretamente à declaração da *operação de rota* no OpenAPI (fora das partes do OpenAPI que usam o JSON Schema). + +Para `Path()`, `Query()`, `Header()`, e `Cookie()`, o `example` e `examples` são adicionados a definição do OpenAPI, dentro do `Parameter Object` (na especificação). + +E para `Body()`, `File()`, e `Form()`, o `example` e `examples` são de maneira equivalente adicionados para a definição do OpenAPI, dentro do `Request Body Object`, no campo `content`, no `Media Type Object` (na especificação). + +Por outro lado, há uma versão mais recente do OpenAPI: **3.1.0**, lançada recentemente. Baseado no JSON Schema mais recente e a maioria das modificações da versão customizada do OpenAPI do JSON Schema são removidas, em troca dos recursos das versões recentes do JSON Schema, portanto, todas essas pequenas diferenças são reduzidas. No entanto, a UI do Swagger atualmente não oferece suporte a OpenAPI 3.1.0, então, por enquanto, é melhor continuar usando as opções acima. diff --git a/docs/pt/docs/tutorial/security/first-steps.md b/docs/pt/docs/tutorial/security/first-steps.md index ed07d1c963102..395621d3b6f85 100644 --- a/docs/pt/docs/tutorial/security/first-steps.md +++ b/docs/pt/docs/tutorial/security/first-steps.md @@ -26,7 +26,7 @@ Copie o exemplo em um arquivo `main.py`: ## Execute-o !!! informação - Primeiro, instale `python-multipart`. + Primeiro, instale `python-multipart`. Ex: `pip install python-multipart`. diff --git a/docs/ru/docs/alternatives.md b/docs/ru/docs/alternatives.md index 9e3c497d10b41..24a45fa55fa21 100644 --- a/docs/ru/docs/alternatives.md +++ b/docs/ru/docs/alternatives.md @@ -384,7 +384,7 @@ Hug был одним из первых фреймворков, реализов ## Что используется в **FastAPI** -### Pydantic +### Pydantic Pydantic - это библиотека для валидации данных, сериализации и документирования (используя JSON Schema), основываясь на подсказках типов Python, что делает его чрезвычайно интуитивным. diff --git a/docs/ru/docs/deployment/docker.md b/docs/ru/docs/deployment/docker.md new file mode 100644 index 0000000000000..f045ca944811f --- /dev/null +++ b/docs/ru/docs/deployment/docker.md @@ -0,0 +1,700 @@ +# FastAPI и Docker-контейнеры + +При развёртывании приложений FastAPI, часто начинают с создания **образа контейнера на основе Linux**. Обычно для этого используют **Docker**. Затем можно развернуть такой контейнер на сервере одним из нескольких способов. + +Использование контейнеров на основе Linux имеет ряд преимуществ, включая **безопасность**, **воспроизводимость**, **простоту** и прочие. + +!!! tip "Подсказка" + Торопитесь или уже знакомы с этой технологией? Перепрыгните на раздел [Создать Docker-образ для FastAPI 👇](#docker-fastapi) + +
+Развернуть Dockerfile 👀 + +```Dockerfile +FROM python:3.9 + +WORKDIR /code + +COPY ./requirements.txt /code/requirements.txt + +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt + +COPY ./app /code/app + +CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] + +# Если используете прокси-сервер, такой как Nginx или Traefik, добавьте --proxy-headers +# CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80", "--proxy-headers"] +``` + +
+ +## Что такое "контейнер" + +Контейнеризация - это **легковесный** способ упаковать приложение, включая все его зависимости и необходимые файлы, чтобы изолировать его от других контейнеров (других приложений и компонентов) работающих на этой же системе. + +Контейнеры, основанные на Linux, запускаются используя ядро Linux хоста (машины, виртуальной машины, облачного сервера и т.п.). Это значит, что они очень легковесные (по сравнению с полноценными виртуальными машинами, полностью эмулирующими работу операционной системы). + +Благодаря этому, контейнеры потребляют **малое количество ресурсов**, сравнимое с процессом запущенным напрямую (виртуальная машина потребует гораздо больше ресурсов). + +Контейнеры также имеют собственные запущенные **изолированные** процессы (но часто только один процесс), файловую систему и сеть, что упрощает развёртывание, разработку, управление доступом и т.п. + +## Что такое "образ контейнера" + +Для запуска **контейнера** нужен **образ контейнера**. + +Образ контейнера - это **замороженная** версия всех файлов, переменных окружения, программ и команд по умолчанию, необходимых для работы приложения. **Замороженный** - означает, что **образ** не запущен и не выполняется, это всего лишь упакованные вместе файлы и метаданные. + +В отличие от **образа контейнера**, хранящего неизменное содержимое, под термином **контейнер** подразумевают запущенный образ, то есть объёкт, который **исполняется**. + +Когда **контейнер** запущен (на основании **образа**), он может создавать и изменять файлы, переменные окружения и т.д. Эти изменения будут существовать только внутри контейнера, но не будут сохраняться в образе контейнера (не будут сохранены на диск). + +Образ контейнера можно сравнить с файлом, содержащем **программу**, например, как файл `main.py`. + +И **контейнер** (в отличие от **образа**) - это на самом деле выполняемый экземпляр образа, примерно как **процесс**. По факту, контейнер запущен только когда запущены его процессы (чаще, всего один процесс) и остановлен, когда запущенных процессов нет. + +## Образы контейнеров + +Docker является одним оз основных инструментов для создания **образов** и **контейнеров** и управления ими. + +Существует общедоступный Docker Hub с подготовленными **официальными образами** многих инструментов, окружений, баз данных и приложений. + +К примеру, есть официальный образ Python. + +Также там представлены и другие полезные образы, такие как базы данных: + +* PostgreSQL +* MySQL +* MongoDB +* Redis + +и т.п. + +Использование подготовленных образов значительно упрощает **комбинирование** и использование разных инструментов. Например, Вы можете попытаться использовать новую базу данных. В большинстве случаев можно использовать **официальный образ** и всего лишь указать переменные окружения. + +Таким образом, Вы можете изучить, что такое контейнеризация и Docker, и использовать полученные знания с разными инструментами и компонентами. + +Так, Вы можете запустить одновременно **множество контейнеров** с базой данных, Python-приложением, веб-сервером, React-приложением и соединить их вместе через внутреннюю сеть. + +Все системы управления контейнерами (такие, как Docker или Kubernetes) имеют встроенные возможности для организации такого сетевого взаимодействия. + +## Контейнеры и процессы + +Обычно **образ контейнера** содержит метаданные предустановленной программы или команду, которую следует выполнить при запуске **контейнера**. Также он может содержать параметры, передаваемые предустановленной программе. Похоже на то, как если бы Вы запускали такую программу через терминал. + +Когда **контейнер** запущен, он будет выполнять прописанные в нём команды и программы. Но Вы можете изменить его так, чтоб он выполнял другие команды и программы. + +Контейнер буде работать до тех пор, пока выполняется его **главный процесс** (команда или программа). + +В контейнере обычно выполняется **только один процесс**, но от его имени можно запустить другие процессы, тогда в этом же в контейнере будет выполняться **множество процессов**. + +Контейнер не считается запущенным, если в нём **не выполняется хотя бы один процесс**. Если главный процесс остановлен, значит и контейнер остановлен. + +## Создать Docker-образ для FastAPI + +Что ж, давайте ужё создадим что-нибудь! 🚀 + +Я покажу Вам, как собирать **Docker-образ** для FastAPI **с нуля**, основываясь на **официальном образе Python**. + +Такой подход сгодится для **большинства случаев**, например: + +* Использование с **Kubernetes** или аналогичным инструментом +* Запуск в **Raspberry Pi** +* Использование в облачных сервисах, запускающих образы контейнеров для Вас и т.п. + +### Установить зависимости + +Обычно Вашему приложению необходимы **дополнительные библиотеки**, список которых находится в отдельном файле. + +На название и содержание такого файла влияет выбранный Вами инструмент **установки** этих библиотек (зависимостей). + +Чаще всего это простой файл `requirements.txt` с построчным перечислением библиотек и их версий. + +При этом Вы, для выбора версий, будете использовать те же идеи, что упомянуты на странице [О версиях FastAPI](./versions.md){.internal-link target=_blank}. + +Ваш файл `requirements.txt` может выглядеть как-то так: + +``` +fastapi>=0.68.0,<0.69.0 +pydantic>=1.8.0,<2.0.0 +uvicorn>=0.15.0,<0.16.0 +``` + +Устанавливать зависимости проще всего с помощью `pip`: + +
+ +```console +$ pip install -r requirements.txt +---> 100% +Successfully installed fastapi pydantic uvicorn +``` + +
+ +!!! info "Информация" + Существуют и другие инструменты управления зависимостями. + + В этом же разделе, но позже, я покажу Вам пример использования Poetry. 👇 + +### Создать приложение **FastAPI** + +* Создайте директорию `app` и перейдите в неё. +* Создайте пустой файл `__init__.py`. +* Создайте файл `main.py` и заполните его: + +```Python +from typing import Union + +from fastapi import FastAPI + +app = FastAPI() + + +@app.get("/") +def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} +``` + +### Dockerfile + +В этой же директории создайте файл `Dockerfile` и заполните его: + +```{ .dockerfile .annotate } +# (1) +FROM python:3.9 + +# (2) +WORKDIR /code + +# (3) +COPY ./requirements.txt /code/requirements.txt + +# (4) +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt + +# (5) +COPY ./app /code/app + +# (6) +CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] +``` + +1. Начните с официального образа Python, который будет основой для образа приложения. + +2. Укажите, что в дальнейшем команды запускаемые в контейнере, будут выполняться в директории `/code`. + + Инструкция создаст эту директорию внутри контейнера и мы поместим в неё файл `requirements.txt` и директорию `app`. + +3. Скопируете файл с зависимостями из текущей директории в `/code`. + + Сначала копируйте **только** файл с зависимостями. + + Этот файл **изменяется довольно редко**, Docker ищет изменения при постройке образа и если не находит, то использует **кэш**, в котором хранятся предыдущии версии сборки образа. + +4. Установите библиотеки перечисленные в файле с зависимостями. + + Опция `--no-cache-dir` указывает `pip` не сохранять загружаемые библиотеки на локальной машине для использования их в случае повторной загрузки. В контейнере, в случае пересборки этого шага, они всё равно будут удалены. + + !!! note "Заметка" + Опция `--no-cache-dir` нужна только для `pip`, она никак не влияет на Docker или контейнеры. + + Опция `--upgrade` указывает `pip` обновить библиотеки, емли они уже установлены. + + Ка и в предыдущем шаге с копированием файла, этот шаг также будет использовать **кэш Docker** в случае отсутствия изменений. + + Использрвание кэша, особенно на этом шаге, позволит Вам **сэкономить** кучу времени при повторной сборке образа, так как зависимости будут сохранены в кеше, а не **загружаться и устанавливаться каждый раз**. + +5. Скопируйте директорию `./app` внутрь директории `/code` (в контейнере). + + Так как в этой директории расположен код, который **часто изменяется**, то использование **кэша** на этом шаге будет наименее эффективно, а значит лучше поместить этот шаг **ближе к концу** `Dockerfile`, дабы не терять выгоду от оптимизации предыдущих шагов. + +6. Укажите **команду**, запускающую сервер `uvicorn`. + + `CMD` принимает список строк, разделённых запятыми, но при выполнении объединит их через пробел, собрав из них одну команду, которую Вы могли бы написать в терминале. + + Эта команда будет выполнена в **текущей рабочей директории**, а именно в директории `/code`, котоая указана командой `WORKDIR /code`. + + Так как команда выполняется внутрии директории `/code`, в которую мы поместили папку `./app` с приложением, то **Uvicorn** сможет найти и **импортировать** объект `app` из файла `app.main`. + +!!! tip "Подсказка" + Если ткнёте на кружок с плюсом, то увидите пояснения. 👆 + +На данном этапе структура проекта должны выглядеть так: + +``` +. +├── app +│   ├── __init__.py +│ └── main.py +├── Dockerfile +└── requirements.txt +``` + +#### Использование прокси-сервера + +Если Вы запускаете контейнер за прокси-сервером завершения TLS (балансирующего нагрузку), таким как Nginx или Traefik, добавьте опцию `--proxy-headers`, которая укажет Uvicorn, что он работает позади прокси-сервера и может доверять заголовкам отправляемым им. + +```Dockerfile +CMD ["uvicorn", "app.main:app", "--proxy-headers", "--host", "0.0.0.0", "--port", "80"] +``` + +#### Кэш Docker'а + +В нашем `Dockerfile` использована полезная хитрость, когда сначала копируется **только файл с зависимостями**, а не вся папка с кодом приложения. + +```Dockerfile +COPY ./requirements.txt /code/requirements.txt +``` + +Docker и подобные ему инструменты **создают** образы контейнеров **пошагово**, добавляя **один слой над другим**, начиная с первой строки `Dockerfile` и добавляя файлы, создаваемые при выполнении каждой инструкции из `Dockerfile`. + +При создании образа используется **внутренний кэш** и если в файлах нет изменений с момента последней сборки образа, то будет **переиспользован** ранее созданный слой образа, а не повторное копирование файлов и создание слоя с нуля. +Заметьте, что так как слой следующего шага зависит от слоя предыдущего, то изменения внесённые в промежуточный слой, также повлияют на последующие. + +Избегание копирования файлов не обязательно улучшит ситуацию, но использование кэша на одном шаге, позволит **использовать кэш и на следующих шагах**. Например, можно использовать кэш при установке зависимостей: + +```Dockerfile +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt +``` + +Файл со списком зависимостей **изменяется довольно редко**. Так что выполнив команду копирования только этого файла, Docker сможет **использовать кэш** на этом шаге. + +А затем **использовать кэш и на следующем шаге**, загружающем и устанавливающем зависимости. И вот тут-то мы и **сэкономим много времени**. ✨ ...а не будем томиться в тягостном ожидании. 😪😆 + +Для загрузки и установки необходимых библиотек **может понадобиться несколько минут**, но использование **кэша** занимает несколько **секунд** максимум. + +И так как во время разработки Вы будете часто пересобирать контейнер для проверки работоспособности внесённых изменений, то сэкономленные минуты сложатся в часы, а то и дни. + +Так как папка с кодом приложения **изменяется чаще всего**, то мы расположили её в конце `Dockerfile`, ведь после внесённых в код изменений кэш не будет использован на этом и следующих шагах. + +```Dockerfile +COPY ./app /code/app +``` + +### Создать Docker-образ + +Теперь, когда все файлы на своих местах, давайте создадим образ контейнера. + +* Перейдите в директорию проекта (в ту, где расположены `Dockerfile` и папка `app` с приложением). +* Создай образ приложения FastAPI: + +
+ +```console +$ docker build -t myimage . + +---> 100% +``` + +
+ +!!! tip "Подсказка" + Обратите внимание, что в конце написана точка - `.`, это то же самое что и `./`, тем самым мы указываем Docker директорию, из которой нужно выполнять сборку образа контейнера. + + В данном случае это та же самая директория (`.`). + +### Запуск Docker-контейнера + +* Запустите контейнер, основанный на Вашем образе: + +
+ +```console +$ docker run -d --name mycontainer -p 80:80 myimage +``` + +
+ +## Проверка + +Вы можете проверить, что Ваш Docker-контейнер работает перейдя по ссылке: http://192.168.99.100/items/5?q=somequery или http://127.0.0.1/items/5?q=somequery (или похожей, которую использует Ваш Docker-хост). + +Там Вы увидите: + +```JSON +{"item_id": 5, "q": "somequery"} +``` + +## Интерактивная документация API + +Теперь перейдите по ссылке http://192.168.99.100/docs или http://127.0.0.1/docs (или похожей, которую использует Ваш Docker-хост). + +Здесь Вы увидите автоматическую интерактивную документацию API (предоставляемую Swagger UI): + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +## Альтернативная документация API + +Также Вы можете перейти по ссылке http://192.168.99.100/redoc or http://127.0.0.1/redoc (или похожей, которую использует Ваш Docker-хост). + +Здесь Вы увидите альтернативную автоматическую документацию API (предоставляемую ReDoc): + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +## Создание Docker-образа на основе однофайлового приложения FastAPI + +Если Ваше приложение FastAPI помещено в один файл, например, `main.py` и структура Ваших файлов похожа на эту: + +``` +. +├── Dockerfile +├── main.py +└── requirements.txt +``` + +Вам нужно изменить в `Dockerfile` соответствующие пути копирования файлов: + +```{ .dockerfile .annotate hl_lines="10 13" } +FROM python:3.9 + +WORKDIR /code + +COPY ./requirements.txt /code/requirements.txt + +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt + +# (1) +COPY ./main.py /code/ + +# (2) +CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] +``` + +1. Скопируйте непосредственно файл `main.py` в директорию `/code` (не указывайте `./app`). + +2. При запуске Uvicorn укажите ему, что объект `app` нужно импортировать из файла `main` (вместо импортирования из `app.main`). + +Настройте Uvicorn на использование `main` вместо `app.main` для импорта объекта `app`. + +## Концепции развёртывания + +Давайте вспомним о [Концепциях развёртывания](./concepts.md){.internal-link target=_blank} и применим их к контейнерам. + +Контейнеры - это, в основном, инструмент упрощающий **сборку и развёртывание** приложения и они не обязыают к применению какой-то определённой **концепции развёртывания**, а значит мы можем выбирать нужную стратегию. + +**Хорошая новость** в том, что независимо от выбранной стратегии, мы всё равно можем покрыть все концепции развёртывания. 🎉 + +Рассмотрим эти **концепции развёртывания** применительно к контейнерам: + +* Использование более безопасного протокола HTTPS +* Настройки запуска приложения +* Перезагрузка приложения +* Запуск нескольких экземпляров приложения +* Управление памятью +* Использование перечисленных функций перед запуском приложения + +## Использование более безопасного протокола HTTPS + +Если мы определимся, что **образ контейнера** будет содержать только приложение FastAPI, то работу с HTTPS можно организовать **снаружи** контейнера при помощи другого инструмента. + +Это может быть другой контейнер, в котором есть, например, Traefik, работающий с **HTTPS** и **самостоятельно** обновляющий **сертификаты**. + +!!! tip "Подсказка" + Traefik совместим с Docker, Kubernetes и им подобными инструментами. Он очень прост в установке и настройке использования HTTPS для Ваших контейнеров. + +В качестве альтернативы, работу с HTTPS можно доверить облачному провайдеру, если он предоставляет такую услугу. + +## Настройки запуска и перезагрузки приложения + +Обычно **запуском контейнера с приложением** занимается какой-то отдельный инструмент. + +Это может быть сам **Docker**, **Docker Compose**, **Kubernetes**, **облачный провайдер** и т.п. + +В большинстве случаев это простейшие настройки запуска и перезагрузки приложения (при падении). Например, команде запуска Docker-контейнера можно добавить опцию `--restart`. + +Управление запуском и перезагрузкой приложений без использования контейнеров - весьма затруднительно. Но при **работе с контейнерами** - это всего лишь функционал доступный по умолчанию. ✨ + +## Запуск нескольких экземпляров приложения - Указание количества процессов + +Если у Вас есть кластер машин под управлением **Kubernetes**, Docker Swarm Mode, Nomad или аналогичной сложной системой оркестрации контейнеров, скорее всего, вместо использования менеджера процессов (типа Gunicorn и его воркеры) в каждом контейнере, Вы захотите **управлять количеством запущенных экземпляров приложения** на **уровне кластера**. + +В любую из этих систем управления контейнерами обычно встроен способ управления **количеством запущенных контейнеров** для распределения **нагрузки** от входящих запросов на **уровне кластера**. + +В такой ситуации Вы, вероятно, захотите создать **образ Docker**, как [описано выше](#dockerfile), с установленными зависимостями и запускающий **один процесс Uvicorn** вместо того, чтобы запускать Gunicorn управляющий несколькими воркерами Uvicorn. + +### Балансировщик нагрузки + +Обычно при использовании контейнеров один компонент **прослушивает главный порт**. Это может быть контейнер содержащий **прокси-сервер завершения работы TLS** для работы с **HTTPS** или что-то подобное. + +Поскольку этот компонент **принимает запросы** и равномерно **распределяет** их между компонентами, его также называют **балансировщиком нагрузки**. + +!!! tip "Подсказка" + **Прокси-сервер завершения работы TLS** одновременно может быть **балансировщиком нагрузки**. + +Система оркестрации, которую Вы используете для запуска и управления контейнерами, имеет встроенный инструмент **сетевого взаимодействия** (например, для передачи HTTP-запросов) между контейнерами с Вашими приложениями и **балансировщиком нагрузки** (который также может быть **прокси-сервером**). + +### Один балансировщик - Множество контейнеров + +При работе с **Kubernetes** или аналогичными системами оркестрации использование их внутреннней сети позволяет иметь один **балансировщик нагрузки**, который прослушивает **главный** порт и передаёт запросы **множеству запущенных контейнеров** с Вашими приложениями. + +В каждом из контейнеров обычно работает **только один процесс** (например, процесс Uvicorn управляющий Вашим приложением FastAPI). Контейнеры могут быть **идентичными**, запущенными на основе одного и того же образа, но у каждого будут свои отдельные процесс, память и т.п. Таким образом мы получаем преимущества **распараллеливания** работы по **разным ядрам** процессора или даже **разным машинам**. + +Система управления контейнерами с **балансировщиком нагрузки** будет **распределять запросы** к контейнерам с приложениями **по очереди**. То есть каждый запрос будет обработан одним из множества **одинаковых контейнеров** с одним и тем же приложением. + +**Балансировщик нагрузки** может обрабатывать запросы к *разным* приложениям, расположенным в Вашем кластере (например, если у них разные домены или префиксы пути) и передавать запросы нужному контейнеру с требуемым приложением. + +### Один процесс на контейнер + +В этом варианте **в одном контейнере будет запущен только один процесс (Uvicorn)**, а управление изменением количества запущенных копий приложения происходит на уровне кластера. + +Здесь **не нужен** менеджер процессов типа Gunicorn, управляющий процессами Uvicorn, или же Uvicorn, управляющий другими процессами Uvicorn. Достаточно **только одного процесса Uvicorn** на контейнер (но запуск нескольких процессов не запрещён). + +Использование менеджера процессов (Gunicorn или Uvicorn) внутри контейнера только добавляет **излишнее усложнение**, так как управление следует осуществлять системой оркестрации. + +### Множество процессов внутри контейнера для особых случаев + +Безусловно, бывают **особые случаи**, когда может понадобится внутри контейнера запускать **менеджер процессов Gunicorn**, управляющий несколькими **процессами Uvicorn**. + +Для таких случаев Вы можете использовать **официальный Docker-образ** (прим. пер: - *здесь и далее на этой странице, если Вы встретите сочетание "официальный Docker-образ" без уточнений, то автор имеет в виду именно предоставляемый им образ*), где в качестве менеджера процессов используется **Gunicorn**, запускающий несколько **процессов Uvicorn** и некоторые настройки по умолчанию, автоматически устанавливающие количество запущенных процессов в зависимости от количества ядер Вашего процессора. Я расскажу Вам об этом подробнее тут: [Официальный Docker-образ со встроенными Gunicorn и Uvicorn](#docker-gunicorn-uvicorn). + +Некоторые примеры подобных случаев: + +#### Простое приложение + +Вы можете использовать менеджер процессов внутри контейнера, если Ваше приложение **настолько простое**, что у Вас нет необходимости (по крайней мере, пока нет) в тщательных настройках количества процессов и Вам достаточно имеющихся настроек по умолчанию (если используется официальный Docker-образ) для запуска приложения **только на одном сервере**, а не в кластере. + +#### Docker Compose + +С помощью **Docker Compose** можно разворачивать несколько контейнеров на **одном сервере** (не кластере), но при это у Вас не будет простого способа управления количеством запущенных контейнеров с одновременным сохранением общей сети и **балансировки нагрузки**. + +В этом случае можно использовать **менеджер процессов**, управляющий **несколькими процессами**, внутри **одного контейнера**. + +#### Prometheus и прочие причины + +У Вас могут быть и **другие причины**, когда использование **множества процессов** внутри **одного контейнера** будет проще, нежели запуск **нескольких контейнеров** с **единственным процессом** в каждом из них. + +Например (в зависимости от конфигурации), у Вас могут быть инструменты подобные экспортёру Prometheus, которые должны иметь доступ к **каждому запросу** приходящему в контейнер. + +Если у Вас будет **несколько контейнеров**, то Prometheus, по умолчанию, **при сборе метрик** получит их **только с одного контейнера**, который обрабатывает конкретный запрос, вместо **сбора метрик** со всех работающих контейнеров. + +В таком случае может быть проще иметь **один контейнер** со **множеством процессов**, с нужным инструментом (таким как экспортёр Prometheus) в этом же контейнере и собирающем метрики со всех внутренних процессов этого контейнера. + +--- + +Самое главное - **ни одно** из перечисленных правил не является **высеченным в камне** и Вы не обязаны слепо их повторять. Вы можете использовать эти идеи при **рассмотрении Вашего конкретного случая** и самостоятельно решать, какая из концепции подходит лучше: + +* Использование более безопасного протокола HTTPS +* Настройки запуска приложения +* Перезагрузка приложения +* Запуск нескольких экземпляров приложения +* Управление памятью +* Использование перечисленных функций перед запуском приложения + +## Управление памятью + +При **запуске одного процесса на контейнер** Вы получаете относительно понятный, стабильный и ограниченный объём памяти, потребляемый одним контейнером. + +Вы можете установить аналогичные ограничения по памяти при конфигурировании своей системы управления контейнерами (например, **Kubernetes**). Таким образом система сможет **изменять количество контейнеров** на **доступных ей машинах** приводя в соответствие количество памяти нужной контейнерам с количеством памяти доступной в кластере (наборе доступных машин). + +Если у Вас **простенькое** приложение, вероятно у Вас не будет **необходимости** устанавливать жёсткие ограничения на выделяемую ему память. Но если приложение **использует много памяти** (например, оно использует модели **машинного обучения**), Вам следует проверить, как много памяти ему требуется и отрегулировать **количество контейнеров** запущенных на **каждой машине** (может быть даже добавить машин в кластер). + +Если Вы запускаете **несколько процессов в контейнере**, то должны быть уверены, что эти процессы не **займут памяти больше**, чем доступно для контейнера. + +## Подготовительные шаги при запуске контейнеров + +Есть два основных подхода, которые Вы можете использовать при запуске контейнеров (Docker, Kubernetes и т.п.). + +### Множество контейнеров + +Когда Вы запускаете **множество контейнеров**, в каждом из которых работает **только один процесс** (например, в кластере **Kubernetes**), может возникнуть необходимость иметь **отдельный контейнер**, который осуществит **предварительные шаги перед запуском** остальных контейнеров (например, применяет миграции к базе данных). + +!!! info "Информация" + При использовании Kubernetes, это может быть Инициализирующий контейнер. + +При отсутствии такой необходимости (допустим, не нужно применять миграции к базе данных, а только проверить, что она готова принимать соединения), Вы можете проводить такую проверку в каждом контейнере перед запуском его основного процесса и запускать все контейнеры **одновременно**. + +### Только один контейнер + +Если у Вас несложное приложение для работы которого достаточно **одного контейнера**, но в котором работает **несколько процессов** (или один процесс), то прохождение предварительных шагов можно осуществить в этом же контейнере до запуска основного процесса. Официальный Docker-образ поддерживает такие действия. + +## Официальный Docker-образ с Gunicorn и Uvicorn + +Я подготовил для Вас Docker-образ, в который включён Gunicorn управляющий процессами (воркерами) Uvicorn, в соответствии с концепциями рассмотренными в предыдущей главе: [Рабочие процессы сервера (воркеры) - Gunicorn совместно с Uvicorn](./server-workers.md){.internal-link target=_blank}. + +Этот образ может быть полезен для ситуаций описанных тут: [Множество процессов внутри контейнера для особых случаев](#special-cases). + +* tiangolo/uvicorn-gunicorn-fastapi. + +!!! warning "Предупреждение" + Скорее всего у Вас **нет необходимости** в использовании этого образа или подобного ему и лучше создать свой образ с нуля как описано тут: [Создать Docker-образ для FastAPI](#docker-fastapi). + +В этом образе есть **автоматический** механизм подстройки для запуска **необходимого количества процессов** в соответствии с доступным количеством ядер процессора. + +В нём установлены **разумные значения по умолчанию**, но можно изменять и обновлять конфигурацию с помощью **переменных окружения** или конфигурационных файлов. + +Он также поддерживает прохождение **Подготовительных шагов при запуске контейнеров** при помощи скрипта. + +!!! tip "Подсказка" + Для просмотра всех возможных настроек перейдите на страницу этого Docker-образа: tiangolo/uvicorn-gunicorn-fastapi. + +### Количество процессов в официальном Docker-образе + +**Количество процессов** в этом образе **вычисляется автоматически** и зависит от доступного количества **ядер** центрального процессора. + +Это означает, что он будет пытаться **выжать** из процессора как можно больше **производительности**. + +Но Вы можете изменять и обновлять конфигурацию с помощью **переменных окружения** и т.п. + +Поскольку количество процессов зависит от процессора, на котором работает контейнер, **объём потребляемой памяти** также будет зависеть от этого. + +А значит, если Вашему приложению требуется много оперативной памяти (например, оно использует модели машинного обучения) и Ваш сервер имеет центральный процессор с большим количеством ядер, но **не слишком большим объёмом оперативной памяти**, то может дойти до того, что контейнер попытается занять памяти больше, чем доступно, из-за чего будет падение производительности (или сервер вовсе упадёт). 🚨 + + +### Написание `Dockerfile` + +Итак, теперь мы можем написать `Dockerfile` основанный на этом официальном Docker-образе: + +```Dockerfile +FROM tiangolo/uvicorn-gunicorn-fastapi:python3.9 + +COPY ./requirements.txt /app/requirements.txt + +RUN pip install --no-cache-dir --upgrade -r /app/requirements.txt + +COPY ./app /app +``` + +### Большие приложения + +Если Вы успели ознакомиться с разделом [Приложения содержащие много файлов](../tutorial/bigger-applications.md){.internal-link target=_blank}, состоящие из множества файлов, Ваш Dockerfile может выглядеть так: + +```Dockerfile hl_lines="7" +FROM tiangolo/uvicorn-gunicorn-fastapi:python3.9 + +COPY ./requirements.txt /app/requirements.txt + +RUN pip install --no-cache-dir --upgrade -r /app/requirements.txt + +COPY ./app /app/app +``` + +### Как им пользоваться + +Если Вы используете **Kubernetes** (или что-то вроде того), скорее всего Вам **не нужно** использовать официальный Docker-образ (или другой похожий) в качестве основы, так как управление **количеством запущенных контейнеров** должно быть настроено на уровне кластера. В таком случае лучше **создать образ с нуля**, как описано в разделе Создать [Docker-образ для FastAPI](#docker-fastapi). + +Официальный образ может быть полезен в отдельных случаях, описанных выше в разделе [Множество процессов внутри контейнера для особых случаев](#special-cases). Например, если Ваше приложение **достаточно простое**, не требует запуска в кластере и способно уместиться в один контейнер, то его настройки по умолчанию будут работать довольно хорошо. Или же Вы развертываете его с помощью **Docker Compose**, работаете на одном сервере и т. д + +## Развёртывание образа контейнера + +После создания образа контейнера существует несколько способов его развёртывания. + +Например: + +* С использованием **Docker Compose** при развёртывании на одном сервере +* С использованием **Kubernetes** в кластере +* С использованием режима Docker Swarm в кластере +* С использованием других инструментов, таких как Nomad +* С использованием облачного сервиса, который будет управлять разворачиванием Вашего контейнера + +## Docker-образ и Poetry + +Если Вы пользуетесь Poetry для управления зависимостями Вашего проекта, то можете использовать многоэтапную сборку образа: + +```{ .dockerfile .annotate } +# (1) +FROM python:3.9 as requirements-stage + +# (2) +WORKDIR /tmp + +# (3) +RUN pip install poetry + +# (4) +COPY ./pyproject.toml ./poetry.lock* /tmp/ + +# (5) +RUN poetry export -f requirements.txt --output requirements.txt --without-hashes + +# (6) +FROM python:3.9 + +# (7) +WORKDIR /code + +# (8) +COPY --from=requirements-stage /tmp/requirements.txt /code/requirements.txt + +# (9) +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt + +# (10) +COPY ./app /code/app + +# (11) +CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] +``` + +1. Это первый этап, которому мы дадим имя `requirements-stage`. + +2. Установите директорию `/tmp` в качестве рабочей директории. + + В ней будет создан файл `requirements.txt` + +3. На этом шаге установите Poetry. + +4. Скопируйте файлы `pyproject.toml` и `poetry.lock` в директорию `/tmp`. + + Поскольку название файла написано как `./poetry.lock*` (с `*` в конце), то ничего не сломается, если такой файл не будет найден. + +5. Создайте файл `requirements.txt`. + +6. Это второй (и последний) этап сборки, который и создаст окончательный образ контейнера. + +7. Установите директорию `/code` в качестве рабочей. + +8. Скопируйте файл `requirements.txt` в директорию `/code`. + + Этот файл находится в образе, созданном на предыдущем этапе, которому мы дали имя requirements-stage, потому при копировании нужно написать `--from-requirements-stage`. + +9. Установите зависимости, указанные в файле `requirements.txt`. + +10. Скопируйте папку `app` в папку `/code`. + +11. Запустите `uvicorn`, указав ему использовать объект `app`, расположенный в `app.main`. + +!!! tip "Подсказка" + Если ткнёте на кружок с плюсом, то увидите объяснения, что происходит в этой строке. + +**Этапы сборки Docker-образа** являются частью `Dockerfile` и работают как **временные образы контейнеров**. Они нужны только для создания файлов, используемых в дальнейших этапах. + +Первый этап был нужен только для **установки Poetry** и **создания файла `requirements.txt`**, в которым прописаны зависимости Вашего проекта, взятые из файла `pyproject.toml`. + +На **следующем этапе** `pip` будет использовать файл `requirements.txt`. + +В итоговом образе будет содержаться **только последний этап сборки**, предыдущие этапы будут отброшены. + +При использовании Poetry, имеет смысл использовать **многоэтапную сборку Docker-образа**, потому что на самом деле Вам не нужен Poetry и его зависимости в окончательном образе контейнера, Вам **нужен только** сгенерированный файл `requirements.txt` для установки зависимостей Вашего проекта. + +А на последнем этапе, придерживаясь описанных ранее правил, создаётся итоговый образ + +### Использование прокси-сервера завершения TLS и Poetry + +И снова повторюсь, если используете прокси-сервер (балансировщик нагрузки), такой, как Nginx или Traefik, добавьте в команду запуска опцию `--proxy-headers`: + +```Dockerfile +CMD ["uvicorn", "app.main:app", "--proxy-headers", "--host", "0.0.0.0", "--port", "80"] +``` + +## Резюме + +При помощи систем контейнеризации (таких, как **Docker** и **Kubernetes**), становится довольно просто обрабатывать все **концепции развертывания**: + +* Использование более безопасного протокола HTTPS +* Настройки запуска приложения +* Перезагрузка приложения +* Запуск нескольких экземпляров приложения +* Управление памятью +* Использование перечисленных функций перед запуском приложения + +В большинстве случаев Вам, вероятно, не нужно использовать какой-либо базовый образ, **лучше создать образ контейнера с нуля** на основе официального Docker-образа Python. + +Позаботившись о **порядке написания** инструкций в `Dockerfile`, Вы сможете использовать **кэш Docker'а**, **минимизировав время сборки**, максимально повысив свою производительность (и избежать скуки). 😎 + +В некоторых особых случаях вы можете использовать официальный образ Docker для FastAPI. 🤓 diff --git a/docs/ru/docs/external-links.md b/docs/ru/docs/external-links.md index 4daf65898b0e2..2448ef82ef216 100644 --- a/docs/ru/docs/external-links.md +++ b/docs/ru/docs/external-links.md @@ -9,70 +9,21 @@ !!! tip Если у вас есть статья, проект, инструмент или что-либо, связанное с **FastAPI**, что еще не перечислено здесь, создайте Pull Request. -## Статьи +{% for section_name, section_content in external_links.items() %} -### На английском +## {{ section_name }} -{% if external_links %} -{% for article in external_links.articles.english %} +{% for lang_name, lang_content in section_content.items() %} -* {{ article.title }} by {{ article.author }}. -{% endfor %} -{% endif %} - -### На японском - -{% if external_links %} -{% for article in external_links.articles.japanese %} - -* {{ article.title }} by {{ article.author }}. -{% endfor %} -{% endif %} +### {{ lang_name }} -### На вьетнамском +{% for item in lang_content %} -{% if external_links %} -{% for article in external_links.articles.vietnamese %} +* {{ item.title }} by {{ item.author }}. -* {{ article.title }} by {{ article.author }}. {% endfor %} -{% endif %} - -### На русском - -{% if external_links %} -{% for article in external_links.articles.russian %} - -* {{ article.title }} by {{ article.author }}. {% endfor %} -{% endif %} - -### На немецком - -{% if external_links %} -{% for article in external_links.articles.german %} - -* {{ article.title }} by {{ article.author }}. -{% endfor %} -{% endif %} - -## Подкасты - -{% if external_links %} -{% for article in external_links.podcasts.english %} - -* {{ article.title }} by {{ article.author }}. -{% endfor %} -{% endif %} - -## Talks - -{% if external_links %} -{% for article in external_links.talks.english %} - -* {{ article.title }} by {{ article.author }}. {% endfor %} -{% endif %} ## Проекты diff --git a/docs/ru/docs/fastapi-people.md b/docs/ru/docs/fastapi-people.md index 64ae66a035912..0e42aab69033b 100644 --- a/docs/ru/docs/fastapi-people.md +++ b/docs/ru/docs/fastapi-people.md @@ -5,7 +5,7 @@ ## Создатель и хранитель -Ку! 👋 +Хай! 👋 Это я: @@ -41,7 +41,7 @@ {% if people %}
-{% for user in people.last_month_active %} +{% for user in people.last_month_experts[:10] %}
@{{ user.login }}
Issues replied: {{ user.count }}
{% endfor %} @@ -59,7 +59,7 @@ {% if people %}
-{% for user in people.experts %} +{% for user in people.experts[:50] %}
@{{ user.login }}
Issues replied: {{ user.count }}
{% endfor %} @@ -77,7 +77,7 @@ {% if people %}
-{% for user in people.top_contributors %} +{% for user in people.top_contributors[:50] %}
@{{ user.login }}
Pull Requests: {{ user.count }}
{% endfor %} @@ -102,7 +102,7 @@ {% if people %}
-{% for user in people.top_reviewers %} +{% for user in people.top_translations_reviewers[:50] %}
@{{ user.login }}
Reviews: {{ user.count }}
{% endfor %} diff --git a/docs/ru/docs/features.md b/docs/ru/docs/features.md index e18f7bc87cba5..110c7d31e128a 100644 --- a/docs/ru/docs/features.md +++ b/docs/ru/docs/features.md @@ -27,7 +27,7 @@ ### Только современный Python -Все эти возможности основаны на стандартных **аннотациях типов Python 3.6** (благодаря Pydantic). Не нужно изучать новый синтаксис. Только лишь стандартный современный Python. +Все эти возможности основаны на стандартных **аннотациях типов Python 3.8** (благодаря Pydantic). Не нужно изучать новый синтаксис. Только лишь стандартный современный Python. Если вам нужно освежить знания, как использовать аннотации типов в Python (даже если вы не используете FastAPI), выделите 2 минуты и просмотрите краткое руководство: [Введение в аннотации типов Python¶ ](python-types.md){.internal-link target=_blank}. @@ -177,7 +177,7 @@ FastAPI включает в себя чрезвычайно простую в и ## Особенности и возможности Pydantic -**FastAPI** основан на Pydantic и полностью совместим с ним. Так что, любой дополнительный код Pydantic, который у вас есть, будет также работать. +**FastAPI** основан на Pydantic и полностью совместим с ним. Так что, любой дополнительный код Pydantic, который у вас есть, будет также работать. Включая внешние библиотеки, также основанные на Pydantic, такие как: ORM'ы, ODM'ы для баз данных. @@ -192,8 +192,6 @@ FastAPI включает в себя чрезвычайно простую в и * Если вы знаете аннотации типов в Python, вы знаете, как использовать Pydantic. * Прекрасно сочетается с вашими **IDE/linter/мозгом**: * Потому что структуры данных pydantic - это всего лишь экземпляры классов, определённых вами. Автодополнение, проверка кода, mypy и ваша интуиция - всё будет работать с вашими проверенными данными. -* **Быстродействие**: - * В тестовых замерах Pydantic быстрее, чем все другие проверенные библиотеки. * Проверка **сложных структур**: * Использование иерархических моделей Pydantic; `List`, `Dict` и т.п. из модуля `typing` (входит в стандартную библиотеку Python). * Валидаторы позволяют четко и легко определять, проверять и документировать сложные схемы данных в виде JSON Schema. diff --git a/docs/ru/docs/help-fastapi.md b/docs/ru/docs/help-fastapi.md index a69e37bd8ca77..65ff768d1efef 100644 --- a/docs/ru/docs/help-fastapi.md +++ b/docs/ru/docs/help-fastapi.md @@ -223,8 +223,6 @@ Используйте этот чат только для бесед на отвлечённые темы. -Существует также чат в Gitter, но поскольку в нем нет каналов и расширенных функций, общение в нём сложнее, потому рекомендуемой системой является Discord. - ### Не использовать чаты для вопросов Имейте в виду, что чаты позволяют больше "свободного общения", потому там легко задавать вопросы, которые слишком общие и на которые труднее ответить, так что Вы можете не получить нужные Вам ответы. diff --git a/docs/ru/docs/history-design-future.md b/docs/ru/docs/history-design-future.md index 2a5e428b1b10c..e9572a6d6e3ec 100644 --- a/docs/ru/docs/history-design-future.md +++ b/docs/ru/docs/history-design-future.md @@ -52,7 +52,7 @@ ## Зависимости -Протестировав несколько вариантов, я решил, что в качестве основы буду использовать **Pydantic** и его преимущества. +Протестировав несколько вариантов, я решил, что в качестве основы буду использовать **Pydantic** и его преимущества. По моим предложениям был изменён код этого фреймворка, чтобы сделать его полностью совместимым с JSON Schema, поддержать различные способы определения ограничений и улучшить помощь редакторов (проверки типов, автозаполнение). diff --git a/docs/ru/docs/index.md b/docs/ru/docs/index.md index 30c32e0463389..477567af69df4 100644 --- a/docs/ru/docs/index.md +++ b/docs/ru/docs/index.md @@ -27,7 +27,7 @@ --- -FastAPI — это современный, быстрый (высокопроизводительный) веб-фреймворк для создания API используя Python 3.6+, в основе которого лежит стандартная аннотация типов Python. +FastAPI — это современный, быстрый (высокопроизводительный) веб-фреймворк для создания API используя Python 3.8+, в основе которого лежит стандартная аннотация типов Python. Ключевые особенности: @@ -109,12 +109,12 @@ FastAPI — это современный, быстрый (высокопрои ## Зависимости -Python 3.7+ +Python 3.8+ FastAPI стоит на плечах гигантов: * Starlette для части связанной с вебом. -* Pydantic для части связанной с данными. +* Pydantic для части связанной с данными. ## Установка @@ -321,11 +321,11 @@ def update_item(item_id: int, item: Item): Таким образом, вы объявляете **один раз** типы параметров, тело и т. д. в качестве параметров функции. -Вы делаете это испльзуя стандартную современную типизацию Python. +Вы делаете это используя стандартную современную типизацию Python. Вам не нужно изучать новый синтаксис, методы или классы конкретной библиотеки и т. д. -Только стандартный **Python 3.6+**. +Только стандартный **Python 3.8+**. Например, для `int`: @@ -445,7 +445,7 @@ item: Item * HTTPX - Обязательно, если вы хотите использовать `TestClient`. * jinja2 - Обязательно, если вы хотите использовать конфигурацию шаблона по умолчанию. -* python-multipart - Обязательно, если вы хотите поддерживать форму "парсинга" с помощью `request.form()`. +* python-multipart - Обязательно, если вы хотите поддерживать форму "парсинга" с помощью `request.form()`. * itsdangerous - Обязательно, для поддержки `SessionMiddleware`. * pyyaml - Обязательно, для поддержки `SchemaGenerator` Starlette (возможно, вам это не нужно с FastAPI). * ujson - Обязательно, если вы хотите использовать `UJSONResponse`. diff --git a/docs/ru/docs/learn/index.md b/docs/ru/docs/learn/index.md new file mode 100644 index 0000000000000..b2e4cabc751a6 --- /dev/null +++ b/docs/ru/docs/learn/index.md @@ -0,0 +1,5 @@ +# Обучение + +Здесь представлены вводные разделы и учебные пособия для изучения **FastAPI**. + +Вы можете считать это **книгой**, **курсом**, **официальным** и рекомендуемым способом изучения FastAPI. 😎 diff --git a/docs/ru/docs/python-types.md b/docs/ru/docs/python-types.md index 7523083c88319..3c8492c67bb26 100644 --- a/docs/ru/docs/python-types.md +++ b/docs/ru/docs/python-types.md @@ -265,7 +265,7 @@ John Doe ## Pydantic-модели -Pydantic является Python-библиотекой для выполнения валидации данных. +Pydantic является Python-библиотекой для выполнения валидации данных. Вы объявляете «форму» данных как классы с атрибутами. @@ -282,7 +282,7 @@ John Doe ``` !!! info - Чтобы узнать больше о Pydantic, читайте его документацию. + Чтобы узнать больше о Pydantic, читайте его документацию. **FastAPI** целиком основан на Pydantic. diff --git a/docs/ru/docs/tutorial/background-tasks.md b/docs/ru/docs/tutorial/background-tasks.md index 81efda786ad8c..73ba860bc3dd9 100644 --- a/docs/ru/docs/tutorial/background-tasks.md +++ b/docs/ru/docs/tutorial/background-tasks.md @@ -63,7 +63,7 @@ {!> ../../../docs_src/background_tasks/tutorial002_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="13 15 22 25" {!> ../../../docs_src/background_tasks/tutorial002.py!} @@ -71,7 +71,7 @@ В этом примере сообщения будут записаны в `log.txt` *после* того, как ответ сервера был отправлен. -Если бы в запросе была очередь `q`, она бы первой записалась в `log.txt` фоновой задачей (потому что вызывается в зависимости `get_query`). +Если бы в запрос был передан query-параметр `q`, он бы первыми записался в `log.txt` фоновой задачей (потому что вызывается в зависимости `get_query`). После другая фоновая задача, которая была сгенерирована в функции, запишет сообщение из параметра `email`. diff --git a/docs/ru/docs/tutorial/body-fields.md b/docs/ru/docs/tutorial/body-fields.md index 674b8bde47bf7..02a598004a86e 100644 --- a/docs/ru/docs/tutorial/body-fields.md +++ b/docs/ru/docs/tutorial/body-fields.md @@ -12,7 +12,7 @@ {!> ../../../docs_src/body_fields/tutorial001_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="4" {!> ../../../docs_src/body_fields/tutorial001.py!} @@ -31,13 +31,13 @@ {!> ../../../docs_src/body_fields/tutorial001_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="11-14" {!> ../../../docs_src/body_fields/tutorial001.py!} ``` -Функция `Field` работает так же, как `Query`, `Path` и `Body`, у ее такие же параметры и т.д. +Функция `Field` работает так же, как `Query`, `Path` и `Body`, у неё такие же параметры и т.д. !!! note "Технические детали" На самом деле, `Query`, `Path` и другие функции, которые вы увидите в дальнейшем, создают объекты подклассов общего класса `Param`, который сам по себе является подклассом `FieldInfo` из Pydantic. diff --git a/docs/ru/docs/tutorial/body-multiple-params.md b/docs/ru/docs/tutorial/body-multiple-params.md index a20457092b34b..e52ef6f6f0b4d 100644 --- a/docs/ru/docs/tutorial/body-multiple-params.md +++ b/docs/ru/docs/tutorial/body-multiple-params.md @@ -20,7 +20,7 @@ {!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="19-21" {!> ../../../docs_src/body_multiple_params/tutorial001_an.py!} @@ -35,7 +35,7 @@ {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! Заметка Рекомендуется использовать версию с `Annotated`, если это возможно. @@ -68,7 +68,7 @@ {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="22" {!> ../../../docs_src/body_multiple_params/tutorial002.py!} @@ -123,7 +123,7 @@ {!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="24" {!> ../../../docs_src/body_multiple_params/tutorial003_an.py!} @@ -138,7 +138,7 @@ {!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! Заметка Рекомендуется использовать `Annotated` версию, если это возможно. @@ -197,7 +197,7 @@ q: str | None = None {!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="28" {!> ../../../docs_src/body_multiple_params/tutorial004_an.py!} @@ -212,7 +212,7 @@ q: str | None = None {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! Заметка Рекомендуется использовать `Annotated` версию, если это возможно. @@ -250,7 +250,7 @@ item: Item = Body(embed=True) {!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="18" {!> ../../../docs_src/body_multiple_params/tutorial005_an.py!} @@ -265,7 +265,7 @@ item: Item = Body(embed=True) {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! Заметка Рекомендуется использовать `Annotated` версию, если это возможно. diff --git a/docs/ru/docs/tutorial/body-nested-models.md b/docs/ru/docs/tutorial/body-nested-models.md index 6435e316f4254..51a32ba5672e0 100644 --- a/docs/ru/docs/tutorial/body-nested-models.md +++ b/docs/ru/docs/tutorial/body-nested-models.md @@ -12,7 +12,7 @@ {!> ../../../docs_src/body_nested_models/tutorial001_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="14" {!> ../../../docs_src/body_nested_models/tutorial001.py!} @@ -73,7 +73,7 @@ my_list: List[str] {!> ../../../docs_src/body_nested_models/tutorial002_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="14" {!> ../../../docs_src/body_nested_models/tutorial002.py!} @@ -85,7 +85,7 @@ my_list: List[str] И в Python есть специальный тип данных для множеств уникальных элементов - `set`. -Тогда мы может обьявить поле `tags` как множество строк: +Тогда мы можем обьявить поле `tags` как множество строк: === "Python 3.10+" @@ -99,7 +99,7 @@ my_list: List[str] {!> ../../../docs_src/body_nested_models/tutorial003_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="1 14" {!> ../../../docs_src/body_nested_models/tutorial003.py!} @@ -137,7 +137,7 @@ my_list: List[str] {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9-11" {!> ../../../docs_src/body_nested_models/tutorial004.py!} @@ -159,7 +159,7 @@ my_list: List[str] {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="20" {!> ../../../docs_src/body_nested_models/tutorial004.py!} @@ -192,7 +192,7 @@ my_list: List[str] Помимо обычных простых типов, таких как `str`, `int`, `float`, и т.д. Вы можете использовать более сложные базовые типы, которые наследуются от типа `str`. -Чтобы увидеть все варианты, которые у вас есть, ознакомьтесь с документацией по необычным типам Pydantic. Вы увидите некоторые примеры в следующей главе. +Чтобы увидеть все варианты, которые у вас есть, ознакомьтесь с документацией по необычным типам Pydantic. Вы увидите некоторые примеры в следующей главе. Например, так как в модели `Image` у нас есть поле `url`, то мы можем объявить его как тип `HttpUrl` из модуля Pydantic вместо типа `str`: @@ -208,7 +208,7 @@ my_list: List[str] {!> ../../../docs_src/body_nested_models/tutorial005_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="4 10" {!> ../../../docs_src/body_nested_models/tutorial005.py!} @@ -232,7 +232,7 @@ my_list: List[str] {!> ../../../docs_src/body_nested_models/tutorial006_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="20" {!> ../../../docs_src/body_nested_models/tutorial006.py!} @@ -283,7 +283,7 @@ my_list: List[str] {!> ../../../docs_src/body_nested_models/tutorial007_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9 14 20 23 27" {!> ../../../docs_src/body_nested_models/tutorial007.py!} @@ -314,7 +314,7 @@ images: list[Image] {!> ../../../docs_src/body_nested_models/tutorial008_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="15" {!> ../../../docs_src/body_nested_models/tutorial008.py!} @@ -354,7 +354,7 @@ images: list[Image] {!> ../../../docs_src/body_nested_models/tutorial009_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9" {!> ../../../docs_src/body_nested_models/tutorial009.py!} diff --git a/docs/ru/docs/tutorial/body-updates.md b/docs/ru/docs/tutorial/body-updates.md new file mode 100644 index 0000000000000..4998ab31ac310 --- /dev/null +++ b/docs/ru/docs/tutorial/body-updates.md @@ -0,0 +1,153 @@ +# Body - Обновления + +## Полное обновление с помощью `PUT` + +Для полного обновления элемента можно воспользоваться операцией HTTP `PUT`. + +Вы можете использовать функцию `jsonable_encoder` для преобразования входных данных в JSON, так как нередки случаи, когда работать можно только с простыми типами данных (например, для хранения в NoSQL-базе данных). + +=== "Python 3.10+" + + ```Python hl_lines="28-33" + {!> ../../../docs_src/body_updates/tutorial001_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="30-35" + {!> ../../../docs_src/body_updates/tutorial001_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="30-35" + {!> ../../../docs_src/body_updates/tutorial001.py!} + ``` + +`PUT` используется для получения данных, которые должны полностью заменить существующие данные. + +### Предупреждение о замене + +Это означает, что если вы хотите обновить элемент `bar`, используя `PUT` с телом, содержащим: + +```Python +{ + "name": "Barz", + "price": 3, + "description": None, +} +``` + +поскольку оно не включает уже сохраненный атрибут `"tax": 20.2`, входная модель примет значение по умолчанию `"tax": 10.5`. + +И данные будут сохранены с этим "новым" `tax`, равным `10,5`. + +## Частичное обновление с помощью `PATCH` + +Также можно использовать HTTP `PATCH` операцию для *частичного* обновления данных. + +Это означает, что можно передавать только те данные, которые необходимо обновить, оставляя остальные нетронутыми. + +!!! note "Технические детали" + `PATCH` менее распространен и известен, чем `PUT`. + + А многие команды используют только `PUT`, даже для частичного обновления. + + Вы можете **свободно** использовать их как угодно, **FastAPI** не накладывает никаких ограничений. + + Но в данном руководстве более или менее понятно, как они должны использоваться. + +### Использование параметра `exclude_unset` в Pydantic + +Если необходимо выполнить частичное обновление, то очень полезно использовать параметр `exclude_unset` в методе `.dict()` модели Pydantic. + +Например, `item.dict(exclude_unset=True)`. + +В результате будет сгенерирован словарь, содержащий только те данные, которые были заданы при создании модели `item`, без учета значений по умолчанию. Затем вы можете использовать это для создания словаря только с теми данными, которые были установлены (отправлены в запросе), опуская значения по умолчанию: + +=== "Python 3.10+" + + ```Python hl_lines="32" + {!> ../../../docs_src/body_updates/tutorial002_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="34" + {!> ../../../docs_src/body_updates/tutorial002_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="34" + {!> ../../../docs_src/body_updates/tutorial002.py!} + ``` + +### Использование параметра `update` в Pydantic + +Теперь можно создать копию существующей модели, используя `.copy()`, и передать параметр `update` с `dict`, содержащим данные для обновления. + +Например, `stored_item_model.copy(update=update_data)`: + +=== "Python 3.10+" + + ```Python hl_lines="33" + {!> ../../../docs_src/body_updates/tutorial002_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="35" + {!> ../../../docs_src/body_updates/tutorial002_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="35" + {!> ../../../docs_src/body_updates/tutorial002.py!} + ``` + +### Кратко о частичном обновлении + +В целом, для применения частичных обновлений необходимо: + +* (Опционально) использовать `PATCH` вместо `PUT`. +* Извлечь сохранённые данные. +* Поместить эти данные в Pydantic модель. +* Сгенерировать `dict` без значений по умолчанию из входной модели (с использованием `exclude_unset`). + * Таким образом, можно обновлять только те значения, которые действительно установлены пользователем, вместо того чтобы переопределять значения, уже сохраненные в модели по умолчанию. +* Создать копию хранимой модели, обновив ее атрибуты полученными частичными обновлениями (с помощью параметра `update`). +* Преобразовать скопированную модель в то, что может быть сохранено в вашей БД (например, с помощью `jsonable_encoder`). + * Это сравнимо с повторным использованием метода модели `.dict()`, но при этом происходит проверка (и преобразование) значений в типы данных, которые могут быть преобразованы в JSON, например, `datetime` в `str`. +* Сохранить данные в своей БД. +* Вернуть обновленную модель. + +=== "Python 3.10+" + + ```Python hl_lines="28-35" + {!> ../../../docs_src/body_updates/tutorial002_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="30-37" + {!> ../../../docs_src/body_updates/tutorial002_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="30-37" + {!> ../../../docs_src/body_updates/tutorial002.py!} + ``` + +!!! tip "Подсказка" + Эту же технику можно использовать и для операции HTTP `PUT`. + + Но в приведенном примере используется `PATCH`, поскольку он был создан именно для таких случаев использования. + +!!! note "Технические детали" + Обратите внимание, что входная модель по-прежнему валидируется. + + Таким образом, если вы хотите получать частичные обновления, в которых могут быть опущены все атрибуты, вам необходимо иметь модель, в которой все атрибуты помечены как необязательные (со значениями по умолчанию или `None`). + + Чтобы отличить модели со всеми необязательными значениями для **обновления** от моделей с обязательными значениями для **создания**, можно воспользоваться идеями, описанными в [Дополнительные модели](extra-models.md){.internal-link target=_blank}. diff --git a/docs/ru/docs/tutorial/body.md b/docs/ru/docs/tutorial/body.md index c03d40c3fb34e..96f80af0607ec 100644 --- a/docs/ru/docs/tutorial/body.md +++ b/docs/ru/docs/tutorial/body.md @@ -6,7 +6,7 @@ Ваш API почти всегда отправляет тело **ответа**. Но клиентам не обязательно всегда отправлять тело **запроса**. -Чтобы объявить тело **запроса**, необходимо использовать модели Pydantic, со всей их мощью и преимуществами. +Чтобы объявить тело **запроса**, необходимо использовать модели Pydantic, со всей их мощью и преимуществами. !!! info "Информация" Чтобы отправить данные, необходимо использовать один из методов: `POST` (обычно), `PUT`, `DELETE` или `PATCH`. diff --git a/docs/ru/docs/tutorial/cookie-params.md b/docs/ru/docs/tutorial/cookie-params.md index a6f2caa267606..5f99458b697fa 100644 --- a/docs/ru/docs/tutorial/cookie-params.md +++ b/docs/ru/docs/tutorial/cookie-params.md @@ -12,7 +12,7 @@ {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="3" {!> ../../../docs_src/cookie_params/tutorial001.py!} @@ -30,7 +30,7 @@ {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9" {!> ../../../docs_src/cookie_params/tutorial001.py!} diff --git a/docs/ru/docs/tutorial/debugging.md b/docs/ru/docs/tutorial/debugging.md index 755d98cf20d28..38709e56df7c3 100644 --- a/docs/ru/docs/tutorial/debugging.md +++ b/docs/ru/docs/tutorial/debugging.md @@ -22,7 +22,7 @@ $ python myapp.py
-но не вызывался, когда другой файл импортирует это, например:: +но не вызывался, когда другой файл импортирует это, например: ```Python from myapp import app diff --git a/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md new file mode 100644 index 0000000000000..b6ad25dafcc95 --- /dev/null +++ b/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md @@ -0,0 +1,478 @@ +# Классы как зависимости + +Прежде чем углубиться в систему **Внедрения Зависимостей**, давайте обновим предыдущий пример. + +## `Словарь` из предыдущего примера + +В предыдущем примере мы возвращали `словарь` из нашей зависимости: + +=== "Python 3.10+" + + ```Python hl_lines="9" + {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="11" + {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="12" + {!> ../../../docs_src/dependencies/tutorial001_an.py!} + ``` + +=== "Python 3.10+ без Annotated" + + !!! tip "Подсказка" + Рекомендуется использовать версию с `Annotated` если возможно. + + ```Python hl_lines="7" + {!> ../../../docs_src/dependencies/tutorial001_py310.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "Подсказка" + Рекомендуется использовать версию с `Annotated` если возможно. + + ```Python hl_lines="11" + {!> ../../../docs_src/dependencies/tutorial001.py!} + ``` + +Но затем мы получаем `словарь` в параметре `commons` *функции операции пути*. И мы знаем, что редакторы не могут обеспечить достаточную поддержку для `словаря`, поскольку они не могут знать их ключи и типы значений. + +Мы можем сделать лучше... + +## Что делает зависимость + +До сих пор вы видели зависимости, объявленные как функции. + +Но это не единственный способ объявления зависимостей (хотя, вероятно, более распространенный). + +Ключевым фактором является то, что зависимость должна быть "вызываемой". + +В Python "**вызываемый**" - это все, что Python может "вызвать", как функцию. + +Так, если у вас есть объект `something` (который может _не_ быть функцией) и вы можете "вызвать" его (выполнить) как: + +```Python +something() +``` + +или + +```Python +something(some_argument, some_keyword_argument="foo") +``` + +в таком случае он является "вызываемым". + +## Классы как зависимости + +Вы можете заметить, что для создания экземпляра класса в Python используется тот же синтаксис. + +Например: + +```Python +class Cat: + def __init__(self, name: str): + self.name = name + + +fluffy = Cat(name="Mr Fluffy") +``` + +В данном случае `fluffy` является экземпляром класса `Cat`. + +А чтобы создать `fluffy`, вы "вызываете" `Cat`. + +Таким образом, класс в Python также является **вызываемым**. + +Тогда в **FastAPI** в качестве зависимости можно использовать класс Python. + +На самом деле FastAPI проверяет, что переданный объект является "вызываемым" (функция, класс или что-либо еще) и указаны необходимые для его вызова параметры. + +Если вы передаёте что-то, что можно "вызывать" в качестве зависимости в **FastAPI**, то он будет анализировать параметры, необходимые для "вызова" этого объекта и обрабатывать их так же, как параметры *функции операции пути*. Включая подзависимости. + +Это относится и к вызываемым объектам без параметров. Работа с ними происходит точно так же, как и для *функций операции пути* без параметров. + +Теперь мы можем изменить зависимость `common_parameters`, указанную выше, на класс `CommonQueryParams`: + +=== "Python 3.10+" + + ```Python hl_lines="11-15" + {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="11-15" + {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="12-16" + {!> ../../../docs_src/dependencies/tutorial002_an.py!} + ``` + +=== "Python 3.10+ без Annotated" + + !!! tip "Подсказка" + Рекомендуется использовать версию с `Annotated` если возможно. + + ```Python hl_lines="9-13" + {!> ../../../docs_src/dependencies/tutorial002_py310.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "Подсказка" + Рекомендуется использовать версию с `Annotated` если возможно. + + ```Python hl_lines="11-15" + {!> ../../../docs_src/dependencies/tutorial002.py!} + ``` + +Обратите внимание на метод `__init__`, используемый для создания экземпляра класса: + +=== "Python 3.10+" + + ```Python hl_lines="12" + {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="12" + {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="13" + {!> ../../../docs_src/dependencies/tutorial002_an.py!} + ``` + +=== "Python 3.10+ без Annotated" + + !!! tip "Подсказка" + Рекомендуется использовать версию с `Annotated` если возможно. + + ```Python hl_lines="10" + {!> ../../../docs_src/dependencies/tutorial002_py310.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "Подсказка" + Рекомендуется использовать версию с `Annotated` если возможно. + + ```Python hl_lines="12" + {!> ../../../docs_src/dependencies/tutorial002.py!} + ``` + +...имеет те же параметры, что и ранее используемая функция `common_parameters`: + +=== "Python 3.10+" + + ```Python hl_lines="8" + {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="9" + {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="10" + {!> ../../../docs_src/dependencies/tutorial001_an.py!} + ``` + +=== "Python 3.10+ без Annotated" + + !!! tip "Подсказка" + Рекомендуется использовать версию с `Annotated` если возможно. + + ```Python hl_lines="6" + {!> ../../../docs_src/dependencies/tutorial001_py310.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "Подсказка" + Рекомендуется использовать версию с `Annotated` если возможно. + + ```Python hl_lines="9" + {!> ../../../docs_src/dependencies/tutorial001.py!} + ``` + +Эти параметры и будут использоваться **FastAPI** для "решения" зависимости. + +В обоих случаях она будет иметь: + +* Необязательный параметр запроса `q`, представляющий собой `str`. +* Параметр запроса `skip`, представляющий собой `int`, по умолчанию `0`. +* Параметр запроса `limit`, представляющий собой `int`, по умолчанию равный `100`. + +В обоих случаях данные будут конвертированы, валидированы, документированы по схеме OpenAPI и т.д. + +## Как это использовать + +Теперь вы можете объявить свою зависимость, используя этот класс. + +=== "Python 3.10+" + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="20" + {!> ../../../docs_src/dependencies/tutorial002_an.py!} + ``` + +=== "Python 3.10+ без Annotated" + + !!! tip "Подсказка" + Рекомендуется использовать версию с `Annotated` если возможно. + + ```Python hl_lines="17" + {!> ../../../docs_src/dependencies/tutorial002_py310.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "Подсказка" + Рекомендуется использовать версию с `Annotated` если возможно. + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial002.py!} + ``` + +**FastAPI** вызывает класс `CommonQueryParams`. При этом создается "экземпляр" этого класса, который будет передан в качестве параметра `commons` в вашу функцию. + +## Аннотация типа или `Depends` + +Обратите внимание, что в приведенном выше коде мы два раза пишем `CommonQueryParams`: + +=== "Python 3.6+ без Annotated" + + !!! tip "Подсказка" + Рекомендуется использовать версию с `Annotated` если возможно. + + ```Python + commons: CommonQueryParams = Depends(CommonQueryParams) + ``` + +=== "Python 3.6+" + + ```Python + commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] + ``` + +Последний параметр `CommonQueryParams`, в: + +```Python +... Depends(CommonQueryParams) +``` + +...это то, что **FastAPI** будет использовать, чтобы узнать, что является зависимостью. + +Из него FastAPI извлечёт объявленные параметры и именно их будет вызывать. + +--- + +В этом случае первый `CommonQueryParams`, в: + +=== "Python 3.6+" + + ```Python + commons: Annotated[CommonQueryParams, ... + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "Подсказка" + Рекомендуется использовать версию с `Annotated` если возможно. + + ```Python + commons: CommonQueryParams ... + ``` + +...не имеет никакого специального значения для **FastAPI**. FastAPI не будет использовать его для преобразования данных, валидации и т.д. (поскольку для этого используется `Depends(CommonQueryParams)`). + +На самом деле можно написать просто: + +=== "Python 3.6+" + + ```Python + commons: Annotated[Any, Depends(CommonQueryParams)] + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "Подсказка" + Рекомендуется использовать версию с `Annotated` если возможно. + + ```Python + commons = Depends(CommonQueryParams) + ``` + +...как тут: + +=== "Python 3.10+" + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial003_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial003_an_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="20" + {!> ../../../docs_src/dependencies/tutorial003_an.py!} + ``` + +=== "Python 3.10+ без Annotated" + + !!! tip "Подсказка" + Рекомендуется использовать версию с `Annotated` если возможно. + + ```Python hl_lines="17" + {!> ../../../docs_src/dependencies/tutorial003_py310.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "Подсказка" + Рекомендуется использовать версию с `Annotated` если возможно. + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial003.py!} + ``` + +Но объявление типа приветствуется, так как в этом случае ваш редактор будет знать, что будет передано в качестве параметра `commons`, и тогда он сможет помочь вам с автодополнением, проверкой типов и т.д: + + + +## Сокращение + +Но вы видите, что здесь мы имеем некоторое повторение кода, дважды написав `CommonQueryParams`: + +=== "Python 3.6+ без Annotated" + + !!! tip "Подсказка" + Рекомендуется использовать версию с `Annotated` если возможно. + + ```Python + commons: CommonQueryParams = Depends(CommonQueryParams) + ``` + +=== "Python 3.6+" + + ```Python + commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] + ``` + +Для случаев, когда зависимостью является *конкретный* класс, который **FastAPI** "вызовет" для создания экземпляра этого класса, можно использовать укороченную запись. + + +Вместо того чтобы писать: + +=== "Python 3.6+" + + ```Python + commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "Подсказка" + Рекомендуется использовать версию с `Annotated` если возможно. + + ```Python + commons: CommonQueryParams = Depends(CommonQueryParams) + ``` + +...следует написать: + +=== "Python 3.6+" + + ```Python + commons: Annotated[CommonQueryParams, Depends()] + ``` + +=== "Python 3.6 без Annotated" + + !!! tip "Подсказка" + Рекомендуется использовать версию с `Annotated` если возможно. + + ```Python + commons: CommonQueryParams = Depends() + ``` + +Вы объявляете зависимость как тип параметра и используете `Depends()` без какого-либо параметра, вместо того чтобы *снова* писать полный класс внутри `Depends(CommonQueryParams)`. + +Аналогичный пример будет выглядеть следующим образом: + +=== "Python 3.10+" + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial004_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial004_an_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="20" + {!> ../../../docs_src/dependencies/tutorial004_an.py!} + ``` + +=== "Python 3.10+ без Annotated" + + !!! tip "Подсказка" + Рекомендуется использовать версию с `Annotated` если возможно. + + ```Python hl_lines="17" + {!> ../../../docs_src/dependencies/tutorial004_py310.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "Подсказка" + Рекомендуется использовать версию с `Annotated` если возможно. + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial004.py!} + ``` + +...и **FastAPI** будет знать, что делать. + +!!! tip "Подсказка" + Если это покажется вам более запутанным, чем полезным, не обращайте внимания, это вам не *нужно*. + + Это просто сокращение. Потому что **FastAPI** заботится о том, чтобы помочь вам свести к минимуму повторение кода. diff --git a/docs/ru/docs/tutorial/dependencies/global-dependencies.md b/docs/ru/docs/tutorial/dependencies/global-dependencies.md new file mode 100644 index 0000000000000..eb1b4d7c1c1c8 --- /dev/null +++ b/docs/ru/docs/tutorial/dependencies/global-dependencies.md @@ -0,0 +1,34 @@ +# Глобальные зависимости + +Для некоторых типов приложений может потребоваться добавить зависимости ко всему приложению. + +Подобно тому, как вы можете [добавлять зависимости через параметр `dependencies` в *декораторах операций пути*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, вы можете добавлять зависимости сразу ко всему `FastAPI` приложению. + +В этом случае они будут применяться ко всем *операциям пути* в приложении: + +=== "Python 3.9+" + + ```Python hl_lines="16" + {!> ../../../docs_src/dependencies/tutorial012_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="16" + {!> ../../../docs_src/dependencies/tutorial012_an.py!} + ``` + +=== "Python 3.8 non-Annotated" + + !!! tip "Подсказка" + Рекомендуется использовать 'Annotated' версию, если это возможно. + + ```Python hl_lines="15" + {!> ../../../docs_src/dependencies/tutorial012.py!} + ``` + +Все способы [добавления зависимостей в *декораторах операций пути*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} по-прежнему применимы, но в данном случае зависимости применяются ко всем *операциям пути* приложения. + +## Зависимости для групп *операций пути* + +Позднее, читая о том, как структурировать более крупные [приложения, содержащие много файлов](../../tutorial/bigger-applications.md){.internal-link target=_blank}, вы узнаете, как объявить один параметр dependencies для целой группы *операций пути*. diff --git a/docs/ru/docs/tutorial/dependencies/index.md b/docs/ru/docs/tutorial/dependencies/index.md new file mode 100644 index 0000000000000..ad6e835e5b580 --- /dev/null +++ b/docs/ru/docs/tutorial/dependencies/index.md @@ -0,0 +1,350 @@ +# Зависимости + +**FastAPI** имеет очень мощную и интуитивную систему **Dependency Injection**. + +Она проектировалась таким образом, чтобы быть простой в использовании и облегчить любому разработчику интеграцию других компонентов с **FastAPI**. + +## Что такое "Dependency Injection" (инъекция зависимости) + +**"Dependency Injection"** в программировании означает, что у вашего кода (в данном случае, вашей *функции обработки пути*) есть способы объявить вещи, которые запрашиваются для работы и использования: "зависимости". + +И потом эта система (в нашем случае **FastAPI**) организует всё, что требуется, чтобы обеспечить ваш код этой зависимостью (сделать "инъекцию" зависимости). + +Это очень полезно, когда вам нужно: + +* Обеспечить общую логику (один и тот же алгоритм снова и снова). +* Общее соединение с базой данных. +* Обеспечение безопасности, аутентификации, запроса роли и т.п. +* И многое другое. + +Всё это минимизирует повторение кода. + +## Первые шаги + +Давайте рассмотрим очень простой пример. Он настолько простой, что на данный момент почти бесполезный. + +Но таким способом мы можем сфокусироваться на том, как же всё таки работает система **Dependency Injection**. + +### Создание зависимости или "зависимого" +Давайте для начала сфокусируемся на зависимостях. + +Это просто функция, которая может принимать все те же параметры, что и *функции обработки пути*: +=== "Python 3.10+" + + ```Python hl_lines="8-9" + {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="8-11" + {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9-12" + {!> ../../../docs_src/dependencies/tutorial001_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip "Подсказка" + Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. + + ```Python hl_lines="6-7" + {!> ../../../docs_src/dependencies/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip "Подсказка" + + Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. + + ```Python hl_lines="8-11" + {!> ../../../docs_src/dependencies/tutorial001.py!} + ``` + +**И всё.** + +**2 строки.** + +И теперь она той же формы и структуры, что и все ваши *функции обработки пути*. + +Вы можете думать об *функции обработки пути* как о функции без "декоратора" (без `@app.get("/some-path")`). + +И она может возвращать всё, что требуется. + +В этом случае, эта зависимость ожидает: + +* Необязательный query-параметр `q` с типом `str` +* Необязательный query-параметр `skip` с типом `int`, и значением по умолчанию `0` +* Необязательный query-параметр `limit` с типом `int`, и значением по умолчанию `100` + +И в конце она возвращает `dict`, содержащий эти значения. + +!!! Информация + + **FastAPI** добавил поддержку для `Annotated` (и начал её рекомендовать) в версии 0.95.0. + + Если у вас более старая версия, будут ошибки при попытке использовать `Annotated`. + + Убедитесь, что вы [Обновили FastAPI версию](../../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} до, как минимум 0.95.1, перед тем как использовать `Annotated`. + +### Import `Depends` + +=== "Python 3.10+" + + ```Python hl_lines="3" + {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="3" + {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="3" + {!> ../../../docs_src/dependencies/tutorial001_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip "Подсказка" + Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. + + ```Python hl_lines="1" + {!> ../../../docs_src/dependencies/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip "Подсказка" + Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. + + ```Python hl_lines="3" + {!> ../../../docs_src/dependencies/tutorial001.py!} + ``` + +### Объявите зависимость в "зависимом" + +Точно так же, как вы использовали `Body`, `Query` и т.д. с вашей *функцией обработки пути* для параметров, используйте `Depends` с новым параметром: + +=== "Python 3.10+" + + ```Python hl_lines="13 18" + {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="15 20" + {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="16 21" + {!> ../../../docs_src/dependencies/tutorial001_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip "Подсказка" + Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. + + ```Python hl_lines="11 16" + {!> ../../../docs_src/dependencies/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip "Подсказка" + Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. + + ```Python hl_lines="15 20" + {!> ../../../docs_src/dependencies/tutorial001.py!} + ``` + +`Depends` работает немного иначе. Вы передаёте в `Depends` одиночный параметр, который будет похож на функцию. + +Вы **не вызываете его** на месте (не добавляете скобочки в конце: 👎 *your_best_func()*👎), просто передаёте как параметр в `Depends()`. + +И потом функция берёт параметры так же, как *функция обработки пути*. + +!!! tip "Подсказка" + В следующей главе вы увидите, какие другие вещи, помимо функций, можно использовать в качестве зависимостей. + +Каждый раз, когда новый запрос приходит, **FastAPI** позаботится о: + +* Вызове вашей зависимости ("зависимого") функции с корректными параметрами. +* Получении результата из вашей функции. +* Назначении результата в параметр в вашей *функции обработки пути*. + +```mermaid +graph TB + +common_parameters(["common_parameters"]) +read_items["/items/"] +read_users["/users/"] + +common_parameters --> read_items +common_parameters --> read_users +``` + +Таким образом, вы пишете общий код один раз, и **FastAPI** позаботится о его вызове для ваших *операций с путями*. + +!!! check "Проверка" + Обратите внимание, что вы не создаёте специальный класс и не передаёте его куда-то в **FastAPI** для регистрации, или что-то в этом роде. + + Вы просто передаёте это в `Depends`, и **FastAPI** знает, что делать дальше. + +## Объединяем с `Annotated` зависимостями + +В приведенном выше примере есть небольшое **повторение кода**. + +Когда вам нужно использовать `common_parameters()` зависимость, вы должны написать весь параметр с аннотацией типов и `Depends()`: + +```Python +commons: Annotated[dict, Depends(common_parameters)] +``` + +Но потому что мы используем `Annotated`, мы можем хранить `Annotated` значение в переменной и использовать его в нескольких местах: + +=== "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.8+" + + ```Python hl_lines="15 19 24" + {!> ../../../docs_src/dependencies/tutorial001_02_an.py!} + ``` + +!!! tip "Подсказка" + Это стандартный синтаксис python и называется "type alias", это не особенность **FastAPI**. + + Но потому что **FastAPI** базируется на стандартах Python, включая `Annotated`, вы можете использовать этот трюк в вашем коде. 😎 + + +Зависимости продолжат работу как ожидалось, и **лучшая часть** в том, что **информация о типе будет сохранена**. Это означает, что ваш редактор кода будет корректно обрабатывать **автодополнения**, **встроенные ошибки** и так далее. То же самое относится и к инструментам, таким как `mypy`. + +Это очень полезно, когда вы интегрируете это в **большую кодовую базу**, используя **одинаковые зависимости** снова и снова во **многих** ***операциях пути***. + +## Использовать `async` или не `async` + +Для зависимостей, вызванных **FastAPI** (то же самое, что и ваши *функции обработки пути*), те же правила, что приняты для определения ваших функций. + +Вы можете использовать `async def` или обычное `def`. + +Вы также можете объявить зависимости с `async def` внутри обычной `def` *функции обработки пути*, или `def` зависимости внутри `async def` *функции обработки пути*, и так далее. + +Это всё не важно. **FastAPI** знает, что нужно сделать. 😎 + +!!! note "Информация" + Если вам эта тема не знакома, прочтите [Async: *"In a hurry?"*](../../async.md){.internal-link target=_blank} раздел о `async` и `await` в документации. + +## Интеграция с OpenAPI + +Все заявления о запросах, валидаторы, требования ваших зависимостей (и подзависимостей) будут интегрированы в соответствующую OpenAPI-схему. + +В интерактивной документации будет вся информация по этим зависимостям тоже: + + + +## Простое использование + +Если вы посмотрите на фото, *функция обработки пути* объявляется каждый раз, когда вычисляется путь, и тогда **FastAPI** позаботится о вызове функции с корректными параметрами, извлекая информацию из запроса. + +На самом деле, все (или большинство) веб-фреймворков работают по схожему сценарию. + +Вы никогда не вызываете эти функции на месте. Их вызовет ваш фреймворк (в нашем случае, **FastAPI**). + +С системой Dependency Injection, вы можете сообщить **FastAPI**, что ваша *функция обработки пути* "зависит" от чего-то ещё, что должно быть извлечено перед вашей *функцией обработки пути*, и **FastAPI** позаботится об извлечении и инъекции результата. + +Другие распространённые термины для описания схожей идеи "dependency injection" являются: + +- ресурсность +- доставка +- сервисность +- инъекция +- компонентность + +## **FastAPI** подключаемые модули + +Инъекции и модули могут быть построены с использованием системы **Dependency Injection**. Но на самом деле, **нет необходимости создавать новые модули**, просто используя зависимости, можно объявить бесконечное количество интеграций и взаимодействий, которые доступны вашей *функции обработки пути*. + +И зависимости могут быть созданы очень простым и интуитивным способом, что позволяет вам просто импортировать нужные пакеты Python и интегрировать их в API функции за пару строк. + +Вы увидите примеры этого в следующих главах о реляционных и NoSQL базах данных, безопасности и т.д. + +## Совместимость с **FastAPI** + +Простота Dependency Injection делает **FastAPI** совместимым с: + +- всеми реляционными базами данных +- NoSQL базами данных +- внешними пакетами +- внешними API +- системами авторизации, аутентификации +- системами мониторинга использования API +- системами ввода данных ответов +- и так далее. + +## Просто и сильно + +Хотя иерархическая система Dependency Injection очень проста для описания и использования, она по-прежнему очень мощная. + +Вы можете описывать зависимости в очередь, и они уже будут вызываться друг за другом. + +Когда иерархическое дерево построено, система **Dependency Injection** берет на себя решение всех зависимостей для вас (и их подзависимостей) и обеспечивает (инъектирует) результат на каждом шаге. + +Например, у вас есть 4 API-эндпоинта (*операции пути*): + +- `/items/public/` +- `/items/private/` +- `/users/{user_id}/activate` +- `/items/pro/` + +Тогда вы можете требовать разные права для каждого из них, используя зависимости и подзависимости: + +```mermaid +graph TB + +current_user(["current_user"]) +active_user(["active_user"]) +admin_user(["admin_user"]) +paying_user(["paying_user"]) + +public["/items/public/"] +private["/items/private/"] +activate_user["/users/{user_id}/activate"] +pro_items["/items/pro/"] + +current_user --> active_user +active_user --> admin_user +active_user --> paying_user + +current_user --> public +active_user --> private +admin_user --> activate_user +paying_user --> pro_items +``` + +## Интегрировано с **OpenAPI** + +Все эти зависимости, объявляя свои требования, также добавляют параметры, проверки и т.д. к вашим операциям *path*. + +**FastAPI** позаботится о добавлении всего этого в схему открытого API, чтобы это отображалось в системах интерактивной документации. diff --git a/docs/ru/docs/tutorial/encoder.md b/docs/ru/docs/tutorial/encoder.md new file mode 100644 index 0000000000000..c26b2c94117c8 --- /dev/null +++ b/docs/ru/docs/tutorial/encoder.md @@ -0,0 +1,42 @@ +# JSON кодировщик + +В некоторых случаях может потребоваться преобразование типа данных (например, Pydantic-модели) в тип, совместимый с JSON (например, `dict`, `list` и т.д.). + +Например, если необходимо хранить его в базе данных. + +Для этого **FastAPI** предоставляет функцию `jsonable_encoder()`. + +## Использование `jsonable_encoder` + +Представим, что у вас есть база данных `fake_db`, которая принимает только JSON-совместимые данные. + +Например, он не принимает объекты `datetime`, так как они не совместимы с JSON. + +В таком случае объект `datetime` следует преобразовать в строку соответствующую формату ISO. + +Точно так же эта база данных не может принять Pydantic модель (объект с атрибутами), а только `dict`. + +Для этого можно использовать функцию `jsonable_encoder`. + +Она принимает объект, например, модель Pydantic, и возвращает его версию, совместимую с JSON: + +=== "Python 3.10+" + + ```Python hl_lines="4 21" + {!> ../../../docs_src/encoder/tutorial001_py310.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="5 22" + {!> ../../../docs_src/encoder/tutorial001.py!} + ``` + +В данном примере она преобразует Pydantic модель в `dict`, а `datetime` - в `str`. + +Результатом её вызова является объект, который может быть закодирован с помощью функции из стандартной библиотеки Python – `json.dumps()`. + +Функция не возвращает большой `str`, содержащий данные в формате JSON (в виде строки). Она возвращает стандартную структуру данных Python (например, `dict`) со значениями и подзначениями, которые совместимы с JSON. + +!!! note "Технические детали" + `jsonable_encoder` фактически используется **FastAPI** внутри системы для преобразования данных. Однако он полезен и во многих других сценариях. diff --git a/docs/ru/docs/tutorial/extra-data-types.md b/docs/ru/docs/tutorial/extra-data-types.md index efcbcb38a2390..d4727e2d4d015 100644 --- a/docs/ru/docs/tutorial/extra-data-types.md +++ b/docs/ru/docs/tutorial/extra-data-types.md @@ -36,7 +36,7 @@ * `datetime.timedelta`: * Встроенный в Python `datetime.timedelta`. * В запросах и ответах будет представлен в виде общего количества секунд типа `float`. - * Pydantic также позволяет представить его как "Кодировку разницы во времени ISO 8601", см. документацию для получения дополнительной информации. + * Pydantic также позволяет представить его как "Кодировку разницы во времени ISO 8601", см. документацию для получения дополнительной информации. * `frozenset`: * В запросах и ответах обрабатывается так же, как и `set`: * В запросах будет прочитан список, исключены дубликаты и преобразован в `set`. @@ -49,13 +49,13 @@ * `Decimal`: * Встроенный в Python `Decimal`. * В запросах и ответах обрабатывается так же, как и `float`. -* Вы можете проверить все допустимые типы данных pydantic здесь: Типы данных Pydantic. +* Вы можете проверить все допустимые типы данных pydantic здесь: Типы данных Pydantic. ## Пример Вот пример *операции пути* с параметрами, который демонстрирует некоторые из вышеперечисленных типов. -=== "Python 3.6 и выше" +=== "Python 3.8 и выше" ```Python hl_lines="1 3 12-16" {!> ../../../docs_src/extra_data_types/tutorial001.py!} @@ -69,7 +69,7 @@ Обратите внимание, что параметры внутри функции имеют свой естественный тип данных, и вы, например, можете выполнять обычные манипуляции с датами, такие как: -=== "Python 3.6 и выше" +=== "Python 3.8 и выше" ```Python hl_lines="18-19" {!> ../../../docs_src/extra_data_types/tutorial001.py!} diff --git a/docs/ru/docs/tutorial/extra-models.md b/docs/ru/docs/tutorial/extra-models.md index a346f7432c7f1..78855313da8ce 100644 --- a/docs/ru/docs/tutorial/extra-models.md +++ b/docs/ru/docs/tutorial/extra-models.md @@ -23,7 +23,7 @@ {!> ../../../docs_src/extra_models/tutorial001_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" {!> ../../../docs_src/extra_models/tutorial001.py!} @@ -164,7 +164,7 @@ UserInDB( {!> ../../../docs_src/extra_models/tutorial002_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9 15-16 19-20 23-24" {!> ../../../docs_src/extra_models/tutorial002.py!} @@ -179,7 +179,7 @@ UserInDB( Для этого используйте стандартные аннотации типов в Python `typing.Union`: !!! note "Примечание" - При объявлении `Union`, сначала указывайте наиболее детальные типы, затем менее детальные. В примере ниже более детальный `PlaneItem` стоит перед `CarItem` в `Union[PlaneItem, CarItem]`. + При объявлении `Union`, сначала указывайте наиболее детальные типы, затем менее детальные. В примере ниже более детальный `PlaneItem` стоит перед `CarItem` в `Union[PlaneItem, CarItem]`. === "Python 3.10+" @@ -187,7 +187,7 @@ UserInDB( {!> ../../../docs_src/extra_models/tutorial003_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="1 14-15 18-20 33" {!> ../../../docs_src/extra_models/tutorial003.py!} @@ -219,7 +219,7 @@ some_variable: PlaneItem | CarItem {!> ../../../docs_src/extra_models/tutorial004_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="1 20" {!> ../../../docs_src/extra_models/tutorial004.py!} @@ -239,7 +239,7 @@ some_variable: PlaneItem | CarItem {!> ../../../docs_src/extra_models/tutorial005_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="1 8" {!> ../../../docs_src/extra_models/tutorial005.py!} diff --git a/docs/ru/docs/tutorial/handling-errors.md b/docs/ru/docs/tutorial/handling-errors.md new file mode 100644 index 0000000000000..40b6f9bc4a152 --- /dev/null +++ b/docs/ru/docs/tutorial/handling-errors.md @@ -0,0 +1,261 @@ +# Обработка ошибок + +Существует множество ситуаций, когда необходимо сообщить об ошибке клиенту, использующему ваш API. + +Таким клиентом может быть браузер с фронтендом, чужой код, IoT-устройство и т.д. + +Возможно, вам придется сообщить клиенту о следующем: + +* Клиент не имеет достаточных привилегий для выполнения данной операции. +* Клиент не имеет доступа к данному ресурсу. +* Элемент, к которому клиент пытался получить доступ, не существует. +* и т.д. + +В таких случаях обычно возвращается **HTTP-код статуса ответа** в диапазоне **400** (от 400 до 499). + +Они похожи на двухсотые HTTP статус-коды (от 200 до 299), которые означают, что запрос обработан успешно. + +Четырёхсотые статус-коды означают, что ошибка произошла по вине клиента. + +Помните ли ошибки **"404 Not Found "** (и шутки) ? + +## Использование `HTTPException` + +Для возврата клиенту HTTP-ответов с ошибками используется `HTTPException`. + +### Импортируйте `HTTPException` + +```Python hl_lines="1" +{!../../../docs_src/handling_errors/tutorial001.py!} +``` + +### Вызовите `HTTPException` в своем коде + +`HTTPException` - это обычное исключение Python с дополнительными данными, актуальными для API. + +Поскольку это исключение Python, то его не `возвращают`, а `вызывают`. + +Это также означает, что если вы находитесь внутри функции, которая вызывается внутри вашей *функции операции пути*, и вы поднимаете `HTTPException` внутри этой функции, то она не будет выполнять остальной код в *функции операции пути*, а сразу завершит запрос и отправит HTTP-ошибку из `HTTPException` клиенту. + +О том, насколько выгоднее `вызывать` исключение, чем `возвращать` значение, будет рассказано в разделе, посвященном зависимостям и безопасности. + +В данном примере, когда клиент запрашивает элемент по несуществующему ID, возникает исключение со статус-кодом `404`: + +```Python hl_lines="11" +{!../../../docs_src/handling_errors/tutorial001.py!} +``` + +### Возвращаемый ответ + +Если клиент запросит `http://example.com/items/foo` (`item_id` `"foo"`), то он получит статус-код 200 и ответ в формате JSON: + +```JSON +{ + "item": "The Foo Wrestlers" +} +``` + +Но если клиент запросит `http://example.com/items/bar` (несуществующий `item_id` `"bar"`), то он получит статус-код 404 (ошибка "не найдено") и JSON-ответ в виде: + +```JSON +{ + "detail": "Item not found" +} +``` + +!!! tip "Подсказка" + При вызове `HTTPException` в качестве параметра `detail` можно передавать любое значение, которое может быть преобразовано в JSON, а не только `str`. + + Вы можете передать `dict`, `list` и т.д. + + Они автоматически обрабатываются **FastAPI** и преобразуются в JSON. + +## Добавление пользовательских заголовков + +В некоторых ситуациях полезно иметь возможность добавлять пользовательские заголовки к ошибке HTTP. Например, для некоторых типов безопасности. + +Скорее всего, вам не потребуется использовать его непосредственно в коде. + +Но в случае, если это необходимо для продвинутого сценария, можно добавить пользовательские заголовки: + +```Python hl_lines="14" +{!../../../docs_src/handling_errors/tutorial002.py!} +``` + +## Установка пользовательских обработчиков исключений + +Вы можете добавить пользовательские обработчики исключений с помощью то же самое исключение - утилиты от Starlette. + +Допустим, у вас есть пользовательское исключение `UnicornException`, которое вы (или используемая вами библиотека) можете `вызвать`. + +И вы хотите обрабатывать это исключение глобально с помощью FastAPI. + +Можно добавить собственный обработчик исключений с помощью `@app.exception_handler()`: + +```Python hl_lines="5-7 13-18 24" +{!../../../docs_src/handling_errors/tutorial003.py!} +``` + +Здесь, если запросить `/unicorns/yolo`, то *операция пути* вызовет `UnicornException`. + +Но оно будет обработано `unicorn_exception_handler`. + +Таким образом, вы получите чистую ошибку с кодом состояния HTTP `418` и содержимым JSON: + +```JSON +{"message": "Oops! yolo did something. There goes a rainbow..."} +``` + +!!! note "Технические детали" + Также можно использовать `from starlette.requests import Request` и `from starlette.responses import JSONResponse`. + + **FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette. То же самое касается и `Request`. + +## Переопределение стандартных обработчиков исключений + +**FastAPI** имеет некоторые обработчики исключений по умолчанию. + +Эти обработчики отвечают за возврат стандартных JSON-ответов при `вызове` `HTTPException` и при наличии в запросе недопустимых данных. + +Вы можете переопределить эти обработчики исключений на свои собственные. + +### Переопределение исключений проверки запроса + +Когда запрос содержит недопустимые данные, **FastAPI** внутренне вызывает ошибку `RequestValidationError`. + +А также включает в себя обработчик исключений по умолчанию. + +Чтобы переопределить его, импортируйте `RequestValidationError` и используйте его с `@app.exception_handler(RequestValidationError)` для создания обработчика исключений. + +Обработчик исключения получит объект `Request` и исключение. + +```Python hl_lines="2 14-16" +{!../../../docs_src/handling_errors/tutorial004.py!} +``` + +Теперь, если перейти к `/items/foo`, то вместо стандартной JSON-ошибки с: + +```JSON +{ + "detail": [ + { + "loc": [ + "path", + "item_id" + ], + "msg": "value is not a valid integer", + "type": "type_error.integer" + } + ] +} +``` + +вы получите текстовую версию: + +``` +1 validation error +path -> item_id + value is not a valid integer (type=type_error.integer) +``` + +#### `RequestValidationError` или `ValidationError` + +!!! warning "Внимание" + Это технические детали, которые можно пропустить, если они не важны для вас сейчас. + +`RequestValidationError` является подклассом Pydantic `ValidationError`. + +**FastAPI** использует его для того, чтобы, если вы используете Pydantic-модель в `response_model`, и ваши данные содержат ошибку, вы увидели ошибку в журнале. + +Но клиент/пользователь этого не увидит. Вместо этого клиент получит сообщение "Internal Server Error" с кодом состояния HTTP `500`. + +Так и должно быть, потому что если в вашем *ответе* или где-либо в вашем коде (не в *запросе* клиента) возникает Pydantic `ValidationError`, то это действительно ошибка в вашем коде. + +И пока вы не устраните ошибку, ваши клиенты/пользователи не должны иметь доступа к внутренней информации о ней, так как это может привести к уязвимости в системе безопасности. + +### Переопределите обработчик ошибок `HTTPException` + +Аналогичным образом можно переопределить обработчик `HTTPException`. + +Например, для этих ошибок можно вернуть обычный текстовый ответ вместо JSON: + +```Python hl_lines="3-4 9-11 22" +{!../../../docs_src/handling_errors/tutorial004.py!} +``` + +!!! note "Технические детали" + Можно также использовать `from starlette.responses import PlainTextResponse`. + + **FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette. + +### Используйте тело `RequestValidationError` + +Ошибка `RequestValidationError` содержит полученное `тело` с недопустимыми данными. + +Вы можете использовать его при разработке приложения для регистрации тела и его отладки, возврата пользователю и т.д. + +```Python hl_lines="14" +{!../../../docs_src/handling_errors/tutorial005.py!} +``` + +Теперь попробуйте отправить недействительный элемент, например: + +```JSON +{ + "title": "towel", + "size": "XL" +} +``` + +Вы получите ответ о том, что данные недействительны, содержащий следующее тело: + +```JSON hl_lines="12-15" +{ + "detail": [ + { + "loc": [ + "body", + "size" + ], + "msg": "value is not a valid integer", + "type": "type_error.integer" + } + ], + "body": { + "title": "towel", + "size": "XL" + } +} +``` + +#### `HTTPException` в FastAPI или в Starlette + +**FastAPI** имеет собственный `HTTPException`. + +Класс ошибок **FastAPI** `HTTPException` наследует от класса ошибок Starlette `HTTPException`. + +Единственное отличие заключается в том, что `HTTPException` от **FastAPI** позволяет добавлять заголовки, которые будут включены в ответ. + +Он необходим/используется внутри системы для OAuth 2.0 и некоторых утилит безопасности. + +Таким образом, вы можете продолжать вызывать `HTTPException` от **FastAPI** как обычно в своем коде. + +Но когда вы регистрируете обработчик исключений, вы должны зарегистрировать его для `HTTPException` от Starlette. + +Таким образом, если какая-либо часть внутреннего кода Starlette, расширение или плагин Starlette вызовет исключение Starlette `HTTPException`, ваш обработчик сможет перехватить и обработать его. + +В данном примере, чтобы иметь возможность использовать оба `HTTPException` в одном коде, исключения Starlette переименованы в `StarletteHTTPException`: + +```Python +from starlette.exceptions import HTTPException as StarletteHTTPException +``` + +### Переиспользование обработчиков исключений **FastAPI** + +Если вы хотите использовать исключение вместе с теми же обработчиками исключений по умолчанию из **FastAPI**, вы можете импортировать и повторно использовать обработчики исключений по умолчанию из `fastapi.exception_handlers`: + +```Python hl_lines="2-5 15 21" +{!../../../docs_src/handling_errors/tutorial006.py!} +``` + +В этом примере вы просто `выводите в терминал` ошибку с очень выразительным сообщением, но идея вам понятна. Вы можете использовать исключение, а затем просто повторно использовать стандартные обработчики исключений. diff --git a/docs/ru/docs/tutorial/header-params.md b/docs/ru/docs/tutorial/header-params.md new file mode 100644 index 0000000000000..1be4ac707149f --- /dev/null +++ b/docs/ru/docs/tutorial/header-params.md @@ -0,0 +1,227 @@ +# Header-параметры + +Вы можете определить параметры заголовка таким же образом, как вы определяете параметры `Query`, `Path` и `Cookie`. + +## Импорт `Header` + +Сперва импортируйте `Header`: + +=== "Python 3.10+" + + ```Python hl_lines="3" + {!> ../../../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.8+" + + ```Python hl_lines="3" + {!> ../../../docs_src/header_params/tutorial001_an.py!} + ``` + +=== "Python 3.10+ без Annotated" + + !!! tip "Подсказка" + Предпочтительнее использовать версию с аннотацией, если это возможно. + + ```Python hl_lines="1" + {!> ../../../docs_src/header_params/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ без Annotated" + + !!! tip "Подсказка" + Предпочтительнее использовать версию с аннотацией, если это возможно. + + ```Python hl_lines="3" + {!> ../../../docs_src/header_params/tutorial001.py!} + ``` + +## Объявление параметров `Header` + +Затем объявите параметры заголовка, используя ту же структуру, что и с `Path`, `Query` и `Cookie`. + +Первое значение является значением по умолчанию, вы можете передать все дополнительные параметры валидации или аннотации: + +=== "Python 3.10+" + + ```Python hl_lines="9" + {!> ../../../docs_src/header_params/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="9" + {!> ../../../docs_src/header_params/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="10" + {!> ../../../docs_src/header_params/tutorial001_an.py!} + ``` + +=== "Python 3.10+ без Annotated" + + !!! tip "Подсказка" + Предпочтительнее использовать версию с аннотацией, если это возможно. + + ```Python hl_lines="7" + {!> ../../../docs_src/header_params/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ без Annotated" + + !!! tip "Подсказка" + Предпочтительнее использовать версию с аннотацией, если это возможно. + + ```Python hl_lines="9" + {!> ../../../docs_src/header_params/tutorial001.py!} + ``` + +!!! note "Технические детали" + `Header` - это "родственный" класс `Path`, `Query` и `Cookie`. Он также наследуется от того же общего класса `Param`. + + Но помните, что когда вы импортируете `Query`, `Path`, `Header` и другие из `fastapi`, на самом деле это функции, которые возвращают специальные классы. + +!!! info "Дополнительная информация" + Чтобы объявить заголовки, важно использовать `Header`, иначе параметры интерпретируются как query-параметры. + +## Автоматическое преобразование + +`Header` обладает небольшой дополнительной функциональностью в дополнение к тому, что предоставляют `Path`, `Query` и `Cookie`. + +Большинство стандартных заголовков разделены символом "дефис", также известным как "минус" (`-`). + +Но переменная вроде `user-agent` недопустима в Python. + +По умолчанию `Header` преобразует символы имен параметров из символа подчеркивания (`_`) в дефис (`-`) для извлечения и документирования заголовков. + +Кроме того, HTTP-заголовки не чувствительны к регистру, поэтому вы можете объявить их в стандартном стиле Python (также известном как "snake_case"). + +Таким образом вы можете использовать `user_agent`, как обычно, в коде Python, вместо того, чтобы вводить заглавные буквы как `User_Agent` или что-то подобное. + +Если по какой-либо причине вам необходимо отключить автоматическое преобразование подчеркиваний в дефисы, установите для параметра `convert_underscores` в `Header` значение `False`: + +=== "Python 3.10+" + + ```Python hl_lines="10" + {!> ../../../docs_src/header_params/tutorial002_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="11" + {!> ../../../docs_src/header_params/tutorial002_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="12" + {!> ../../../docs_src/header_params/tutorial002_an.py!} + ``` + +=== "Python 3.10+ без Annotated" + + !!! tip "Подсказка" + Предпочтительнее использовать версию с аннотацией, если это возможно. + + ```Python hl_lines="8" + {!> ../../../docs_src/header_params/tutorial002_py310.py!} + ``` + +=== "Python 3.8+ без Annotated" + + !!! tip "Подсказка" + Предпочтительнее использовать версию с аннотацией, если это возможно. + + ```Python hl_lines="10" + {!> ../../../docs_src/header_params/tutorial002.py!} + ``` + +!!! warning "Внимание" + Прежде чем установить для `convert_underscores` значение `False`, имейте в виду, что некоторые HTTP-прокси и серверы запрещают использование заголовков с подчеркиванием. + +## Повторяющиеся заголовки + +Есть возможность получать несколько заголовков с одним и тем же именем, но разными значениями. + +Вы можете определить эти случаи, используя список в объявлении типа. + +Вы получите все значения из повторяющегося заголовка в виде `list` Python. + +Например, чтобы объявить заголовок `X-Token`, который может появляться более одного раза, вы можете написать: + +=== "Python 3.10+" + + ```Python hl_lines="9" + {!> ../../../docs_src/header_params/tutorial003_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="9" + {!> ../../../docs_src/header_params/tutorial003_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="10" + {!> ../../../docs_src/header_params/tutorial003_an.py!} + ``` + +=== "Python 3.10+ без Annotated" + + !!! tip "Подсказка" + Предпочтительнее использовать версию с аннотацией, если это возможно. + + ```Python hl_lines="7" + {!> ../../../docs_src/header_params/tutorial003_py310.py!} + ``` + +=== "Python 3.9+ без Annotated" + + !!! tip "Подсказка" + Предпочтительнее использовать версию с аннотацией, если это возможно. + + ```Python hl_lines="9" + {!> ../../../docs_src/header_params/tutorial003_py39.py!} + ``` + +=== "Python 3.8+ без Annotated" + + !!! tip "Подсказка" + Предпочтительнее использовать версию с аннотацией, если это возможно. + + ```Python hl_lines="9" + {!> ../../../docs_src/header_params/tutorial003.py!} + ``` + +Если вы взаимодействуете с этой *операцией пути*, отправляя два HTTP-заголовка, таких как: + +``` +X-Token: foo +X-Token: bar +``` + +Ответ был бы таким: + +```JSON +{ + "X-Token values": [ + "bar", + "foo" + ] +} +``` + +## Резюме + +Объявляйте заголовки с помощью `Header`, используя тот же общий шаблон, как при `Query`, `Path` и `Cookie`. + +И не беспокойтесь о символах подчеркивания в ваших переменных, **FastAPI** позаботится об их преобразовании. diff --git a/docs/ru/docs/tutorial/path-operation-configuration.md b/docs/ru/docs/tutorial/path-operation-configuration.md index 013903add1cc0..db99409f469bf 100644 --- a/docs/ru/docs/tutorial/path-operation-configuration.md +++ b/docs/ru/docs/tutorial/path-operation-configuration.md @@ -25,7 +25,7 @@ {!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="3 17" {!> ../../../docs_src/path_operation_configuration/tutorial001.py!} @@ -54,7 +54,7 @@ {!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="17 22 27" {!> ../../../docs_src/path_operation_configuration/tutorial002.py!} @@ -92,7 +92,7 @@ {!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="20-21" {!> ../../../docs_src/path_operation_configuration/tutorial003.py!} @@ -116,7 +116,7 @@ {!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="19-27" {!> ../../../docs_src/path_operation_configuration/tutorial004.py!} @@ -142,7 +142,7 @@ {!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="21" {!> ../../../docs_src/path_operation_configuration/tutorial005.py!} diff --git a/docs/ru/docs/tutorial/path-params-numeric-validations.md b/docs/ru/docs/tutorial/path-params-numeric-validations.md index 0d034ef343897..bd2c29d0a0013 100644 --- a/docs/ru/docs/tutorial/path-params-numeric-validations.md +++ b/docs/ru/docs/tutorial/path-params-numeric-validations.md @@ -18,7 +18,7 @@ {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="3-4" {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} @@ -33,7 +33,7 @@ {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} ``` -=== "Python 3.6+ без Annotated" +=== "Python 3.8+ без Annotated" !!! tip "Подсказка" Рекомендуется использовать версию с `Annotated` если возможно. @@ -67,7 +67,7 @@ {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="11" {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} @@ -82,7 +82,7 @@ {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} ``` -=== "Python 3.6+ без Annotated" +=== "Python 3.8+ без Annotated" !!! tip "Подсказка" Рекомендуется использовать версию с `Annotated` если возможно. @@ -117,7 +117,7 @@ Поэтому вы можете определить функцию так: -=== "Python 3.6 без Annotated" +=== "Python 3.8 без Annotated" !!! tip "Подсказка" Рекомендуется использовать версию с `Annotated` если возможно. @@ -134,7 +134,7 @@ {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9" {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!} @@ -174,7 +174,7 @@ Python не будет ничего делать с `*`, но он будет з {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9" {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!} @@ -192,13 +192,13 @@ Python не будет ничего делать с `*`, но он будет з {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9" {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!} ``` -=== "Python 3.6+ без Annotated" +=== "Python 3.8+ без Annotated" !!! tip "Подсказка" Рекомендуется использовать версию с `Annotated` если возможно. @@ -220,13 +220,13 @@ Python не будет ничего делать с `*`, но он будет з {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9" {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!} ``` -=== "Python 3.6+ без Annotated" +=== "Python 3.8+ без Annotated" !!! tip "Подсказка" Рекомендуется использовать версию с `Annotated` если возможно. @@ -251,13 +251,13 @@ Python не будет ничего делать с `*`, но он будет з {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="12" {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!} ``` -=== "Python 3.6+ без Annotated" +=== "Python 3.8+ без Annotated" !!! tip "Подсказка" Рекомендуется использовать версию с `Annotated` если возможно. diff --git a/docs/ru/docs/tutorial/path-params.md b/docs/ru/docs/tutorial/path-params.md index 55b498ef0acd2..1241e0919d046 100644 --- a/docs/ru/docs/tutorial/path-params.md +++ b/docs/ru/docs/tutorial/path-params.md @@ -93,7 +93,7 @@ ## Pydantic -Вся проверка данных выполняется под капотом с помощью Pydantic. Поэтому вы можете быть уверены в качестве обработки данных. +Вся проверка данных выполняется под капотом с помощью Pydantic. Поэтому вы можете быть уверены в качестве обработки данных. Вы можете использовать в аннотациях как простые типы данных, вроде `str`, `float`, `bool`, так и более сложные типы. diff --git a/docs/ru/docs/tutorial/query-params-str-validations.md b/docs/ru/docs/tutorial/query-params-str-validations.md index 68042db639629..108aefefc5db5 100644 --- a/docs/ru/docs/tutorial/query-params-str-validations.md +++ b/docs/ru/docs/tutorial/query-params-str-validations.md @@ -10,7 +10,7 @@ {!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9" {!> ../../../docs_src/query_params_str_validations/tutorial001.py!} @@ -42,7 +42,7 @@ Query-параметр `q` имеет тип `Union[str, None]` (или `str | N {!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" В версиях Python ниже Python 3.9 `Annotation` импортируется из `typing_extensions`. @@ -66,7 +66,7 @@ Query-параметр `q` имеет тип `Union[str, None]` (или `str | N q: str | None = None ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python q: Union[str, None] = None @@ -80,7 +80,7 @@ Query-параметр `q` имеет тип `Union[str, None]` (или `str | N q: Annotated[str | None] = None ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python q: Annotated[Union[str, None]] = None @@ -100,7 +100,7 @@ Query-параметр `q` имеет тип `Union[str, None]` (или `str | N {!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="10" {!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!} @@ -131,7 +131,7 @@ Query-параметр `q` имеет тип `Union[str, None]` (или `str | N {!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9" {!> ../../../docs_src/query_params_str_validations/tutorial002.py!} @@ -244,7 +244,7 @@ q: str = Query(default="rick") {!> ../../../docs_src/query_params_str_validations/tutorial003_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="11" {!> ../../../docs_src/query_params_str_validations/tutorial003_an.py!} @@ -259,7 +259,7 @@ q: str = Query(default="rick") {!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!} ``` -=== "Python 3.6+ без Annotated" +=== "Python 3.8+ без Annotated" !!! tip "Подсказка" Рекомендуется использовать версию с `Annotated` если возможно. @@ -284,7 +284,7 @@ q: str = Query(default="rick") {!> ../../../docs_src/query_params_str_validations/tutorial004_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="12" {!> ../../../docs_src/query_params_str_validations/tutorial004_an.py!} @@ -299,7 +299,7 @@ q: str = Query(default="rick") {!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!} ``` -=== "Python 3.6+ без Annotated" +=== "Python 3.8+ без Annotated" !!! tip "Подсказка" Рекомендуется использовать версию с `Annotated` если возможно. @@ -330,13 +330,13 @@ q: str = Query(default="rick") {!> ../../../docs_src/query_params_str_validations/tutorial005_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="8" {!> ../../../docs_src/query_params_str_validations/tutorial005_an.py!} ``` -=== "Python 3.6+ без Annotated" +=== "Python 3.8+ без Annotated" !!! tip "Подсказка" Рекомендуется использовать версию с `Annotated` если возможно. @@ -384,13 +384,13 @@ q: Union[str, None] = None {!> ../../../docs_src/query_params_str_validations/tutorial006_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="8" {!> ../../../docs_src/query_params_str_validations/tutorial006_an.py!} ``` -=== "Python 3.6+ без Annotated" +=== "Python 3.8+ без Annotated" !!! tip "Подсказка" Рекомендуется использовать версию с `Annotated` если возможно. @@ -414,13 +414,13 @@ q: Union[str, None] = None {!> ../../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="8" {!> ../../../docs_src/query_params_str_validations/tutorial006b_an.py!} ``` -=== "Python 3.6+ без Annotated" +=== "Python 3.8+ без Annotated" !!! tip "Подсказка" Рекомендуется использовать версию с `Annotated` если возможно. @@ -454,7 +454,7 @@ q: Union[str, None] = None {!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="10" {!> ../../../docs_src/query_params_str_validations/tutorial006c_an.py!} @@ -469,7 +469,7 @@ q: Union[str, None] = None {!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!} ``` -=== "Python 3.6+ без Annotated" +=== "Python 3.8+ без Annotated" !!! tip "Подсказка" Рекомендуется использовать версию с `Annotated` если возможно. @@ -479,7 +479,7 @@ q: Union[str, None] = None ``` !!! tip "Подсказка" - Pydantic, мощь которого используется в FastAPI для валидации и сериализации, имеет специальное поведение для `Optional` или `Union[Something, None]` без значения по умолчанию. Вы можете узнать об этом больше в документации Pydantic, раздел Обязательные Опциональные поля. + Pydantic, мощь которого используется в FastAPI для валидации и сериализации, имеет специальное поведение для `Optional` или `Union[Something, None]` без значения по умолчанию. Вы можете узнать об этом больше в документации Pydantic, раздел Обязательные Опциональные поля. ### Использование Pydantic's `Required` вместо Ellipsis (`...`) @@ -491,13 +491,13 @@ q: Union[str, None] = None {!> ../../../docs_src/query_params_str_validations/tutorial006d_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="2 9" {!> ../../../docs_src/query_params_str_validations/tutorial006d_an.py!} ``` -=== "Python 3.6+ без Annotated" +=== "Python 3.8+ без Annotated" !!! tip "Подсказка" Рекомендуется использовать версию с `Annotated` если возможно. @@ -527,7 +527,7 @@ q: Union[str, None] = None {!> ../../../docs_src/query_params_str_validations/tutorial011_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="10" {!> ../../../docs_src/query_params_str_validations/tutorial011_an.py!} @@ -551,7 +551,7 @@ q: Union[str, None] = None {!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!} ``` -=== "Python 3.6+ без Annotated" +=== "Python 3.8+ без Annotated" !!! tip "Подсказка" Рекомендуется использовать версию с `Annotated` если возможно. @@ -596,7 +596,7 @@ http://localhost:8000/items/?q=foo&q=bar {!> ../../../docs_src/query_params_str_validations/tutorial012_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="10" {!> ../../../docs_src/query_params_str_validations/tutorial012_an.py!} @@ -611,7 +611,7 @@ http://localhost:8000/items/?q=foo&q=bar {!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!} ``` -=== "Python 3.6+ без Annotated" +=== "Python 3.8+ без Annotated" !!! tip "Подсказка" Рекомендуется использовать версию с `Annotated` если возможно. @@ -647,13 +647,13 @@ http://localhost:8000/items/ {!> ../../../docs_src/query_params_str_validations/tutorial013_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="8" {!> ../../../docs_src/query_params_str_validations/tutorial013_an.py!} ``` -=== "Python 3.6+ без Annotated" +=== "Python 3.8+ без Annotated" !!! tip "Подсказка" Рекомендуется использовать версию с `Annotated` если возможно. @@ -692,7 +692,7 @@ http://localhost:8000/items/ {!> ../../../docs_src/query_params_str_validations/tutorial007_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="11" {!> ../../../docs_src/query_params_str_validations/tutorial007_an.py!} @@ -707,7 +707,7 @@ http://localhost:8000/items/ {!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!} ``` -=== "Python 3.6+ без Annotated" +=== "Python 3.8+ без Annotated" !!! tip "Подсказка" Рекомендуется использовать версию с `Annotated` если возможно. @@ -730,7 +730,7 @@ http://localhost:8000/items/ {!> ../../../docs_src/query_params_str_validations/tutorial008_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="15" {!> ../../../docs_src/query_params_str_validations/tutorial008_an.py!} @@ -741,11 +741,11 @@ http://localhost:8000/items/ !!! tip "Подсказка" Рекомендуется использовать версию с `Annotated` если возможно. - ```Python hl_lines="12" + ```Python hl_lines="11" {!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!} ``` -=== "Python 3.6+ без Annotated" +=== "Python 3.8+ без Annotated" !!! tip "Подсказка" Рекомендуется использовать версию с `Annotated` если возможно. @@ -784,7 +784,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems {!> ../../../docs_src/query_params_str_validations/tutorial009_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="10" {!> ../../../docs_src/query_params_str_validations/tutorial009_an.py!} @@ -799,7 +799,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems {!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!} ``` -=== "Python 3.6+ без Annotated" +=== "Python 3.8+ без Annotated" !!! tip "Подсказка" Рекомендуется использовать версию с `Annotated` если возможно. @@ -828,7 +828,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems {!> ../../../docs_src/query_params_str_validations/tutorial010_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="20" {!> ../../../docs_src/query_params_str_validations/tutorial010_an.py!} @@ -839,11 +839,11 @@ http://127.0.0.1:8000/items/?item-query=foobaritems !!! tip "Подсказка" Рекомендуется использовать версию с `Annotated` если возможно. - ```Python hl_lines="17" + ```Python hl_lines="16" {!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!} ``` -=== "Python 3.6+ без Annotated" +=== "Python 3.8+ без Annotated" !!! tip "Подсказка" Рекомендуется использовать версию с `Annotated` если возможно. @@ -872,7 +872,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems {!> ../../../docs_src/query_params_str_validations/tutorial014_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="11" {!> ../../../docs_src/query_params_str_validations/tutorial014_an.py!} @@ -887,7 +887,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems {!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!} ``` -=== "Python 3.6+ без Annotated" +=== "Python 3.8+ без Annotated" !!! tip "Подсказка" Рекомендуется использовать версию с `Annotated` если возможно. diff --git a/docs/ru/docs/tutorial/query-params.md b/docs/ru/docs/tutorial/query-params.md index 68333ec56604c..6e885cb656fe4 100644 --- a/docs/ru/docs/tutorial/query-params.md +++ b/docs/ru/docs/tutorial/query-params.md @@ -69,7 +69,7 @@ http://127.0.0.1:8000/items/?skip=20 {!> ../../../docs_src/query_params/tutorial002_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9" {!> ../../../docs_src/query_params/tutorial002.py!} @@ -90,7 +90,7 @@ http://127.0.0.1:8000/items/?skip=20 {!> ../../../docs_src/query_params/tutorial003_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9" {!> ../../../docs_src/query_params/tutorial003.py!} @@ -143,7 +143,7 @@ http://127.0.0.1:8000/items/foo?short=yes {!> ../../../docs_src/query_params/tutorial004_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="8 10" {!> ../../../docs_src/query_params/tutorial004.py!} @@ -209,7 +209,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy {!> ../../../docs_src/query_params/tutorial006_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="10" {!> ../../../docs_src/query_params/tutorial006.py!} diff --git a/docs/ru/docs/tutorial/request-files.md b/docs/ru/docs/tutorial/request-files.md new file mode 100644 index 0000000000000..79b3bd067f7d2 --- /dev/null +++ b/docs/ru/docs/tutorial/request-files.md @@ -0,0 +1,314 @@ +# Загрузка файлов + +Используя класс `File`, мы можем позволить клиентам загружать файлы. + +!!! info "Дополнительная информация" + Чтобы получать загруженные файлы, сначала установите `python-multipart`. + + Например: `pip install python-multipart`. + + Это связано с тем, что загружаемые файлы передаются как данные формы. + +## Импорт `File` + +Импортируйте `File` и `UploadFile` из модуля `fastapi`: + +=== "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+ без Annotated" + + !!! tip "Подсказка" + Предпочтительнее использовать версию с аннотацией, если это возможно. + + ```Python hl_lines="1" + {!> ../../../docs_src/request_files/tutorial001.py!} + ``` + +## Определите параметры `File` + +Создайте параметры `File` так же, как вы это делаете для `Body` или `Form`: + +=== "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+ без Annotated" + + !!! tip "Подсказка" + Предпочтительнее использовать версию с аннотацией, если это возможно. + + ```Python hl_lines="7" + {!> ../../../docs_src/request_files/tutorial001.py!} + ``` + +!!! info "Дополнительная информация" + `File` - это класс, который наследуется непосредственно от `Form`. + + Но помните, что когда вы импортируете `Query`, `Path`, `File` и другие из `fastapi`, на самом деле это функции, которые возвращают специальные классы. + +!!! tip "Подсказка" + Для объявления тела файла необходимо использовать `File`, поскольку в противном случае параметры будут интерпретироваться как параметры запроса или параметры тела (JSON). + +Файлы будут загружены как данные формы. + +Если вы объявите тип параметра у *функции операции пути* как `bytes`, то **FastAPI** прочитает файл за вас, и вы получите его содержимое в виде `bytes`. + +Следует иметь в виду, что все содержимое будет храниться в памяти. Это хорошо подходит для небольших файлов. + +Однако возможны случаи, когда использование `UploadFile` может оказаться полезным. + +## Загрузка файла с помощью `UploadFile` + +Определите параметр файла с типом `UploadFile`: + +=== "Python 3.9+" + + ```Python hl_lines="14" + {!> ../../../docs_src/request_files/tutorial001_an_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="13" + {!> ../../../docs_src/request_files/tutorial001_an.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "Подсказка" + Предпочтительнее использовать версию с аннотацией, если это возможно. + + ```Python hl_lines="12" + {!> ../../../docs_src/request_files/tutorial001.py!} + ``` + +Использование `UploadFile` имеет ряд преимуществ перед `bytes`: + +* Использовать `File()` в значении параметра по умолчанию не обязательно. +* При этом используется "буферный" файл: + * Файл, хранящийся в памяти до максимального предела размера, после преодоления которого он будет храниться на диске. +* Это означает, что он будет хорошо работать с большими файлами, такими как изображения, видео, большие бинарные файлы и т.д., не потребляя при этом всю память. +* Из загруженного файла можно получить метаданные. +* Он реализует file-like `async` интерфейс. +* Он предоставляет реальный объект Python `SpooledTemporaryFile` который вы можете передать непосредственно другим библиотекам, которые ожидают файл в качестве объекта. + +### `UploadFile` + +`UploadFile` имеет следующие атрибуты: + +* `filename`: Строка `str` с исходным именем файла, который был загружен (например, `myimage.jpg`). +* `content_type`: Строка `str` с типом содержимого (MIME type / media type) (например, `image/jpeg`). +* `file`: `SpooledTemporaryFile` (a file-like объект). Это фактический файл Python, который можно передавать непосредственно другим функциям или библиотекам, ожидающим файл в качестве объекта. + +`UploadFile` имеет следующие методы `async`. Все они вызывают соответствующие файловые методы (используя внутренний SpooledTemporaryFile). + +* `write(data)`: Записать данные `data` (`str` или `bytes`) в файл. +* `read(size)`: Прочитать количество `size` (`int`) байт/символов из файла. +* `seek(offset)`: Перейти к байту на позиции `offset` (`int`) в файле. + * Наример, `await myfile.seek(0)` перейдет к началу файла. + * Это особенно удобно, если вы один раз выполнили команду `await myfile.read()`, а затем вам нужно прочитать содержимое файла еще раз. +* `close()`: Закрыть файл. + +Поскольку все эти методы являются `async` методами, вам следует использовать "await" вместе с ними. + +Например, внутри `async` *функции операции пути* можно получить содержимое с помощью: + +```Python +contents = await myfile.read() +``` + +Если вы находитесь внутри обычной `def` *функции операции пути*, можно получить прямой доступ к файлу `UploadFile.file`, например: + +```Python +contents = myfile.file.read() +``` + +!!! note "Технические детали `async`" + При использовании методов `async` **FastAPI** запускает файловые методы в пуле потоков и ожидает их. + +!!! note "Технические детали Starlette" + **FastAPI** наследует `UploadFile` непосредственно из **Starlette**, но добавляет некоторые детали для совместимости с **Pydantic** и другими частями FastAPI. + +## Про данные формы ("Form Data") + +Способ, которым HTML-формы (`
`) отправляют данные на сервер, обычно использует "специальную" кодировку для этих данных, отличную от JSON. + +**FastAPI** позаботится о том, чтобы считать эти данные из нужного места, а не из JSON. + +!!! note "Технические детали" + Данные из форм обычно кодируются с использованием "media type" `application/x-www-form-urlencoded` когда он не включает файлы. + + Но когда форма включает файлы, она кодируется как multipart/form-data. Если вы используете `File`, **FastAPI** будет знать, что ему нужно получить файлы из нужной части тела. + + Если вы хотите узнать больше об этих кодировках и полях форм, перейдите по ссылке MDN web docs for POST. + +!!! warning "Внимание" + В операции *функции операции пути* можно объявить несколько параметров `File` и `Form`, но нельзя также объявлять поля `Body`, которые предполагается получить в виде JSON, поскольку тело запроса будет закодировано с помощью `multipart/form-data`, а не `application/json`. + + Это не является ограничением **FastAPI**, это часть протокола HTTP. + +## Необязательная загрузка файлов + +Вы можете сделать загрузку файла необязательной, используя стандартные аннотации типов и установив значение по умолчанию `None`: + +=== "Python 3.10+" + + ```Python hl_lines="9 17" + {!> ../../../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+ без Annotated" + + !!! tip "Подсказка" + Предпочтительнее использовать версию с аннотацией, если это возможно. + + ```Python hl_lines="7 15" + {!> ../../../docs_src/request_files/tutorial001_02_py310.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "Подсказка" + Предпочтительнее использовать версию с аннотацией, если это возможно. + + ```Python hl_lines="9 17" + {!> ../../../docs_src/request_files/tutorial001_02.py!} + ``` + +## `UploadFile` с дополнительными метаданными + +Вы также можете использовать `File()` вместе с `UploadFile`, например, для установки дополнительных метаданных: + +=== "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+ без Annotated" + + !!! tip "Подсказка" + Предпочтительнее использовать версию с аннотацией, если это возможно. + + ```Python hl_lines="7 13" + {!> ../../../docs_src/request_files/tutorial001_03.py!} + ``` + +## Загрузка нескольких файлов + +Можно одновременно загружать несколько файлов. + +Они будут связаны с одним и тем же "полем формы", отправляемым с помощью данных формы. + +Для этого необходимо объявить список `bytes` или `UploadFile`: + +=== "Python 3.9+" + + ```Python hl_lines="10 15" + {!> ../../../docs_src/request_files/tutorial002_an_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="11 16" + {!> ../../../docs_src/request_files/tutorial002_an.py!} + ``` + +=== "Python 3.9+ без Annotated" + + !!! tip "Подсказка" + Предпочтительнее использовать версию с аннотацией, если это возможно. + + ```Python hl_lines="8 13" + {!> ../../../docs_src/request_files/tutorial002_py39.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "Подсказка" + Предпочтительнее использовать версию с аннотацией, если это возможно. + + ```Python hl_lines="10 15" + {!> ../../../docs_src/request_files/tutorial002.py!} + ``` + +Вы получите, как и было объявлено, список `list` из `bytes` или `UploadFile`. + +!!! note "Technical Details" + Можно также использовать `from starlette.responses import HTMLResponse`. + + **FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette. + +### Загрузка нескольких файлов с дополнительными метаданными + +Так же, как и раньше, вы можете использовать `File()` для задания дополнительных параметров, даже для `UploadFile`: + +=== "Python 3.9+" + + ```Python hl_lines="11 18-20" + {!> ../../../docs_src/request_files/tutorial003_an_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="12 19-21" + {!> ../../../docs_src/request_files/tutorial003_an.py!} + ``` + +=== "Python 3.9+ без Annotated" + + !!! tip "Подсказка" + Предпочтительнее использовать версию с аннотацией, если это возможно. + + ```Python hl_lines="9 16" + {!> ../../../docs_src/request_files/tutorial003_py39.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "Подсказка" + Предпочтительнее использовать версию с аннотацией, если это возможно. + + ```Python hl_lines="11 18" + {!> ../../../docs_src/request_files/tutorial003.py!} + ``` + +## Резюме + +Используйте `File`, `bytes` и `UploadFile` для работы с файлами, которые будут загружаться и передаваться в виде данных формы. diff --git a/docs/ru/docs/tutorial/request-forms-and-files.md b/docs/ru/docs/tutorial/request-forms-and-files.md new file mode 100644 index 0000000000000..a08232ca73913 --- /dev/null +++ b/docs/ru/docs/tutorial/request-forms-and-files.md @@ -0,0 +1,69 @@ +# Файлы и формы в запросе + +Вы можете определять файлы и поля формы одновременно, используя `File` и `Form`. + +!!! info "Дополнительная информация" + Чтобы получать загруженные файлы и/или данные форм, сначала установите `python-multipart`. + + Например: `pip install python-multipart`. + +## Импортируйте `File` и `Form` + +=== "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+ без Annotated" + + !!! tip "Подсказка" + Предпочтительнее использовать версию с аннотацией, если это возможно. + + ```Python hl_lines="1" + {!> ../../../docs_src/request_forms_and_files/tutorial001.py!} + ``` + +## Определите параметры `File` и `Form` + +Создайте параметры файла и формы таким же образом, как для `Body` или `Query`: + +=== "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+ без Annotated" + + !!! tip "Подсказка" + Предпочтительнее использовать версию с аннотацией, если это возможно. + + ```Python hl_lines="8" + {!> ../../../docs_src/request_forms_and_files/tutorial001.py!} + ``` + +Файлы и поля формы будут загружены в виде данных формы, и вы получите файлы и поля формы. + +Вы можете объявить некоторые файлы как `bytes`, а некоторые - как `UploadFile`. + +!!! warning "Внимание" + Вы можете объявить несколько параметров `File` и `Form` в операции *path*, но вы не можете также объявить поля `Body`, которые вы ожидаете получить в виде JSON, так как запрос будет иметь тело, закодированное с помощью `multipart/form-data` вместо `application/json`. + + Это не ограничение **Fast API**, это часть протокола HTTP. + +## Резюме + +Используйте `File` и `Form` вместе, когда необходимо получить данные и файлы в одном запросе. diff --git a/docs/ru/docs/tutorial/request-forms.md b/docs/ru/docs/tutorial/request-forms.md new file mode 100644 index 0000000000000..fa2bcb7cbb902 --- /dev/null +++ b/docs/ru/docs/tutorial/request-forms.md @@ -0,0 +1,92 @@ +# Данные формы + +Когда вам нужно получить поля формы вместо JSON, вы можете использовать `Form`. + +!!! info "Дополнительная информация" + Чтобы использовать формы, сначала установите `python-multipart`. + + Например, выполните команду `pip install python-multipart`. + +## Импорт `Form` + +Импортируйте `Form` из `fastapi`: + +=== "Python 3.9+" + + ```Python hl_lines="3" + {!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="1" + {!> ../../../docs_src/request_forms/tutorial001_an.py!} + ``` + +=== "Python 3.8+ без Annotated" + + !!! tip "Подсказка" + Рекомендуется использовать 'Annotated' версию, если это возможно. + + ```Python hl_lines="1" + {!> ../../../docs_src/request_forms/tutorial001.py!} + ``` + +## Определение параметров `Form` + +Создайте параметры формы так же, как это делается для `Body` или `Query`: + +=== "Python 3.9+" + + ```Python hl_lines="9" + {!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="8" + {!> ../../../docs_src/request_forms/tutorial001_an.py!} + ``` + +=== "Python 3.8+ без Annotated" + + !!! tip "Подсказка" + Рекомендуется использовать 'Annotated' версию, если это возможно. + + ```Python hl_lines="7" + {!> ../../../docs_src/request_forms/tutorial001.py!} + ``` + +Например, в одном из способов использования спецификации OAuth2 (называемом "потоком пароля") требуется отправить `username` и `password` в виде полей формы. + +Данный способ требует отправку данных для авторизации посредством формы (а не JSON) и обязательного наличия в форме строго именованных полей `username` и `password`. + +Вы можете настроить `Form` точно так же, как настраиваете и `Body` ( `Query`, `Path`, `Cookie`), включая валидации, примеры, псевдонимы (например, `user-name` вместо `username`) и т.д. + +!!! info "Дополнительная информация" + `Form` - это класс, который наследуется непосредственно от `Body`. + +!!! tip "Подсказка" + Вам необходимо явно указывать параметр `Form` при объявлении каждого поля, иначе поля будут интерпретироваться как параметры запроса или параметры тела (JSON). + +## О "полях формы" + +Обычно способ, которым HTML-формы (`
`) отправляют данные на сервер, использует "специальное" кодирование для этих данных, отличное от JSON. + +**FastAPI** гарантирует правильное чтение этих данных из соответствующего места, а не из JSON. + +!!! note "Технические детали" + Данные из форм обычно кодируются с использованием "типа медиа" `application/x-www-form-urlencoded`. + + Но когда форма содержит файлы, она кодируется как `multipart/form-data`. Вы узнаете о работе с файлами в следующей главе. + + Если вы хотите узнать больше про кодировки и поля формы, ознакомьтесь с документацией MDN для `POST` на веб-сайте. + +!!! warning "Предупреждение" + Вы можете объявлять несколько параметров `Form` в *операции пути*, но вы не можете одновременно с этим объявлять поля `Body`, которые вы ожидаете получить в виде JSON, так как запрос будет иметь тело, закодированное с использованием `application/x-www-form-urlencoded`, а не `application/json`. + + Это не ограничение **FastAPI**, это часть протокола HTTP. + +## Резюме + +Используйте `Form` для объявления входных параметров данных формы. diff --git a/docs/ru/docs/tutorial/response-model.md b/docs/ru/docs/tutorial/response-model.md new file mode 100644 index 0000000000000..9b9b60dd5501a --- /dev/null +++ b/docs/ru/docs/tutorial/response-model.md @@ -0,0 +1,480 @@ +# Модель ответа - Возвращаемый тип + +Вы можете объявить тип ответа, указав аннотацию **возвращаемого значения** для *функции операции пути*. + +FastAPI позволяет использовать **аннотации типов** таким же способом, как и для ввода данных в **параметры** функции, вы можете использовать модели Pydantic, списки, словари, скалярные типы (такие, как int, bool и т.д.). + +=== "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.8+" + + ```Python hl_lines="18 23" + {!> ../../../docs_src/response_model/tutorial001_01.py!} + ``` + +FastAPI будет использовать этот возвращаемый тип для: + +* **Валидации** ответа. + * Если данные невалидны (например, отсутствует одно из полей), это означает, что код *вашего* приложения работает некорректно и функция возвращает не то, что вы ожидаете. В таком случае приложение вернет server error вместо того, чтобы отправить неправильные данные. Таким образом, вы и ваши пользователи можете быть уверены, что получите корректные данные в том виде, в котором они ожидаются. +* Добавьте **JSON схему** для ответа внутри *операции пути* OpenAPI. + * Она будет использована для **автоматически генерируемой документации**. + * А также - для автоматической кодогенерации пользователями. + +Но самое важное: + +* Ответ будет **ограничен и отфильтрован** - т.е. в нем останутся только те данные, которые определены в возвращаемом типе. + * Это особенно важно для **безопасности**, далее мы рассмотрим эту тему подробнее. + +## Параметр `response_model` + +Бывают случаи, когда вам необходимо (или просто хочется) возвращать данные, которые не полностью соответствуют объявленному типу. + +Допустим, вы хотите, чтобы ваша функция **возвращала словарь (dict)** или объект из базы данных, но при этом **объявляете выходной тип как модель Pydantic**. Тогда именно указанная модель будет использована для автоматической документации, валидации и т.п. для объекта, который вы вернули (например, словаря или объекта из базы данных). + +Но если указать аннотацию возвращаемого типа, статическая проверка типов будет выдавать ошибку (абсолютно корректную в данном случае). Она будет говорить о том, что ваша функция должна возвращать данные одного типа (например, dict), а в аннотации вы объявили другой тип (например, модель Pydantic). + +В таком случае можно использовать параметр `response_model` внутри *декоратора операции пути* вместо аннотации возвращаемого значения функции. + +Параметр `response_model` может быть указан для любой *операции пути*: + +* `@app.get()` +* `@app.post()` +* `@app.put()` +* `@app.delete()` +* и др. + +=== "Python 3.10+" + + ```Python hl_lines="17 22 24-27" + {!> ../../../docs_src/response_model/tutorial001_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="17 22 24-27" + {!> ../../../docs_src/response_model/tutorial001_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="17 22 24-27" + {!> ../../../docs_src/response_model/tutorial001.py!} + ``` + +!!! note "Технические детали" + Помните, что параметр `response_model` является параметром именно декоратора http-методов (`get`, `post`, и т.п.). Не следует его указывать для *функций операций пути*, как вы бы поступили с другими параметрами или с телом запроса. + +`response_model` принимает те же типы, которые можно указать для какого-либо поля в модели Pydantic. Таким образом, это может быть как одиночная модель Pydantic, так и `список (list)` моделей Pydantic. Например, `List[Item]`. + +FastAPI будет использовать значение `response_model` для того, чтобы автоматически генерировать документацию, производить валидацию и т.п. А также для **конвертации и фильтрации выходных данных** в объявленный тип. + +!!! tip "Подсказка" + Если вы используете анализаторы типов со строгой проверкой (например, mypy), можно указать `Any` в качестве типа возвращаемого значения функции. + + Таким образом вы информируете ваш редактор кода, что намеренно возвращаете данные неопределенного типа. Но возможности FastAPI, такие как автоматическая генерация документации, валидация, фильтрация и т.д. все так же будут работать, просто используя параметр `response_model`. + +### Приоритет `response_model` + +Если одновременно указать аннотацию типа для ответа функции и параметр `response_model` - последний будет иметь больший приоритет и FastAPI будет использовать именно его. + +Таким образом вы можете объявить корректные аннотации типов к вашим функциям, даже если они возвращают тип, отличающийся от указанного в `response_model`. Они будут считаны во время статической проверки типов вашими помощниками, например, mypy. При этом вы все так же используете возможности FastAPI для автоматической документации, валидации и т.д. благодаря `response_model`. + +Вы можете указать значение `response_model=None`, чтобы отключить создание модели ответа для данной *операции пути*. Это может понадобиться, если вы добавляете аннотации типов для данных, не являющихся валидными полями Pydantic. Мы увидим пример кода для такого случая в одном из разделов ниже. + +## Получить и вернуть один и тот же тип данных + +Здесь мы объявили модель `UserIn`, которая хранит пользовательский пароль в открытом виде: + +=== "Python 3.10+" + + ```Python hl_lines="7 9" + {!> ../../../docs_src/response_model/tutorial002_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9 11" + {!> ../../../docs_src/response_model/tutorial002.py!} + ``` + +!!! info "Информация" + Чтобы использовать `EmailStr`, прежде необходимо установить `email_validator`. + Используйте `pip install email-validator` + или `pip install pydantic[email]`. + +Далее мы используем нашу модель в аннотациях типа как для аргумента функции, так и для выходного значения: + +=== "Python 3.10+" + + ```Python hl_lines="16" + {!> ../../../docs_src/response_model/tutorial002_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="18" + {!> ../../../docs_src/response_model/tutorial002.py!} + ``` + +Теперь всякий раз, когда клиент создает пользователя с паролем, API будет возвращать его пароль в ответе. + +В данном случае это не такая уж большая проблема, поскольку ответ получит тот же самый пользователь, который и создал пароль. + +Но что если мы захотим использовать эту модель для какой-либо другой *операции пути*? Мы можем, сами того не желая, отправить пароль любому другому пользователю. + +!!! danger "Осторожно" + Никогда не храните пароли пользователей в открытом виде, а также никогда не возвращайте их в ответе, как в примере выше. В противном случае - убедитесь, что вы хорошо продумали и учли все возможные риски такого подхода и вам известно, что вы делаете. + +## Создание модели для ответа + +Вместо этого мы можем создать входную модель, хранящую пароль в открытом виде и выходную модель без пароля: + +=== "Python 3.10+" + + ```Python hl_lines="9 11 16" + {!> ../../../docs_src/response_model/tutorial003_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9 11 16" + {!> ../../../docs_src/response_model/tutorial003.py!} + ``` + +В таком случае, даже несмотря на то, что наша *функция операции пути* возвращает тот же самый объект пользователя с паролем, полученным на вход: + +=== "Python 3.10+" + + ```Python hl_lines="24" + {!> ../../../docs_src/response_model/tutorial003_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="24" + {!> ../../../docs_src/response_model/tutorial003.py!} + ``` + +...мы указали в `response_model` модель `UserOut`, в которой отсутствует поле, содержащее пароль - и он будет исключен из ответа: + +=== "Python 3.10+" + + ```Python hl_lines="22" + {!> ../../../docs_src/response_model/tutorial003_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="22" + {!> ../../../docs_src/response_model/tutorial003.py!} + ``` + +Таким образом **FastAPI** позаботится о фильтрации ответа и исключит из него всё, что не указано в выходной модели (при помощи Pydantic). + +### `response_model` или возвращаемый тип данных + +В нашем примере модели входных данных и выходных данных различаются. И если мы укажем аннотацию типа выходного значения функции как `UserOut` - проверка типов выдаст ошибку из-за того, что мы возвращаем некорректный тип. Поскольку это 2 разных класса. + +Поэтому в нашем примере мы можем объявить тип ответа только в параметре `response_model`. + +...но продолжайте читать дальше, чтобы узнать как можно это обойти. + +## Возвращаемый тип и Фильтрация данных + +Продолжим рассматривать предыдущий пример. Мы хотели **аннотировать входные данные одним типом**, а выходное значение - **другим типом**. + +Мы хотим, чтобы FastAPI продолжал **фильтровать** данные, используя `response_model`. + +В прошлом примере, т.к. входной и выходной типы являлись разными классами, мы были вынуждены использовать параметр `response_model`. И как следствие, мы лишались помощи статических анализаторов для проверки ответа функции. + +Но в подавляющем большинстве случаев мы будем хотеть, чтобы модель ответа лишь **фильтровала/удаляла** некоторые данные из ответа, как в нашем примере. + +И в таких случаях мы можем использовать классы и наследование, чтобы пользоваться преимуществами **аннотаций типов** и получать более полную статическую проверку типов. Но при этом все так же получать **фильтрацию ответа** от FastAPI. + +=== "Python 3.10+" + + ```Python hl_lines="7-10 13-14 18" + {!> ../../../docs_src/response_model/tutorial003_01_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9-13 15-16 20" + {!> ../../../docs_src/response_model/tutorial003_01.py!} + ``` + +Таким образом, мы получаем поддержку редактора кода и mypy в части типов, сохраняя при этом фильтрацию данных от FastAPI. + +Как это возможно? Давайте разберемся. 🤓 + +### Аннотации типов и инструменты для их проверки + +Для начала давайте рассмотрим как наш редактор кода, mypy и другие помощники разработчика видят аннотации типов. + +У модели `BaseUser` есть некоторые поля. Затем `UserIn` наследуется от `BaseUser` и добавляет новое поле `password`. Таким образом модель будет включать в себя все поля из первой модели (родителя), а также свои собственные. + +Мы аннотируем возвращаемый тип функции как `BaseUser`, но фактически мы будем возвращать объект типа `UserIn`. + +Редакторы, mypy и другие инструменты не будут иметь возражений против такого подхода, поскольку `UserIn` является подклассом `BaseUser`. Это означает, что такой тип будет *корректным*, т.к. ответ может быть чем угодно, если это будет `BaseUser`. + +### Фильтрация Данных FastAPI + +FastAPI знает тип ответа функции, так что вы можете быть уверены, что на выходе будут **только** те поля, которые вы указали. + +FastAPI совместно с Pydantic выполнит некоторую магию "под капотом", чтобы убедиться, что те же самые правила наследования классов не используются для фильтрации возвращаемых данных, в противном случае вы могли бы в конечном итоге вернуть гораздо больше данных, чем ожидали. + +Таким образом, вы можете получить все самое лучшее из обоих миров: аннотации типов с **поддержкой инструментов для разработки** и **фильтрацию данных**. + +## Автоматическая документация + +Если посмотреть на сгенерированную документацию, вы можете убедиться, что в ней присутствуют обе JSON схемы - как для входной модели, так и для выходной: + + + +И также обе модели будут использованы в интерактивной документации API: + + + +## Другие аннотации типов + +Бывают случаи, когда вы возвращаете что-то, что не является валидным типом для Pydantic и вы указываете аннотацию ответа функции только для того, чтобы работала поддержка различных инструментов (редактор кода, mypy и др.). + +### Возвращаем Response + +Самый частый сценарий использования - это [возвращать Response напрямую, как описано в расширенной документации](../advanced/response-directly.md){.internal-link target=_blank}. + +```Python hl_lines="8 10-11" +{!> ../../../docs_src/response_model/tutorial003_02.py!} +``` + +Это поддерживается FastAPI по-умолчанию, т.к. аннотация проставлена в классе (или подклассе) `Response`. + +И ваши помощники разработки также будут счастливы, т.к. оба класса `RedirectResponse` и `JSONResponse` являются подклассами `Response`. Таким образом мы получаем корректную аннотацию типа. + +### Подкласс Response в аннотации типа + +Вы также можете указать подкласс `Response` в аннотации типа: + +```Python hl_lines="8-9" +{!> ../../../docs_src/response_model/tutorial003_03.py!} +``` + +Это сработает, потому что `RedirectResponse` является подклассом `Response` и FastAPI автоматически обработает этот простейший случай. + +### Некорректные аннотации типов + +Но когда вы возвращаете какой-либо другой произвольный объект, который не является допустимым типом Pydantic (например, объект из базы данных), и вы аннотируете его подобным образом для функции, FastAPI попытается создать из этого типа модель Pydantic и потерпит неудачу. + +То же самое произошло бы, если бы у вас было что-то вроде Union различных типов и один или несколько из них не являлись бы допустимыми типами для Pydantic. Например, такой вариант приведет к ошибке 💥: + +=== "Python 3.10+" + + ```Python hl_lines="8" + {!> ../../../docs_src/response_model/tutorial003_04_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="10" + {!> ../../../docs_src/response_model/tutorial003_04.py!} + ``` + +...такой код вызовет ошибку, потому что в аннотации указан неподдерживаемый Pydantic тип. А также этот тип не является классом или подклассом `Response`. + +### Возможно ли отключить генерацию модели ответа? + +Продолжим рассматривать предыдущий пример. Допустим, что вы хотите отказаться от автоматической валидации ответа, документации, фильтрации и т.д. + +Но в то же время, хотите сохранить аннотацию возвращаемого типа для функции, чтобы обеспечить работу помощников и анализаторов типов (например, mypy). + +В таком случае, вы можете отключить генерацию модели ответа, указав `response_model=None`: + +=== "Python 3.10+" + + ```Python hl_lines="7" + {!> ../../../docs_src/response_model/tutorial003_05_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9" + {!> ../../../docs_src/response_model/tutorial003_05.py!} + ``` + +Тогда FastAPI не станет генерировать модель ответа и вы сможете сохранить такую аннотацию типа, которая вам требуется, никак не влияя на работу FastAPI. 🤓 + +## Параметры модели ответа + +Модель ответа может иметь значения по умолчанию, например: + +=== "Python 3.10+" + + ```Python hl_lines="9 11-12" + {!> ../../../docs_src/response_model/tutorial004_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="11 13-14" + {!> ../../../docs_src/response_model/tutorial004_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="11 13-14" + {!> ../../../docs_src/response_model/tutorial004.py!} + ``` + +* `description: Union[str, None] = None` (или `str | None = None` в Python 3.10), где `None` является значением по умолчанию. +* `tax: float = 10.5`, где `10.5` является значением по умолчанию. +* `tags: List[str] = []`, где пустой список `[]` является значением по умолчанию. + +но вы, возможно, хотели бы исключить их из ответа, если данные поля не были заданы явно. + +Например, у вас есть модель с множеством необязательных полей в NoSQL базе данных, но вы не хотите отправлять в качестве ответа очень длинный JSON с множеством значений по умолчанию. + +### Используйте параметр `response_model_exclude_unset` + +Установите для *декоратора операции пути* параметр `response_model_exclude_unset=True`: + +=== "Python 3.10+" + + ```Python hl_lines="22" + {!> ../../../docs_src/response_model/tutorial004_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="24" + {!> ../../../docs_src/response_model/tutorial004_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="24" + {!> ../../../docs_src/response_model/tutorial004.py!} + ``` + +и тогда значения по умолчанию не будут включены в ответ. В нем будут только те поля, значения которых фактически были установлены. + +Итак, если вы отправите запрос на данную *операцию пути* для элемента, с ID = `Foo` - ответ (с исключенными значениями по-умолчанию) будет таким: + +```JSON +{ + "name": "Foo", + "price": 50.2 +} +``` + +!!! info "Информация" + "Под капотом" FastAPI использует метод `.dict()` у объектов моделей Pydantic с параметром `exclude_unset`, чтобы достичь такого эффекта. + +!!! info "Информация" + Вы также можете использовать: + + * `response_model_exclude_defaults=True` + * `response_model_exclude_none=True` + + как описано в документации Pydantic для параметров `exclude_defaults` и `exclude_none`. + +#### Если значение поля отличается от значения по-умолчанию + +Если для некоторых полей модели, имеющих значения по-умолчанию, значения были явно установлены - как для элемента с ID = `Bar`, ответ будет таким: + +```Python hl_lines="3 5" +{ + "name": "Bar", + "description": "The bartenders", + "price": 62, + "tax": 20.2 +} +``` + +они не будут исключены из ответа. + +#### Если значение поля совпадает с его значением по умолчанию + +Если данные содержат те же значения, которые являются для этих полей по умолчанию, но были установлены явно - как для элемента с ID = `baz`, ответ будет таким: + +```Python hl_lines="3 5-6" +{ + "name": "Baz", + "description": None, + "price": 50.2, + "tax": 10.5, + "tags": [] +} +``` + +FastAPI достаточно умен (на самом деле, это заслуга Pydantic), чтобы понять, что, хотя `description`, `tax` и `tags` хранят такие же данные, какие должны быть по умолчанию - для них эти значения были установлены явно (а не получены из значений по умолчанию). + +И поэтому, они также будут включены в JSON ответа. + +!!! tip "Подсказка" + Значением по умолчанию может быть что угодно, не только `None`. + + Им может быть и список (`[]`), значение 10.5 типа `float`, и т.п. + +### `response_model_include` и `response_model_exclude` + +Вы также можете использовать параметры *декоратора операции пути*, такие, как `response_model_include` и `response_model_exclude`. + +Они принимают аргументы типа `set`, состоящий из строк (`str`) с названиями атрибутов, которые либо требуется включить в ответ (при этом исключив все остальные), либо наоборот исключить (оставив в ответе все остальные поля). + +Это можно использовать как быстрый способ исключить данные из ответа, не создавая отдельную модель Pydantic. + +!!! tip "Подсказка" + Но по-прежнему рекомендуется следовать изложенным выше советам и использовать несколько моделей вместо данных параметров. + + Потому как JSON схема OpenAPI, генерируемая вашим приложением (а также документация) все еще будет содержать все поля, даже если вы использовали `response_model_include` или `response_model_exclude` и исключили некоторые атрибуты. + + То же самое применимо к параметру `response_model_by_alias`. + +=== "Python 3.10+" + + ```Python hl_lines="29 35" + {!> ../../../docs_src/response_model/tutorial005_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="31 37" + {!> ../../../docs_src/response_model/tutorial005.py!} + ``` + +!!! tip "Подсказка" + При помощи кода `{"name","description"}` создается объект множества (`set`) с двумя строковыми значениями. + + Того же самого можно достичь используя `set(["name", "description"])`. + +#### Что если использовать `list` вместо `set`? + +Если вы забыли про `set` и использовали структуру `list` или `tuple`, FastAPI автоматически преобразует этот объект в `set`, чтобы обеспечить корректную работу: + +=== "Python 3.10+" + + ```Python hl_lines="29 35" + {!> ../../../docs_src/response_model/tutorial006_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="31 37" + {!> ../../../docs_src/response_model/tutorial006.py!} + ``` + +## Резюме + +Используйте параметр `response_model` у *декоратора операции пути* для того, чтобы задать модель ответа и в большей степени для того, чтобы быть уверенным, что приватная информация будет отфильтрована. + +А также используйте `response_model_exclude_unset`, чтобы возвращать только те значения, которые были заданы явно. diff --git a/docs/ru/docs/tutorial/schema-extra-example.md b/docs/ru/docs/tutorial/schema-extra-example.md index a0363b9ba7a68..e1011805af539 100644 --- a/docs/ru/docs/tutorial/schema-extra-example.md +++ b/docs/ru/docs/tutorial/schema-extra-example.md @@ -6,7 +6,7 @@ ## Pydantic `schema_extra` -Вы можете объявить ключ `example` для модели Pydantic, используя класс `Config` и переменную `schema_extra`, как описано в Pydantic документации: Настройка схемы: +Вы можете объявить ключ `example` для модели Pydantic, используя класс `Config` и переменную `schema_extra`, как описано в Pydantic документации: Настройка схемы: === "Python 3.10+" @@ -14,7 +14,7 @@ {!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="15-23" {!> ../../../docs_src/schema_extra_example/tutorial001.py!} @@ -39,7 +39,7 @@ {!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="4 10-13" {!> ../../../docs_src/schema_extra_example/tutorial002.py!} @@ -78,7 +78,7 @@ {!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="23-28" {!> ../../../docs_src/schema_extra_example/tutorial003_an.py!} @@ -93,7 +93,7 @@ {!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Заметка Рекомендуется использовать версию с `Annotated`, если это возможно. @@ -133,7 +133,7 @@ {!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="24-50" {!> ../../../docs_src/schema_extra_example/tutorial004_an.py!} @@ -148,7 +148,7 @@ {!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Заметка Рекомендуется использовать версию с `Annotated`, если это возможно. diff --git a/docs/ru/docs/tutorial/security/first-steps.md b/docs/ru/docs/tutorial/security/first-steps.md new file mode 100644 index 0000000000000..fdeccc01ad0ae --- /dev/null +++ b/docs/ru/docs/tutorial/security/first-steps.md @@ -0,0 +1,232 @@ +# Безопасность - первые шаги + +Представим, что у вас есть свой **бэкенд** API на некотором домене. + +И у вас есть **фронтенд** на другом домене или на другом пути того же домена (или в мобильном приложении). + +И вы хотите иметь возможность аутентификации фронтенда с бэкендом, используя **имя пользователя** и **пароль**. + +Мы можем использовать **OAuth2** для создания такой системы с помощью **FastAPI**. + +Но давайте избавим вас от необходимости читать всю длинную спецификацию, чтобы найти те небольшие кусочки информации, которые вам нужны. + +Для работы с безопасностью воспользуемся средствами, предоставленными **FastAPI**. + +## Как это выглядит + +Давайте сначала просто воспользуемся кодом и посмотрим, как он работает, а затем детально разберём, что происходит. + +## Создание `main.py` + +Скопируйте пример в файл `main.py`: + +=== "Python 3.9+" + + ```Python + {!> ../../../docs_src/security/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python + {!> ../../../docs_src/security/tutorial001_an.py!} + ``` + +=== "Python 3.8+ без Annotated" + + !!! tip "Подсказка" + Предпочтительнее использовать версию с аннотацией, если это возможно. + + ```Python + {!> ../../../docs_src/security/tutorial001.py!} + ``` + + +## Запуск + +!!! info "Дополнительная информация" + Вначале, установите библиотеку `python-multipart`. + + А именно: `pip install python-multipart`. + + Это связано с тем, что **OAuth2** использует "данные формы" для передачи `имени пользователя` и `пароля`. + +Запустите ваш сервер: + +
+ +```console +$ uvicorn main:app --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +## Проверка + +Перейдите к интерактивной документации по адресу: http://127.0.0.1:8000/docs. + +Вы увидите примерно следующее: + + + +!!! check "Кнопка авторизации!" + У вас уже появилась новая кнопка "Authorize". + + А у *операции пути* теперь появился маленький замочек в правом верхнем углу, на который можно нажать. + +При нажатии на нее появляется небольшая форма авторизации, в которую нужно ввести `имя пользователя` и `пароль` (и другие необязательные поля): + + + +!!! note "Технические детали" + Неважно, что вы введете в форму, она пока не будет работать. Но мы к этому еще придем. + +Конечно, это не фронтенд для конечных пользователей, но это отличный автоматический инструмент для интерактивного документирования всех ваших API. + +Он может использоваться командой фронтенда (которой можете быть и вы сами). + +Он может быть использован сторонними приложениями и системами. + +Кроме того, его можно использовать самостоятельно для отладки, проверки и тестирования одного и того же приложения. + +## Аутентификация по паролю + +Теперь давайте вернемся немного назад и разберемся, что же это такое. + +Аутентификация по паролю является одним из способов, определенных в OAuth2, для обеспечения безопасности и аутентификации. + +OAuth2 был разработан для того, чтобы бэкэнд или API были независимы от сервера, который аутентифицирует пользователя. + +Но в нашем случае одно и то же приложение **FastAPI** будет работать с API и аутентификацией. + +Итак, рассмотрим его с этой упрощенной точки зрения: + +* Пользователь вводит на фронтенде `имя пользователя` и `пароль` и нажимает `Enter`. +* Фронтенд (работающий в браузере пользователя) отправляет эти `имя пользователя` и `пароль` на определенный URL в нашем API (объявленный с помощью параметра `tokenUrl="token"`). +* API проверяет эти `имя пользователя` и `пароль` и выдает в ответ "токен" (мы еще не реализовали ничего из этого). + * "Токен" - это просто строка с некоторым содержимым, которое мы можем использовать позже для верификации пользователя. + * Обычно срок действия токена истекает через некоторое время. + * Таким образом, пользователю придется снова войти в систему в какой-то момент времени. + * И если токен будет украден, то риск будет меньше, так как он не похож на постоянный ключ, который будет работать вечно (в большинстве случаев). +* Фронтенд временно хранит этот токен в каком-то месте. +* Пользователь щелкает мышью на фронтенде, чтобы перейти в другой раздел на фронтенде. +* Фронтенду необходимо получить дополнительные данные из API. + * Но для этого необходима аутентификация для конкретной конечной точки. + * Поэтому для аутентификации в нашем API он посылает заголовок `Authorization` со значением `Bearer` плюс сам токен. + * Если токен содержит `foobar`, то содержание заголовка `Authorization` будет таким: `Bearer foobar`. + +## Класс `OAuth2PasswordBearer` в **FastAPI** + +**FastAPI** предоставляет несколько средств на разных уровнях абстракции для реализации этих функций безопасности. + +В данном примере мы будем использовать **OAuth2**, с аутентификацией по паролю, используя токен **Bearer**. Для этого мы используем класс `OAuth2PasswordBearer`. + +!!! info "Дополнительная информация" + Токен "bearer" - не единственный вариант, но для нашего случая он является наилучшим. + + И это может быть лучшим вариантом для большинства случаев использования, если только вы не являетесь экспертом в области OAuth2 и точно знаете, почему вам лучше подходит какой-то другой вариант. + + В этом случае **FastAPI** также предоставляет инструменты для его реализации. + +При создании экземпляра класса `OAuth2PasswordBearer` мы передаем в него параметр `tokenUrl`. Этот параметр содержит URL, который клиент (фронтенд, работающий в браузере пользователя) будет использовать для отправки `имени пользователя` и `пароля` с целью получения токена. + +=== "Python 3.9+" + + ```Python hl_lines="8" + {!> ../../../docs_src/security/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="7" + {!> ../../../docs_src/security/tutorial001_an.py!} + ``` + +=== "Python 3.8+ без Annotated" + + !!! tip "Подсказка" + Предпочтительнее использовать версию с аннотацией, если это возможно. + + ```Python hl_lines="6" + {!> ../../../docs_src/security/tutorial001.py!} + ``` + +!!! tip "Подсказка" + Здесь `tokenUrl="token"` ссылается на относительный URL `token`, который мы еще не создали. Поскольку это относительный URL, он эквивалентен `./token`. + + Поскольку мы используем относительный URL, если ваш API расположен по адресу `https://example.com/`, то он будет ссылаться на `https://example.com/token`. Если же ваш API расположен по адресу `https://example.com/api/v1/`, то он будет ссылаться на `https://example.com/api/v1/token`. + + Использование относительного URL важно для того, чтобы ваше приложение продолжало работать даже в таких сложных случаях, как оно находится [за прокси-сервером](../../advanced/behind-a-proxy.md){.internal-link target=_blank}. + +Этот параметр не создает конечную точку / *операцию пути*, а объявляет, что URL `/token` будет таким, который клиент должен использовать для получения токена. Эта информация используется в OpenAPI, а затем в интерактивных системах документации API. + +Вскоре мы создадим и саму операцию пути. + +!!! info "Дополнительная информация" + Если вы очень строгий "питонист", то вам может не понравиться стиль названия параметра `tokenUrl` вместо `token_url`. + + Это связано с тем, что тут используется то же имя, что и в спецификации OpenAPI. Таким образом, если вам необходимо более подробно изучить какую-либо из этих схем безопасности, вы можете просто использовать копирование/вставку, чтобы найти дополнительную информацию о ней. + +Переменная `oauth2_scheme` является экземпляром `OAuth2PasswordBearer`, но она также является "вызываемой". + +Ее можно вызвать следующим образом: + +```Python +oauth2_scheme(some, parameters) +``` + +Поэтому ее можно использовать вместе с `Depends`. + +### Использование + +Теперь вы можете передать ваш `oauth2_scheme` в зависимость с помощью `Depends`. + +=== "Python 3.9+" + + ```Python hl_lines="12" + {!> ../../../docs_src/security/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="11" + {!> ../../../docs_src/security/tutorial001_an.py!} + ``` + +=== "Python 3.8+ без Annotated" + + !!! tip "Подсказка" + Предпочтительнее использовать версию с аннотацией, если это возможно. + + ```Python hl_lines="10" + {!> ../../../docs_src/security/tutorial001.py!} + ``` + +Эта зависимость будет предоставлять `строку`, которая присваивается параметру `token` в *функции операции пути*. + +**FastAPI** будет знать, что он может использовать эту зависимость для определения "схемы безопасности" в схеме OpenAPI (и автоматической документации по API). + +!!! info "Технические детали" + **FastAPI** будет знать, что он может использовать класс `OAuth2PasswordBearer` (объявленный в зависимости) для определения схемы безопасности в OpenAPI, поскольку он наследуется от `fastapi.security.oauth2.OAuth2`, который, в свою очередь, наследуется от `fastapi.security.base.SecurityBase`. + + Все утилиты безопасности, интегрируемые в OpenAPI (и автоматическая документация по API), наследуются от `SecurityBase`, поэтому **FastAPI** может знать, как интегрировать их в OpenAPI. + +## Что он делает + +Он будет искать в запросе заголовок `Authorization` и проверять, содержит ли он значение `Bearer` с некоторым токеном, и возвращать токен в виде `строки`. + +Если он не видит заголовка `Authorization` или значение не имеет токена `Bearer`, то в ответ будет выдана ошибка с кодом состояния 401 (`UNAUTHORIZED`). + +Для возврата ошибки даже не нужно проверять, существует ли токен. Вы можете быть уверены, что если ваша функция будет выполнилась, то в этом токене есть `строка`. + +Проверить это можно уже сейчас в интерактивной документации: + + + +Мы пока не проверяем валидность токена, но для начала неплохо. + +## Резюме + +Таким образом, всего за 3-4 дополнительные строки вы получаете некую примитивную форму защиты. diff --git a/docs/ru/docs/tutorial/security/index.md b/docs/ru/docs/tutorial/security/index.md new file mode 100644 index 0000000000000..d5fe4e76f8940 --- /dev/null +++ b/docs/ru/docs/tutorial/security/index.md @@ -0,0 +1,101 @@ +# Настройка авторизации + +Существует множество способов обеспечения безопасности, аутентификации и авторизации. + +Обычно эта тема является достаточно сложной и трудной. + +Во многих фреймворках и системах только работа с определением доступов к приложению и аутентификацией требует значительных затрат усилий и написания множества кода (во многих случаях его объём может составлять более 50% от всего написанного кода). + +**FastAPI** предоставляет несколько инструментов, которые помогут вам настроить **Авторизацию** легко, быстро, стандартным способом, без необходимости изучать все её тонкости. + +Но сначала давайте рассмотрим некоторые небольшие концепции. + +## Куда-то торопишься? + +Если вам не нужна информация о каких-либо из следующих терминов и вам просто нужно добавить защиту с аутентификацией на основе логина и пароля *прямо сейчас*, переходите к следующим главам. + +## OAuth2 + +OAuth2 - это протокол, который определяет несколько способов обработки аутентификации и авторизации. + +Он довольно обширен и охватывает несколько сложных вариантов использования. + +OAuth2 включает в себя способы аутентификации с использованием "третьей стороны". + +Это то, что используют под собой все кнопки "вход с помощью Facebook, Google, Twitter, GitHub" на страницах авторизации. + +### OAuth 1 + +Ранее использовался протокол OAuth 1, который сильно отличается от OAuth2 и является более сложным, поскольку он включал прямые описания того, как шифровать сообщение. + +В настоящее время он не очень популярен и не используется. + +OAuth2 не указывает, как шифровать сообщение, он ожидает, что ваше приложение будет обслуживаться по протоколу HTTPS. + +!!! tip "Подсказка" + В разделе **Развертывание** вы увидите [как настроить протокол HTTPS бесплатно, используя Traefik и Let's Encrypt.](https://fastapi.tiangolo.com/ru/deployment/https/) + + +## OpenID Connect + +OpenID Connect - это еще один протокол, основанный на **OAuth2**. + +Он просто расширяет OAuth2, уточняя некоторые вещи, не имеющие однозначного определения в OAuth2, в попытке сделать его более совместимым. + +Например, для входа в Google используется OpenID Connect (который под собой использует OAuth2). + +Но вход в Facebook не поддерживает OpenID Connect. У него есть собственная вариация OAuth2. + +### OpenID (не "OpenID Connect") + +Также ранее использовался стандарт "OpenID", который пытался решить ту же проблему, что и **OpenID Connect**, но не был основан на OAuth2. + +Таким образом, это была полноценная дополнительная система. + +В настоящее время не очень популярен и не используется. + +## OpenAPI + +OpenAPI (ранее известный как Swagger) - это открытая спецификация для создания API (в настоящее время является частью Linux Foundation). + +**FastAPI** основан на **OpenAPI**. + +Это то, что делает возможным наличие множества автоматических интерактивных интерфейсов документирования, сгенерированного кода и т.д. + +В OpenAPI есть способ использовать несколько "схем" безопасности. + +Таким образом, вы можете воспользоваться преимуществами Всех этих стандартных инструментов, включая интерактивные системы документирования. + +OpenAPI может использовать следующие схемы авторизации: + +* `apiKey`: уникальный идентификатор для приложения, который может быть получен из: + * Параметров запроса. + * Заголовка. + * Cookies. +* `http`: стандартные системы аутентификации по протоколу HTTP, включая: + * `bearer`: заголовок `Authorization` со значением `Bearer {уникальный токен}`. Это унаследовано от OAuth2. + * Базовая аутентификация по протоколу HTTP. + * HTTP Digest и т.д. +* `oauth2`: все способы обеспечения безопасности OAuth2 называемые "потоки" (англ. "flows"). + * Некоторые из этих "потоков" подходят для реализации аутентификации через сторонний сервис использующий OAuth 2.0 (например, Google, Facebook, Twitter, GitHub и т.д.): + * `implicit` + * `clientCredentials` + * `authorizationCode` + * Но есть один конкретный "поток", который может быть идеально использован для обработки аутентификации непосредственно в том же приложении: + * `password`: в некоторых следующих главах будут рассмотрены примеры этого. +* `openIdConnect`: способ определить, как автоматически обнаруживать данные аутентификации OAuth2. + * Это автоматическое обнаружение определено в спецификации OpenID Connect. + + +!!! tip "Подсказка" + Интеграция сторонних сервисов для аутентификации/авторизации таких как Google, Facebook, Twitter, GitHub и т.д. осуществляется достаточно легко. + + Самой сложной проблемой является создание такого провайдера аутентификации/авторизации, но **FastAPI** предоставляет вам инструменты, позволяющие легко это сделать, выполняя при этом всю тяжелую работу за вас. + +## Преимущества **FastAPI** + +Fast API предоставляет несколько инструментов для каждой из этих схем безопасности в модуле `fastapi.security`, которые упрощают использование этих механизмов безопасности. + +В следующих главах вы увидите, как обезопасить свой API, используя инструменты, предоставляемые **FastAPI**. + +И вы также увидите, как он автоматически интегрируется в систему интерактивной документации. diff --git a/docs/ru/docs/tutorial/testing.md b/docs/ru/docs/tutorial/testing.md index 3f9005112390c..ca47a6f51e0bd 100644 --- a/docs/ru/docs/tutorial/testing.md +++ b/docs/ru/docs/tutorial/testing.md @@ -122,7 +122,7 @@ {!> ../../../docs_src/app_testing/app_b_an_py39/main.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python {!> ../../../docs_src/app_testing/app_b_an/main.py!} @@ -137,7 +137,7 @@ {!> ../../../docs_src/app_testing/app_b_py310/main.py!} ``` -=== "Python 3.6+ без Annotated" +=== "Python 3.8+ без Annotated" !!! tip "Подсказка" По возможности используйте версию с `Annotated`. diff --git a/docs/tr/docs/about/index.md b/docs/tr/docs/about/index.md new file mode 100644 index 0000000000000..e9dee5217cbb4 --- /dev/null +++ b/docs/tr/docs/about/index.md @@ -0,0 +1,3 @@ +# Hakkında + +FastAPI, tasarımı, ilham kaynağı ve daha fazlası hakkında. 🤓 diff --git a/docs/tr/docs/alternatives.md b/docs/tr/docs/alternatives.md new file mode 100644 index 0000000000000..462d8b3046774 --- /dev/null +++ b/docs/tr/docs/alternatives.md @@ -0,0 +1,409 @@ +# Alternatifler, İlham Kaynakları ve Karşılaştırmalar + +**FastAPI**'ya neler ilham verdi? Diğer alternatiflerle karşılaştırıldığında farkları neler? **FastAPI** diğer alternatiflerinden neler öğrendi? + +## Giriş + +Başkalarının daha önceki çalışmaları olmasaydı, **FastAPI** var olmazdı. + +Geçmişte oluşturulan pek çok araç **FastAPI**'a ilham kaynağı olmuştur. + +Yıllardır yeni bir framework oluşturmaktan kaçınıyordum. Başlangıçta **FastAPI**'ın çözdüğü sorunları çözebilmek için pek çok farklı framework, eklenti ve araç kullanmayı denedim. + +Ancak bir noktada, geçmişteki diğer araçlardan en iyi fikirleri alarak bütün bu çözümleri kapsayan, ayrıca bütün bunları Python'ın daha önce mevcut olmayan özelliklerini (Python 3.6+ ile gelen tip belirteçleri) kullanarak yapan bir şey üretmekten başka seçenek kalmamıştı. + +## Daha Önce Geliştirilen Araçlar + +### Django + +Django geniş çapta güvenilen, Python ekosistemindeki en popüler web framework'üdür. Instagram gibi sistemleri geliştirmede kullanılmıştır. + +MySQL ve PostgreSQL gibi ilişkisel veritabanlarıyla nispeten sıkı bir şekilde bağlantılıdır. Bu nedenle Couchbase, MongoDB ve Cassandra gibi NoSQL veritabanlarını ana veritabanı motoru olarak kullanmak pek de kolay değil. + +Modern ön uçlarda (React, Vue.js ve Angular gibi) veya diğer sistemler (örneğin nesnelerin interneti cihazları) tarafından kullanılan API'lar yerine arka uçta HTML üretmek için oluşturuldu. + +### Django REST Framework + +Django REST framework'ü, Django'nun API kabiliyetlerini arttırmak için arka planda Django kullanan esnek bir araç grubu olarak oluşturuldu. + +Üstelik Mozilla, Red Hat ve Eventbrite gibi pek çok şirket tarafından kullanılıyor. + +**Otomatik API dökümantasyonu**nun ilk örneklerinden biri olduğu için, **FastAPI** arayışına ilham veren ilk fikirlerden biri oldu. + +!!! note "Not" + Django REST Framework'ü, aynı zamanda **FastAPI**'ın dayandığı Starlette ve Uvicorn'un da yaratıcısı olan Tom Christie tarafından geliştirildi. + +!!! check "**FastAPI**'a nasıl ilham verdi?" + Kullanıcılar için otomatik API dökümantasyonu sunan bir web arayüzüne sahip olmalı. + +### Flask + +Flask bir mikro framework olduğundan Django gibi framework'lerin aksine veritabanı entegrasyonu gibi Django ile gelen pek çok özelliği direkt barındırmaz. + +Sağladığı basitlik ve esneklik NoSQL veritabanlarını ana veritabanı sistemi olarak kullanmak gibi şeyler yapmaya olanak sağlar. + +Yapısı oldukça basit olduğundan öğrenmesi de nispeten basittir, tabii dökümantasyonu bazı noktalarda biraz teknik hale geliyor. + +Ayrıca Django ile birlikte gelen veritabanı, kullanıcı yönetimi ve diğer pek çok özelliğe ihtiyaç duymayan uygulamalarda da yaygın olarak kullanılıyor. Ancak bu tür özelliklerin pek çoğu eklentiler ile eklenebiliyor. + +Uygulama parçalarının böyle ayrılıyor oluşu ve istenilen özelliklerle genişletilebilecek bir mikro framework olmak tam da benim istediğim bir özellikti. + +Flask'ın basitliği göz önünde bulundurulduğu zaman, API geliştirmek için iyi bir seçim gibi görünüyordu. Sıradaki şey ise Flask için bir "Django REST Framework"! + +!!! check "**FastAPI**'a nasıl ilham verdi?" + Gereken araçları ve parçaları birleştirip eşleştirmeyi kolaylaştıracak bir mikro framework olmalı. + + Basit ve kullanması kolay bir yönlendirme sistemine sahip olmalı. + +### Requests + +**FastAPI** aslında **Requests**'in bir alternatifi değil. İkisininde kapsamı oldukça farklı. + +Aslında Requests'i bir FastAPI uygulamasının *içinde* kullanmak daha olağan olurdu. + +Ama yine de, FastAPI, Requests'ten oldukça ilham aldı. + +**Requests**, API'lar ile bir istemci olarak *etkileşime geçmeyi* sağlayan bir kütüphaneyken **FastAPI** bir sunucu olarak API'lar oluşturmaya yarar. + +Öyle ya da böyle zıt uçlarda olmalarına rağmen birbirlerini tamamlıyorlar. + +Requests oldukça basit ve sezgisel bir tasarıma sahip, kullanması da mantıklı varsayılan değerlerle oldukça kolay. Ama aynı zamanda çok güçlü ve gayet özelleştirilebilir. + +Bu yüzden resmi web sitede de söylendiği gibi: + +> Requests, tüm zamanların en çok indirilen Python paketlerinden biridir. + +Kullanım şekli oldukça basit. Örneğin bir `GET` isteği yapmak için aşağıdaki yeterli: + +```Python +response = requests.get("http://example.com/some/url") +``` + +Bunun FastAPI'deki API *yol işlemi* şöyle görünür: + +```Python hl_lines="1" +@app.get("/some/url") +def read_url(): + return {"message": "Hello World!"} +``` + +`requests.get(...)` ile `@app.get(...)` arasındaki benzerliklere bakın. + +!!! check "**FastAPI**'a nasıl ilham verdi?" + * Basit ve sezgisel bir API'ya sahip olmalı. + * HTTP metot isimlerini (işlemlerini) anlaşılır olacak bir şekilde, direkt kullanmalı. + * Mantıklı varsayılan değerlere ve buna rağmen güçlü bir özelleştirme desteğine sahip olmalı. + +### Swagger / OpenAPI + +Benim Django REST Framework'ünden istediğim ana özellik otomatik API dökümantasyonuydu. + +Daha sonra API'ları dökümanlamak için Swagger adında JSON (veya JSON'un bir uzantısı olan YAML'ı) kullanan bir standart olduğunu buldum. + +Üstelik Swagger API'ları için zaten halihazırda oluşturulmuş bir web arayüzü vardı. Yani, bir API için Swagger dökümantasyonu oluşturmak bu arayüzü otomatik olarak kullanabilmek demekti. + +Swagger bir noktada Linux Foundation'a verildi ve adı OpenAPI olarak değiştirildi. + +İşte bu yüzden versiyon 2.0 hakkında konuşurken "Swagger", versiyon 3 ve üzeri için ise "OpenAPI" adını kullanmak daha yaygın. + +!!! check "**FastAPI**'a nasıl ilham verdi?" + API spesifikasyonları için özel bir şema yerine bir açık standart benimseyip kullanmalı. + + Ayrıca standarda bağlı kullanıcı arayüzü araçlarını entegre etmeli: + + * Swagger UI + * ReDoc + + Yukarıdaki ikisi oldukça popüler ve istikrarlı olduğu için seçildi, ancak hızlı bir araştırma yaparak **FastAPI** ile kullanabileceğiniz pek çok OpenAPI alternatifi arayüz bulabilirsiniz. + +### Flask REST framework'leri + +Pek çok Flask REST framework'ü var, fakat bunları biraz araştırdıktan sonra pek çoğunun artık geliştirilmediğini ve göze batan bazı sorunlarının olduğunu gördüm. + +### Marshmallow + +API sistemlerine gereken ana özelliklerden biri de koddan veriyi alıp ağ üzerinde gönderilebilecek bir şeye çevirmek, yani veri dönüşümü. Bu işleme veritabanındaki veriyi içeren bir objeyi JSON objesine çevirmek, `datetime` objelerini metinlere çevirmek gibi örnekler verilebilir. + +API'lara gereken bir diğer büyük özellik ise veri doğrulamadır, yani verinin çeşitli parametrelere bağlı olarak doğru ve tutarlı olduğundan emin olmaktır. Örneğin bir alanın `int` olmasına karar verdiniz, daha sonra rastgele bir metin değeri almasını istemezsiniz. Bu özellikle sisteme dışarıdan gelen veri için kullanışlı bir özellik oluyor. + +Bir veri doğrulama sistemi olmazsa bütün bu kontrolleri koda dökerek kendiniz yapmak zorunda kalırdınız. + +Marshmallow bu özellikleri sağlamak için geliştirilmişti. Benim de geçmişte oldukça sık kullandığım harika bir kütüphanedir. + +Ama... Python'un tip belirteçleri gelmeden önce oluşturulmuştu. Yani her şemayı tanımlamak için Marshmallow'un sunduğu spesifik araçları ve sınıfları kullanmanız gerekiyordu. + +!!! check "**FastAPI**'a nasıl ilham verdi?" + Kod kullanarak otomatik olarak veri tipini ve veri doğrulamayı belirten "şemalar" tanımlamalı. + +### Webargs + +API'ların ihtiyacı olan bir diğer önemli özellik ise gelen isteklerdeki verileri Python objelerine ayrıştırabilmektir. + +Webargs, Flask gibi bir kaç framework'ün üzerinde bunu sağlamak için geliştirilen bir araçtır. + +Veri doğrulama için arka planda Marshmallow kullanıyor, hatta aynı geliştiriciler tarafından oluşturuldu. + +Webargs da harika bir araç ve onu da geçmişte henüz **FastAPI** yokken çok kullandım. + +!!! info "Bilgi" + Webargs aynı Marshmallow geliştirileri tarafından oluşturuldu. + +!!! check "**FastAPI**'a nasıl ilham verdi?" + Gelen istek verisi için otomatik veri doğrulamaya sahip olmalı. + +### APISpec + +Marshmallow ve Webargs eklentiler olarak; veri doğrulama, ayrıştırma ve dönüştürmeyi sağlıyor. + +Ancak dökümantasyondan hala ses seda yok. Daha sonrasında ise APISpec geldi. + +APISpec pek çok framework için bir eklenti olarak kullanılıyor (Starlette için de bir eklentisi var). + +Şemanın tanımını yol'a istek geldiğinde çalışan her bir fonksiyonun döküman dizesinin içine YAML formatında olacak şekilde yazıyorsunuz o da OpenAPI şemaları üretiyor. + +Flask, Starlette, Responder ve benzerlerinde bu şekilde çalışıyor. + +Fakat sonrasında yine mikro sözdizimi problemiyle karşılaşıyoruz. Python metinlerinin içinde koskoca bir YAML oluyor. + +Editör bu konuda pek yardımcı olamaz. Üstelik eğer parametreleri ya da Marshmallow şemalarını değiştirip YAML kodunu güncellemeyi unutursak artık döküman geçerliliğini yitiriyor. + +!!! info "Bilgi" + APISpec de aynı Marshmallow geliştiricileri tarafından oluşturuldu. + +!!! check "**FastAPI**'a nasıl ilham verdi?" + API'lar için açık standart desteği olmalı (OpenAPI gibi). + +### Flask-apispec + +Flask-apispec ise Webargs, Marshmallow ve APISpec'i birbirine bağlayan bir Flask eklentisi. + +Webargs ve Marshmallow'daki bilgiyi APISpec ile otomatik OpenAPI şemaları üretmek için kullanıyor. + +Hak ettiği değeri görmeyen, harika bir araç. Piyasadaki çoğu Flask eklentisinden çok daha popüler olmalı. Hak ettiği değeri görmüyor oluşunun sebebi ise dökümantasyonun çok kısa ve soyut olması olabilir. + +Böylece Flask-apispec, Python döküman dizilerine YAML gibi farklı bir syntax yazma sorununu çözmüş oldu. + +**FastAPI**'ı geliştirene dek benim favori arka uç kombinasyonum Flask'in yanında Marshmallow ve Webargs ile birlikte Flask-apispec idi. + +Bunu kullanmak, bir kaç full-stack Flask projesi oluşturucusunun yaratılmasına yol açtı. Bunlar benim (ve bir kaç harici ekibin de) şimdiye kadar kullandığı asıl stackler: + +* https://github.com/tiangolo/full-stack +* https://github.com/tiangolo/full-stack-flask-couchbase +* https://github.com/tiangolo/full-stack-flask-couchdb + +Aynı full-stack üreticiler [**FastAPI** Proje Üreticileri](project-generation.md){.internal-link target=_blank}'nin de temelini oluşturdu. + +!!! info "Bilgi" + Flask-apispec de aynı Marshmallow geliştiricileri tarafından üretildi. + +!!! check "**FastAPI**'a nasıl ilham oldu?" + Veri dönüşümü ve veri doğrulamayı tanımlayan kodu kullanarak otomatik olarak OpenAPI şeması oluşturmalı. + +### NestJS (and Angular) + +Bu Python teknolojisi bile değil. NestJS, Angulardan ilham almış olan bir JavaScript (TypeScript) NodeJS framework'ü. + +Flask-apispec ile yapılabileceklere nispeten benzeyen bir şey elde ediyor. + +Angular 2'den ilham alan, içine gömülü bir bağımlılık enjeksiyonu sistemi var. Bildiğim diğer tüm bağımlılık enjeksiyonu sistemlerinde olduğu gibi"bağımlılık"ları önceden kaydetmenizi gerektiriyor. Böylece projeyi daha detaylı hale getiriyor ve kod tekrarını da arttırıyor. + +Parametreler TypeScript tipleri (Python tip belirteçlerine benzer) ile açıklandığından editör desteği oldukça iyi. + +Ama TypeScript verileri kod JavaScript'e derlendikten sonra korunmadığından, bunlara dayanarak aynı anda veri doğrulaması, veri dönüşümü ve dökümantasyon tanımlanamıyor. Bundan ve bazı tasarım tercihlerinden dolayı veri doğrulaması, dönüşümü ve otomatik şema üretimi için pek çok yere dekorator eklemek gerekiyor. Bu da projeyi oldukça detaylandırıyor. + +İç içe geçen derin modelleri pek iyi işleyemiyor. Yani eğer istekteki JSON gövdesi derin bir JSON objesiyse düzgün bir şekilde dökümante edilip doğrulanamıyor. + +!!! check "**FastAPI**'a nasıl ilham oldu?" + Güzel bir editör desteği için Python tiplerini kullanmalı. + + Güçlü bir bağımlılık enjeksiyon sistemine sahip olmalı. Kod tekrarını minimuma indirecek bir yol bulmalı. + +### Sanic + +Sanic, `asyncio`'ya dayanan son derece hızlı Python kütüphanelerinden biriydi. Flask'a epey benzeyecek şekilde geliştirilmişti. + +!!! note "Teknik detaylar" + İçerisinde standart Python `asyncio` döngüsü yerine `uvloop` kullanıldı. Hızının asıl kaynağı buydu. + + Uvicorn ve Starlette'e ilham kaynağı olduğu oldukça açık, şu anda ikisi de açık karşılaştırmalarda Sanicten daha hızlı gözüküyor. + +!!! check "**FastAPI**'a nasıl ilham oldu?" + Uçuk performans sağlayacak bir yol bulmalı. + + Tam da bu yüzden **FastAPI** Starlette'e dayanıyor, çünkü Starlette şu anda kullanılabilir en hızlı framework. (üçüncü parti karşılaştırmalı testlerine göre) + +### Falcon + +Falcon ise bir diğer yüksek performanslı Python framework'ü. Minimal olacak şekilde Hug gibi diğer framework'lerin temeli olabilmek için tasarlandı. + +İki parametre kabul eden fonksiyonlar şeklinde tasarlandı, biri "istek" ve diğeri ise "cevap". Sonra isteğin çeşitli kısımlarını **okuyor**, cevaba ise bir şeyler **yazıyorsunuz**. Bu tasarımdan dolayı istek parametrelerini ve gövdelerini standart Python tip belirteçlerini kullanarak fonksiyon parametreleriyle belirtmek mümkün değil. + +Yani veri doğrulama, veri dönüştürme ve dökümantasyonun hepsi kodda yer almalı, otomatik halledemiyoruz. Ya da Falcon üzerine bir framework olarak uygulanmaları gerekiyor, aynı Hug'da olduğu gibi. Bu ayrım Falcon'un tasarımından esinlenen, istek ve cevap objelerini parametre olarak işleyen diğer kütüphanelerde de yer alıyor. + +!!! check "**FastAPI**'a nasıl ilham oldu?" + Harika bir performans'a sahip olmanın yollarını bulmalı. + + Hug ile birlikte (Hug zaten Falcon'a dayandığından) **FastAPI**'ın fonksiyonlarda `cevap` parametresi belirtmesinde ilham kaynağı oldu. + + FastAPI'da opsiyonel olmasına rağmen, daha çok header'lar, çerezler ve alternatif durum kodları belirlemede kullanılıyor. + +### Molten + +**FastAPI**'ı geliştirmenin ilk aşamalarında Molten'ı keşfettim. Pek çok ortak fikrimiz vardı: + +* Python'daki tip belirteçlerini baz alıyordu. +* Bunlara bağlı olarak veri doğrulaması ve dökümantasyon sağlıyordu. +* Bir bağımlılık enjeksiyonu sistemi vardı. + +Veri doğrulama, veri dönüştürme ve dökümantasyon için Pydantic gibi bir üçüncü parti kütüphane kullanmıyor, kendi içerisinde bunlara sahip. Yani bu veri tipi tanımlarını tekrar kullanmak pek de kolay değil. + +Biraz daha detaylı ayarlamalara gerek duyuyor. Ayrıca ASGI yerine WSGI'a dayanıyor. Yani Uvicorn, Starlette ve Sanic gibi araçların yüksek performansından faydalanacak şekilde tasarlanmamış. + +Bağımlılık enjeksiyonu sistemi bağımlılıkların önceden kaydedilmesini ve sonrasında belirlenen veri tiplerine göre çözülmesini gerektiriyor. Yani spesifik bir tip, birden fazla bileşen ile belirlenemiyor. + +Yol'lar fonksiyonun üstünde endpoint'i işleyen dekoratörler yerine farklı yerlerde tanımlanan fonksiyonlarla belirlenir. Bu Flask (ve Starlette) yerine daha çok Django'nun yaklaşımına daha yakın bir metot. Bu, kodda nispeten birbiriyle sıkı ilişkili olan şeyleri ayırmaya sebep oluyor. + +!!! check "**FastAPI**'a nasıl ilham oldu?" + Model özelliklerinin "standart" değerlerini kullanarak veri tipleri için ekstra veri doğrulama koşulları tanımlamalı. Bu editör desteğini geliştiriyor ve daha önceden Pydantic'te yoktu. + + Bu aslında Pydantic'in de aynı doğrulama stiline geçmesinde ilham kaynağı oldu. Şu anda bütün bu özellikler Pydantic'in yapısında yer alıyor. + +### Hug + +Hug, Python tip belirteçlerini kullanarak API parametrelerinin tipini belirlemeyi uygulayan ilk framework'lerdendi. Bu, diğer araçlara da ilham kaynağı olan harika bir fikirdi. + +Tip belirlerken standart Python veri tipleri yerine kendi özel tiplerini kullandı, yine de bu ileriye dönük devasa bir adımdı. + +Hug ayrıca tüm API'ı JSON ile ifade eden özel bir şema oluşturan ilk framework'lerdendir. + +OpenAPI veya JSON Şeması gibi bir standarda bağlı değildi. Yani Swagger UI gibi diğer araçlarla entegre etmek kolay olmazdı. Ama yine de, bu oldukça yenilikçi bir fikirdi. + +Ayrıca ilginç ve çok rastlanmayan bir özelliği vardı: aynı framework'ü kullanarak hem API'lar hem de CLI'lar oluşturmak mümkündü. + +Senkron çalışan Python web framework'lerinin standardına (WSGI) dayandığından dolayı Websocket'leri ve diğer şeyleri işleyemiyor, ancak yine de yüksek performansa sahip. + +!!! info "Bilgi" + Hug, Python dosyalarında bulunan dahil etme satırlarını otomatik olarak sıralayan harika bir araç olan `isort`'un geliştiricisi Timothy Crosley tarafından geliştirildi. + +!!! check "**FastAPI**'a nasıl ilham oldu?" + Hug, APIStar'ın çeşitli kısımlarında esin kaynağı oldu ve APIStar'la birlikte en umut verici bulduğum araçlardan biriydi. + + **FastAPI**, Python tip belirteçlerini kullanarak parametre belirlemede ve API'ı otomatık tanımlayan bir şema üretmede de Hug'a esinlendi. + + **FastAPI**'ın header ve çerez tanımlamak için fonksiyonlarda `response` parametresini belirtmesinde de Hug'dan ilham alındı. + +### APIStar (<= 0.5) + +**FastAPI**'ı geliştirmeye başlamadan hemen önce **APIStar** sunucusunu buldum. Benim aradığım şeylerin neredeyse hepsine sahipti ve harika bir tasarımı vardı. + +Benim şimdiye kadar gördüğüm Python tip belirteçlerini kullanarak parametre ve istekler belirlemeyi uygulayan ilk framework'lerdendi (Molten ve NestJS'den önce). APIStar'ı da aşağı yukarı Hug ile aynı zamanlarda buldum. Fakat APIStar OpenAPI standardını kullanıyordu. + +Farklı yerlerdeki tip belirteçlerine bağlı olarak otomatik veri doğrulama, veri dönüştürme ve OpenAPI şeması oluşturma desteği sunuyordu. + +Gövde şema tanımları Pydantic ile aynı Python tip belirteçlerini kullanmıyordu, biraz daha Marsmallow'a benziyordu. Dolayısıyla editör desteği de o kadar iyi olmazdı ama APIStar eldeki en iyi seçenekti. + +O dönemlerde karşılaştırmalarda en iyi performansa sahipti (yalnızca Starlette'e kaybediyordu). + +Başlangıçta otomatik API dökümantasyonu sunan bir web arayüzü yoktu, ama ben ona Swagger UI ekleyebileceğimi biliyordum. + +Bağımlılık enjeksiyon sistemi vardı. Yukarıda bahsettiğim diğer araçlar gibi bundaki sistem de bileşenlerin önceden kaydedilmesini gerektiriyordu. Yine de harika bir özellikti. + +Güvenlik entegrasyonu olmadığından dolayı APIStar'ı hiç bir zaman tam bir projede kullanamadım. Bu yüzden Flask-apispec'e bağlı full-stack proje üreticilerde sahip olduğum özellikleri tamamen değiştiremedim. Bu güvenlik entegrasyonunu ekleyen bir PR oluşturmak da projelerim arasında yer alıyordu. + +Sonrasında ise projenin odağı değişti. + +Geliştiricinin Starlette'e odaklanması gerekince proje de artık bir API web framework'ü olmayı bıraktı. + +Artık APIStar, OpenAPI özelliklerini doğrulamak için bir dizi araç sunan bir proje haline geldi. + +!!! info "Bilgi" + APIStar, aşağıdaki projeleri de üreten Tom Christie tarafından geliştirildi: + + * Django REST Framework + * **FastAPI**'ın da dayandığı Starlette + * Starlette ve **FastAPI** tarafından da kullanılan Uvicorn + +!!! check "**FastAPI**'a nasıl ilham oldu?" + Var oldu. + + Aynı Python veri tipleriyle birden fazla şeyi belirleme (veri doğrulama, veri dönüştürme ve dökümantasyon), bir yandan da harika bir editör desteği sunma, benim muhteşem bulduğum bir fikirdi. + + Uzunca bir süre boyunca benzer bir framework arayıp pek çok farklı alternatifi denedikten sonra, APIStar en iyi seçenekti. + + Sonra APIStar bir sunucu olmayı bıraktı ve Starlette oluşturuldu. Starlette, böyle bir sunucu sistemi için daha iyi bir temel sunuyordu. Bu da **FastAPI**'ın son esin kaynağıydı. + + Ben bu önceki araçlardan öğrendiklerime dayanarak **FastAPI**'ın özelliklerini arttırıp geliştiriyor, tip desteği sistemi ve diğer kısımları iyileştiriyorum ancak yine de **FastAPI**'ı APIStar'ın "ruhani varisi" olarak görüyorum. + +## **FastAPI** Tarafından Kullanılanlar + +### Pydantic + +Pydantic Python tip belirteçlerine dayanan; veri doğrulama, veri dönüştürme ve dökümantasyon tanımlamak (JSON Şema kullanarak) için bir kütüphanedir. + +Tip belirteçleri kullanıyor olması onu aşırı sezgisel yapıyor. + +Marshmallow ile karşılaştırılabilir. Ancak karşılaştırmalarda Marshmallowdan daha hızlı görünüyor. Aynı Python tip belirteçlerine dayanıyor ve editör desteği de harika. + +!!! check "**FastAPI** nerede kullanıyor?" + Bütün veri doğrulama, veri dönüştürme ve JSON Şemasına bağlı otomatik model dökümantasyonunu halletmek için! + + **FastAPI** yaptığı her şeyin yanı sıra bu JSON Şema verisini alıp daha sonra OpenAPI'ya yerleştiriyor. + +### Starlette + +Starlette hafif bir ASGI framework'ü ve yüksek performanslı asyncio servisleri oluşturmak için ideal. + +Kullanımı çok kolay ve sezgisel, kolaylıkla genişletilebilecek ve modüler bileşenlere sahip olacak şekilde tasarlandı. + +Sahip olduğu bir kaç özellik: + +* Cidden etkileyici bir performans. +* WebSocket desteği. +* İşlem-içi arka plan görevleri. +* Başlatma ve kapatma olayları. +* HTTPX ile geliştirilmiş bir test istemcisi. +* CORS, GZip, Static Files ve Streaming cevapları desteği. +* Session ve çerez desteği. +* Kodun %100'ü test kapsamında. +* Kodun %100'ü tip belirteçleriyle desteklenmiştir. +* Yalnızca bir kaç zorunlu bağımlılığa sahip. + +Starlette şu anda test edilen en hızlı Python framework'ü. Yalnızca bir sunucu olan Uvicorn'a yeniliyor, o da zaten bir framework değil. + +Starlette bütün temel web mikro framework işlevselliğini sağlıyor. + +Ancak otomatik veri doğrulama, veri dönüştürme ve dökümantasyon sağlamyor. + +Bu, **FastAPI**'ın onun üzerine tamamen Python tip belirteçlerine bağlı olarak eklediği (Pydantic ile) ana şeylerden biri. **FastAPI** bunun yanında artı olarak bağımlılık enjeksiyonu sistemi, güvenlik araçları, OpenAPI şema üretimi ve benzeri özellikler de ekliyor. + +!!! note "Teknik Detaylar" + ASGI, Django'nun ana ekibi tarafından geliştirilen yeni bir "standart". Bir "Python standardı" (PEP) olma sürecinde fakat henüz bir standart değil. + + Bununla birlikte, halihazırda birçok araç tarafından bir "standart" olarak kullanılmakta. Bu, Uvicorn'u farklı ASGI sunucularıyla (Daphne veya Hypercorn gibi) değiştirebileceğiniz veya `python-socketio` gibi ASGI ile uyumlu araçları ekleyebileciğiniz için birlikte çalışılabilirliği büyük ölçüde arttırıyor. + +!!! check "**FastAPI** nerede kullanıyor?" + + Tüm temel web kısımlarında üzerine özellikler eklenerek kullanılmakta. + + `FastAPI` sınıfının kendisi direkt olarak `Starlette` sınıfını miras alıyor! + + Yani, Starlette ile yapabileceğiniz her şeyi, Starlette'in bir nevi güçlendirilmiş hali olan **FastAPI** ile doğrudan yapabilirsiniz. + +### Uvicorn + +Uvicorn, uvlook ile httptools üzerine kurulu ışık hzında bir ASGI sunucusudur. + +Bir web framework'ünden ziyade bir sunucudur, yani yollara bağlı yönlendirme yapmanızı sağlayan araçları yoktur. Bu daha çok Starlette (ya da **FastAPI**) gibi bir framework'ün sunucuya ek olarak sağladığı bir şeydir. + +Starlette ve **FastAPI** için tavsiye edilen sunucu Uvicorndur. + +!!! check "**FastAPI** neden tavsiye ediyor?" + **FastAPI** uygulamalarını çalıştırmak için ana web sunucusu Uvicorn! + + Gunicorn ile birleştirdiğinizde asenkron ve çoklu işlem destekleyen bir sunucu elde ediyorsunuz! + + Daha fazla detay için [Deployment](deployment/index.md){.internal-link target=_blank} bölümünü inceleyebilirsiniz. + +## Karşılaştırma ve Hız + +Uvicorn, Starlette ve FastAPI arasındakı farkı daha iyi anlamak ve karşılaştırma yapmak için [Kıyaslamalar](benchmarks.md){.internal-link target=_blank} bölümüne bakın! diff --git a/docs/tr/docs/async.md b/docs/tr/docs/async.md new file mode 100644 index 0000000000000..2be59434350ad --- /dev/null +++ b/docs/tr/docs/async.md @@ -0,0 +1,401 @@ +# Concurrency ve async / await + +*path operasyon fonksiyonu* için `async def `sözdizimi, asenkron kod, eşzamanlılık ve paralellik hakkında bazı ayrıntılar. + +## Aceleniz mi var? + +TL;DR: + +Eğer `await` ile çağrılması gerektiğini belirten üçüncü taraf kütüphaneleri kullanıyorsanız, örneğin: + +```Python +results = await some_library() +``` + +O zaman *path operasyon fonksiyonunu* `async def` ile tanımlayın örneğin: + +```Python hl_lines="2" +@app.get('/') +async def read_results(): + results = await some_library() + return results +``` + +!!! not + Sadece `async def` ile tanımlanan fonksiyonlar içinde `await` kullanabilirsiniz. + +--- + +Eğer bir veritabanı, bir API, dosya sistemi vb. ile iletişim kuran bir üçüncü taraf bir kütüphane kullanıyorsanız ve `await` kullanımını desteklemiyorsa, (bu şu anda çoğu veritabanı kütüphanesi için geçerli bir durumdur), o zaman *path operasyon fonksiyonunuzu* `def` kullanarak normal bir şekilde tanımlayın, örneğin: + +```Python hl_lines="2" +@app.get('/') +def results(): + results = some_library() + return results +``` + +--- + +Eğer uygulamanız (bir şekilde) başka bir şeyle iletişim kurmak ve onun cevap vermesini beklemek zorunda değilse, `async def` kullanın. + +--- + +Sadece bilmiyorsanız, normal `def` kullanın. + +--- + +**Not**: *path operasyon fonksiyonlarınızda* `def` ve `async def`'i ihtiyaç duyduğunuz gibi karıştırabilir ve her birini sizin için en iyi seçeneği kullanarak tanımlayabilirsiniz. FastAPI onlarla doğru olanı yapacaktır. + +Her neyse, yukarıdaki durumlardan herhangi birinde, FastAPI yine de asenkron olarak çalışacak ve son derece hızlı olacaktır. + +Ancak yukarıdaki adımları takip ederek, bazı performans optimizasyonları yapılabilecektir. + +## Teknik Detaylar + +Python'un modern versiyonlarında **`async` ve `await`** sözdizimi ile **"coroutines"** kullanan **"asenkron kod"** desteğine sahiptir. + +Bu ifadeyi aşağıdaki bölümlerde daha da ayrıntılı açıklayalım: + +* **Asenkron kod** +* **`async` ve `await`** +* **Coroutines** + +## Asenkron kod + +Asenkron kod programlama dilinin 💬 bilgisayara / programa 🤖 kodun bir noktasında, *başka bir kodun* bir yerde bitmesini 🤖 beklemesi gerektiğini söylemenin bir yoludur. Bu *başka koda* "slow-file" denir 📝. + +Böylece, bu süreçte bilgisayar "slow-file" 📝 tamamlanırken gidip başka işler yapabilir. + +Sonra bilgisayar / program 🤖 her fırsatı olduğunda o noktada yaptığı tüm işleri 🤖 bitirene kadar geri dönücek. Ve 🤖 yapması gerekeni yaparak, beklediği görevlerden herhangi birinin bitip bitmediğini görecek. + +Ardından, 🤖 bitirmek için ilk görevi alır ("slow-file" 📝) ve onunla ne yapması gerekiyorsa onu devam ettirir. + +Bu "başka bir şey için bekle" normalde, aşağıdakileri beklemek gibi (işlemcinin ve RAM belleğinin hızına kıyasla) nispeten "yavaş" olan I/O işlemlerine atıfta bulunur: + +* istemci tarafından ağ üzerinden veri göndermek +* ağ üzerinden istemciye gönderilen veriler +* sistem tarafından okunacak ve programınıza verilecek bir dosya içeriği +* programınızın diske yazılmak üzere sisteme verdiği dosya içerikleri +* uzak bir API işlemi +* bir veritabanı bitirme işlemi +* sonuçları döndürmek için bir veritabanı sorgusu +* vb. + +Yürütme süresi çoğunlukla I/O işlemleri beklenerek tüketildiğinden bunlara "I/O bağlantılı" işlemler denir. + +Buna "asenkron" denir, çünkü bilgisayar/program yavaş görevle "senkronize" olmak zorunda değildir, görevin tam olarak biteceği anı bekler, hiçbir şey yapmadan, görev sonucunu alabilmek ve çalışmaya devam edebilmek için . + +Bunun yerine, "asenkron" bir sistem olarak, bir kez bittiğinde, bilgisayarın / programın yapması gerekeni bitirmesi için biraz (birkaç mikrosaniye) sırada bekleyebilir ve ardından sonuçları almak için geri gelebilir ve onlarla çalışmaya devam edebilir. + +"Senkron" ("asenkron"un aksine) için genellikle "sıralı" terimini de kullanırlar, çünkü bilgisayar/program, bu adımlar beklemeyi içerse bile, farklı bir göreve geçmeden önce tüm adımları sırayla izler. + + +### Eşzamanlılık (Concurrency) ve Burgerler + + +Yukarıda açıklanan bu **asenkron** kod fikrine bazen **"eşzamanlılık"** da denir. **"Paralellikten"** farklıdır. + +**Eşzamanlılık** ve **paralellik**, "aynı anda az ya da çok olan farklı işler" ile ilgilidir. + +Ancak *eşzamanlılık* ve *paralellik* arasındaki ayrıntılar oldukça farklıdır. + + +Farkı görmek için burgerlerle ilgili aşağıdaki hikayeyi hayal edin: + +### Eşzamanlı Burgerler + + + +Aşkınla beraber 😍 dışarı hamburger yemeye çıktınız 🍔, kasiyer 💁 öndeki insanlardan sipariş alırken siz sıraya girdiniz. + +Sıra sizde ve sen aşkın 😍 ve kendin için 2 çılgın hamburger 🍔 söylüyorsun. + +Ödemeyi yaptın 💸. + +Kasiyer 💁 mutfakdaki aşçıya 👨‍🍳 hamburgerleri 🍔 hazırlaması gerektiğini söyler ve aşçı bunu bilir (o an önceki müşterilerin siparişlerini hazırlıyor olsa bile). + +Kasiyer 💁 size bir sıra numarası verir. + +Beklerken askınla 😍 bir masaya oturur ve uzun bir süre konuşursunuz(Burgerleriniz çok çılgın olduğundan ve hazırlanması biraz zaman alıyor ✨🍔✨). + +Hamburgeri beklerkenki zamanı 🍔, aşkının ne kadar zeki ve tatlı olduğuna hayran kalarak harcayabilirsin ✨😍✨. + +Aşkınla 😍 konuşurken arada sıranın size gelip gelmediğini kontrol ediyorsun. + +Nihayet sıra size geldi. Tezgaha gidip hamburgerleri 🍔kapıp masaya geri dönüyorsun. + +Aşkınla hamburgerlerinizi yiyor 🍔 ve iyi vakit geçiriyorsunuz ✨. + +--- + +Bu hikayedeki bilgisayar / program 🤖 olduğunuzu hayal edin. + +Sırada beklerken boştasın 😴, sıranı beklerken herhangi bir "üretim" yapmıyorsun. Ama bu sıra hızlı çünkü kasiyer sadece siparişleri alıyor (onları hazırlamıyor), burada bir sıknıtı yok. + +Sonra sıra size geldiğinde gerçekten "üretken" işler yapabilirsiniz 🤓, menüyü oku, ne istediğine larar ver, aşkının seçimini al 😍, öde 💸, doğru kartı çıkart, ödemeyi kontrol et, faturayı kontrol et, siparişin doğru olup olmadığını kontrol et, vb. + +Ama hamburgerler 🍔 hazır olmamasına rağmen Kasiyer 💁 ile işiniz "duraklıyor" ⏸, çünkü hamburgerlerin hazır olmasını bekliyoruz 🕙. + +Ama tezgahtan uzaklaşıp sıranız gelene kadarmasanıza dönebilir 🔀 ve dikkatinizi aşkınıza 😍 verebilirsiniz vr bunun üzerine "çalışabilirsiniz" ⏯ 🤓. Artık "üretken" birşey yapıyorsunuz 🤓, sevgilinle 😍 flört eder gibi. + +Kasiyer 💁 "Hamburgerler hazır !" 🍔 dediğinde ve görüntülenen numara sizin numaranız olduğunda hemen koşup hamburgerlerinizi almaya çalışmıyorsunuz. Biliyorsunuzki kimse sizin hamburgerlerinizi 🍔 çalmayacak çünkü sıra sizin. + +Yani Aşkınızın😍 hikayeyi bitirmesini bekliyorsunuz (çalışmayı bitir ⏯ / görev işleniyor.. 🤓), nazikçe gülümseyin ve hamburger yemeye gittiğinizi söyleyin ⏸. + +Ardından tezgaha 🔀, şimdi biten ilk göreve ⏯ gidin, Hamburgerleri 🍔 alın, teşekkür edin ve masaya götürün. sayacın bu adımı tamamlanır ⏹. Bu da yeni bir görev olan "hamburgerleri ye" 🔀 ⏯ görevini başlatırken "hamburgerleri al" ⏹ görevini bitirir. + +### Parallel Hamburgerler + +Şimdi bunların "Eşzamanlı Hamburger" değil, "Paralel Hamburger" olduğunu düşünelim. + +Hamburger 🍔 almak için 😍 aşkınla Paralel fast food'a gidiyorsun. + +Birden fazla kasiyer varken (varsayalım 8) sıraya girdiniz👩‍🍳👨‍🍳👩‍🍳👨‍🍳👩‍🍳👨‍🍳👩‍🍳👨‍🍳 ve sıranız gelene kadar bekliyorsunuz. + +Sizden önceki herkez ayrılmadan önce hamburgerlerinin 🍔 hazır olmasını bekliyor 🕙. Çünkü kasiyerlerin her biri bir hamburger hazırlanmadan önce bir sonraki siparişe geçmiiyor. + +Sonunda senin sıran, aşkın 😍 ve kendin için 2 hamburger 🍔 siparişi verdiniz. + +Ödemeyi yaptınız 💸. + +Kasiyer mutfağa gider 👨‍🍳. + +Sırada bekliyorsunuz 🕙, kimse sizin burgerinizi 🍔 almaya çalışmıyor çünkü sıra sizin. + +Sen ve aşkın 😍 sıranızı korumak ve hamburgerleri almakla o kadar meşgulsünüz ki birbirinize vakit 🕙 ayıramıyorsunuz 😞. + +İşte bu "senkron" çalışmadır. Kasiyer/aşçı 👨‍🍳ile senkron hareket ediyorsunuz. Bu yüzden beklemek 🕙 ve kasiyer/aşçı burgeri 🍔bitirip size getirdiğinde orda olmak zorundasınız yoksa başka biri alabilir. + +Sonra kasiyeri/aşçı 👨‍🍳 nihayet hamburgerlerinizle 🍔, uzun bir süre sonra 🕙 tezgaha geri geliyor. + +Burgerlerinizi 🍔 al ve aşkınla masanıza doğru ilerle 😍. + +Sadece burgerini yiyorsun 🍔 ve bitti ⏹. + +Bekleyerek çok fazla zaman geçtiğinden 🕙 konuşmaya çok fazla vakit kalmadı 😞. + +--- + +Paralel burger senaryosunda ise, siz iki işlemcili birer robotsunuz 🤖 (sen ve sevgilin 😍), Beklıyorsunuz 🕙 hem konuşarak güzel vakit geçirirken ⏯ hem de sıranızı bekliyorsunuz 🕙. + +Mağazada ise 8 işlemci bulunuyor (Kasiyer/aşçı) 👩‍🍳👨‍🍳👩‍🍳👨‍🍳👩‍🍳👨‍🍳👩‍🍳👨‍🍳. Eşzamanlı burgerde yalnızca 2 kişi olabiliyordu (bir kasiyer ve bir aşçı) 💁 👨‍🍳. + +Ama yine de bu en iyisi değil 😞. + +--- + +Bu hikaye burgerler 🍔 için paralel. + +Bir gerçek hayat örneği verelim. Bir banka hayal edin. + +Bankaların çoğunda birkaç kasiyer 👨‍💼👨‍💼👨‍💼👨‍💼 ve uzun bir sıra var 🕙🕙🕙🕙🕙🕙🕙🕙. + +Tüm işi sırayla bir müşteri ile yapan tüm kasiyerler 👨‍💼⏯. + +Ve uzun süre kuyrukta beklemek 🕙 zorundasın yoksa sıranı kaybedersin. + +Muhtemelen ayak işlerı yaparken sevgilini 😍 bankaya 🏦 getirmezsin. + +### Burger Sonucu + +Bu "aşkınla fast food burgerleri" senaryosunda, çok fazla bekleme olduğu için 🕙, eşzamanlı bir sisteme sahip olmak çok daha mantıklı ⏸🔀⏯. + +Web uygulamalarının çoğu için durum böyledir. + +Pek çok kullanıcı var, ama sunucunuz pek de iyi olmayan bir bağlantı ile istek atmalarını bekliyor. + +Ve sonra yanıtların geri gelmesi için tekrar 🕙 bekliyor + +Bu "bekleme" 🕙 mikrosaniye cinsinden ölçülür, yine de, hepsini toplarsak çok fazla bekleme var. + +Bu nedenle, web API'leri için asenkron ⏸🔀⏯ kod kullanmak çok daha mantıklı. + +Mevcut popüler Python frameworklerinin çoğu (Flask ve Django gibi), Python'daki yeni asenkron özellikler mevcut olmadan önce yazıldı. Bu nedenle, dağıtılma biçimleri paralel yürütmeyi ve yenisi kadar güçlü olmayan eski bir eşzamansız yürütme biçimini destekler. + +Asenkron web (ASGI) özelliği, WebSockets için destek eklemek için Django'ya eklenmiş olsa da. + +Asenkron çalışabilme NodeJS in popüler olmasının sebebi (paralel olamasa bile) ve Go dilini güçlü yapan özelliktir. + +Ve bu **FastAPI** ile elde ettiğiniz performans düzeyiyle aynıdır. + +Aynı anda paralellik ve asenkronluğa sahip olabildiğiniz için, test edilen NodeJS çerçevelerinin çoğundan daha yüksek performans elde edersiniz ve C'ye daha yakın derlenmiş bir dil olan Go ile eşit bir performans elde edersiniz (bütün teşekkürler Starlette'e ). + +### Eşzamanlılık paralellikten daha mı iyi? + +Hayır! Hikayenin ahlakı bu değil. + +Eşzamanlılık paralellikten farklıdır. Ve çok fazla bekleme içeren **belirli** senaryolarda daha iyidir. Bu nedenle, genellikle web uygulamaları için paralellikten çok daha iyidir. Ama her şey için değil. + +Yanı, bunu aklınızda oturtmak için aşağıdaki kısa hikayeyi hayal edin: + +> Büyük, kirli bir evi temizlemelisin. + +*Evet, tüm hikaye bu*. + +--- + +Beklemek yok 🕙. Hiçbir yerde. Sadece evin birden fazla yerinde yapılacak fazlasıyla iş var. + +You could have turns as in the burgers example, first the living room, then the kitchen, but as you are not waiting 🕙 for anything, just cleaning and cleaning, the turns wouldn't affect anything. +Hamburger örneğindeki gibi dönüşleriniz olabilir, önce oturma odası, sonra mutfak, ama hiçbir şey için 🕙 beklemediğinizden, sadece temizlik, temizlik ve temizlik, dönüşler hiçbir şeyi etkilemez. + +Sıralı veya sırasız (eşzamanlılık) bitirmek aynı zaman alır ve aynı miktarda işi yaparsınız. + +Ama bu durumda, 8 eski kasiyer/aşçı - yeni temizlikçiyi getirebilseydiniz 👩‍🍳👨‍🍳👩‍🍳👨‍🍳👩‍🍳👨‍🍳👩‍🍳👨‍🍳 ve her birini (artı siz) evin bir bölgesini temizlemek için görevlendirseydiniz, ekstra yardımla tüm işleri **paralel** olarak yapabilir ve çok daha erken bitirebilirdiniz. + +Bu senaryoda, temizlikçilerin her biri (siz dahil) birer işlemci olacak ve üzerine düşeni yapacaktır. + +Yürütme süresinin çoğu (beklemek yerine) iş yapıldığından ve bilgisayardaki iş bir CPU tarafından yapıldığından, bu sorunlara "CPU bound" diyorlar". + +--- + +CPU'ya bağlı işlemlerin yaygın örnekleri, karmaşık matematik işlemleri gerektiren işlerdir. + +Örneğin: + +* **Ses** veya **görüntü işleme**. +* **Bilgisayar görüsü**: bir görüntü milyonlarca pikselden oluşur, her pikselin 3 değeri / rengi vardır, bu pikseller üzerinde aynı anda bir şeyler hesaplamayı gerektiren işleme. +* **Makine Öğrenimi**: Çok sayıda "matris" ve "vektör" çarpımı gerektirir. Sayıları olan ve hepsini aynı anda çarpan büyük bir elektronik tablo düşünün. +* **Derin Öğrenme**: Bu, Makine Öğreniminin bir alt alanıdır, dolayısıyla aynısı geçerlidir. Sadece çarpılacak tek bir sayı tablosu değil, büyük bir sayı kümesi vardır ve çoğu durumda bu modelleri oluşturmak ve/veya kullanmak için özel işlemciler kullanırsınız. + +### Eşzamanlılık + Paralellik: Web + Makine Öğrenimi + +**FastAPI** ile web geliştirme için çok yaygın olan eşzamanlılıktan yararlanabilirsiniz (NodeJS'in aynı çekiciliği). + +Ancak, Makine Öğrenimi sistemlerindekile gibi **CPU'ya bağlı** iş yükleri için paralellik ve çoklu işlemenin (birden çok işlemin paralel olarak çalışması) avantajlarından da yararlanabilirsiniz. + +Buna ek olarak Python'un **Veri Bilimi**, Makine Öğrenimi ve özellikle Derin Öğrenme için ana dil olduğu gerçeği, FastAPI'yi Veri Bilimi / Makine Öğrenimi web API'leri ve uygulamaları için çok iyi bir seçenek haline getirir. + +Production'da nasıl oldugunu görmek için şu bölüme bakın [Deployment](deployment/index.md){.internal-link target=_blank}. + +## `async` ve `await` + +Python'un modern sürümleri, asenkron kodu tanımlamanın çok sezgisel bir yoluna sahiptir. Bu, normal "sequentıal" (sıralı) kod gibi görünmesini ve doğru anlarda sizin için "awaıt" ile bekleme yapmasını sağlar. + +Sonuçları vermeden önce beklemeyi gerektirecek ve yeni Python özelliklerini destekleyen bir işlem olduğunda aşağıdaki gibi kodlayabilirsiniz: + +```Python +burgers = await get_burgers(2) +``` + +Buradaki `await` anahtari Python'a, sonuçları `burgers` degiskenine atamadan önce `get_burgers(2)` kodunun işini bitirmesini 🕙 beklemesi gerektiğini söyler. Bununla Python, bu ara zamanda başka bir şey 🔀 ⏯ yapabileceğini bilecektir (başka bir istek almak gibi). + + `await`kodunun çalışması için, eşzamansızlığı destekleyen bir fonksiyonun içinde olması gerekir. Bunu da yapmak için fonksiyonu `async def` ile tanımlamamız yeterlidir: + +```Python hl_lines="1" +async def get_burgers(number: int): + # burgerleri oluşturmak için asenkron birkaç iş + return burgers +``` + +...`def` yerine: + +```Python hl_lines="2" +# bu kod asenkron değil +def get_sequential_burgers(number: int): + # burgerleri oluşturmak için senkron bırkaç iş + return burgers +``` + +`async def` ile Python, bu fonksıyonun içinde, `await` ifadelerinin farkında olması gerektiğini ve çalışma zamanı gelmeden önce bu işlevin yürütülmesini "duraklatabileceğini" ve başka bir şey yapabileceğini 🔀 bilir. + +`async def` fonksiyonunu çağırmak istediğinizde, onu "awaıt" ıle kullanmanız gerekir. Yani, bu işe yaramaz: + +```Python +# Bu işe yaramaz, çünkü get_burgers, şu şekilde tanımlandı: async def +burgers = get_burgers(2) +``` + +--- + +Bu nedenle, size onu `await` ile çağırabileceğinizi söyleyen bir kitaplık kullanıyorsanız, onu `async def` ile tanımlanan *path fonksiyonu* içerisinde kullanmanız gerekir, örneğin: + +```Python hl_lines="2-3" +@app.get('/burgers') +async def read_burgers(): + burgers = await get_burgers(2) + return burgers +``` + +### Daha fazla teknik detay + +`await` in yalnızca `async def` ile tanımlanan fonksıyonların içinde kullanılabileceğini fark etmişsinizdir. + +Ama aynı zamanda, `async def` ile tanımlanan fonksiyonların "await" ile beklenmesi gerekir. Bu nedenle, "`async def` içeren fonksiyonlar yalnızca "`async def` ile tanımlanan fonksiyonların içinde çağrılabilir. + + +Yani yumurta mı tavukdan, tavuk mu yumurtadan gibi ilk `async` fonksiyonu nasıl çağırılır? + +**FastAPI** ile çalışıyorsanız bunun için endişelenmenize gerek yok, çünkü bu "ilk" fonksiyon sizin *path fonksiyonunuz* olacak ve FastAPI doğru olanı nasıl yapacağını bilecek. + +Ancak FastAPI olmadan `async` / `await` kullanmak istiyorsanız, resmi Python belgelerini kontrol edin. + +### Asenkron kodun diğer biçimleri + +Bu `async` ve `await` kullanimi oldukça yenidir. + +Ancak asenkron kodla çalışmayı çok daha kolay hale getirir. + +Aynı sözdizimi (hemen hemen aynı) son zamanlarda JavaScript'in modern sürümlerine de dahil edildi (Tarayıcı ve NodeJS'de). + +Ancak bundan önce, asenkron kodu işlemek oldukça karmaşık ve zordu. + +Python'un önceki sürümlerinde, threadlerı veya Gevent kullanıyor olabilirdin. Ancak kodu anlamak, hata ayıklamak ve düşünmek çok daha karmaşık olurdu. + +NodeJS / Browser JavaScript'in önceki sürümlerinde, "callback" kullanırdınız. Bu da callbacks cehennemine yol açar. + +## Coroutine'ler + +**Coroutine**, bir `async def` fonksiyonu tarafından döndürülen değer için çok süslü bir terimdir. Python bunun bir fonksiyon gibi bir noktada başlayıp biteceğini bilir, ancak içinde bir `await` olduğunda dahili olarak da duraklatılabilir ⏸. + +Ancak, `async` ve `await` ile asenkron kod kullanmanın tüm bu işlevselliği, çoğu zaman "Coroutine" kullanmak olarak adlandırılır. Go'nun ana özelliği olan "Goroutines" ile karşılaştırılabilir. + +## Sonuç + +Aynı ifadeyi yukarıdan görelim: + +> Python'ın modern sürümleri, **"async" ve "await"** sözdizimi ile birlikte **"coroutines"** adlı bir özelliği kullanan **"asenkron kod"** desteğine sahiptir. + +Şimdi daha mantıklı gelmeli. ✨ + +FastAPI'ye (Starlette aracılığıyla) güç veren ve bu kadar etkileyici bir performansa sahip olmasını sağlayan şey budur. + +## Çok Teknik Detaylar + +!!! warning + Muhtemelen burayı atlayabilirsiniz. + + Bunlar, **FastAPI**'nin altta nasıl çalıştığına dair çok teknik ayrıntılardır. + + Biraz teknik bilginiz varsa (co-routines, threads, blocking, vb)ve FastAPI'nin "async def" ile normal "def" arasındaki farkı nasıl işlediğini merak ediyorsanız, devam edin. + +### Path fonksiyonu + +"async def" yerine normal "def" ile bir *yol işlem işlevi* bildirdiğinizde, doğrudan çağrılmak yerine (sunucuyu bloke edeceğinden) daha sonra beklenen harici bir iş parçacığı havuzunda çalıştırılır. + +Yukarıda açıklanan şekilde çalışmayan başka bir asenkron framework'den geliyorsanız ve küçük bir performans kazancı (yaklaşık 100 nanosaniye) için "def" ile *path fonksiyonu* tanımlamaya alışkınsanız, **FastAPI**'de tam tersi olacağını unutmayın. Bu durumlarda, *path fonksiyonu* G/Ç engelleyen durum oluşturmadıkça "async def" kullanmak daha iyidir. + +Yine de, her iki durumda da, **FastAPI**'nin önceki frameworkden [hala daha hızlı](/#performance){.internal-link target=_blank} (veya en azından karşılaştırılabilir) olma olasılığı vardır. + +### Bagımlılıklar + +Aynısı bağımlılıklar için de geçerlidir. Bir bağımlılık, "async def" yerine standart bir "def" işleviyse, harici iş parçacığı havuzunda çalıştırılır. + +### Alt-bağımlıklar + +Birbirini gerektiren (fonksiyonlarin parametreleri olarak) birden fazla bağımlılık ve alt bağımlılıklarınız olabilir, bazıları 'async def' ve bazıları normal 'def' ile oluşturulabilir. Yine de normal 'def' ile oluşturulanlar, "await" kulanilmadan harici bir iş parçacığında (iş parçacığı havuzundan) çağrılır. + +### Diğer yardımcı fonksiyonlar + +Doğrudan çağırdığınız diğer herhangi bir yardımcı fonksiyonu, normal "def" veya "async def" ile tanimlayabilirsiniz. FastAPI onu çağırma şeklinizi etkilemez. + +Bu, FastAPI'nin sizin için çağırdığı fonksiyonlarin tam tersidir: *path fonksiyonu* ve bağımlılıklar. + +Yardımcı program fonksiyonunuz 'def' ile normal bir işlevse, bir iş parçacığı havuzunda değil doğrudan (kodunuzda yazdığınız gibi) çağrılır, işlev 'async def' ile oluşturulmuşsa çağırıldığı yerde 'await' ile beklemelisiniz. + +--- + +Yeniden, bunlar, onları aramaya geldiğinizde muhtemelen işinize yarayacak çok teknik ayrıntılardır. + +Aksi takdirde, yukarıdaki bölümdeki yönergeleri iyi bilmelisiniz: Aceleniz mi var?. diff --git a/docs/tr/docs/benchmarks.md b/docs/tr/docs/benchmarks.md index 1ce3c758f1e6a..eb5472869ab69 100644 --- a/docs/tr/docs/benchmarks.md +++ b/docs/tr/docs/benchmarks.md @@ -1,34 +1,34 @@ # Kıyaslamalar -Bağımsız TechEmpower kıyaslamaları gösteriyor ki Uvicorn'la beraber çalışan **FastAPI** uygulamaları Python'un en hızlı frameworklerinden birisi , sadece Starlette ve Uvicorn'dan daha düşük sıralamada (FastAPI bu frameworklerin üzerine kurulu). (*) +Bağımsız TechEmpower kıyaslamaları gösteriyor ki en hızlı Python frameworklerinden birisi olan Uvicorn ile çalıştırılan **FastAPI** uygulamaları, sadece Starlette ve Uvicorn'dan daha düşük sıralamada (FastAPI bu frameworklerin üzerine kurulu) yer alıyor. (*) Fakat kıyaslamaları ve karşılaştırmaları incelerken şunları aklınızda bulundurmalısınız. -## Kıyaslamalar ve hız +## Kıyaslamalar ve Hız -Kıyaslamaları incelediğinizde, farklı özelliklere sahip birçok araçların eşdeğer olarak karşılaştırıldığını görmek yaygındır. +Kıyaslamaları incelediğinizde, farklı özelliklere sahip araçların eşdeğer olarak karşılaştırıldığını yaygın bir şekilde görebilirsiniz. -Özellikle, Uvicorn, Starlette ve FastAPI'ın birlikte karşılaştırıldığını görmek için (diğer birçok araç arasında). +Özellikle, (diğer birçok araç arasında) Uvicorn, Starlette ve FastAPI'ın birlikte karşılaştırıldığını görebilirsiniz. -Araç tarafından çözülen sorun ne kadar basitse, o kadar iyi performans alacaktır. Ve kıyaslamaların çoğu, araç tarafından sağlanan ek özellikleri test etmez. +Aracın çözdüğü problem ne kadar basitse, performansı o kadar iyi olacaktır. Ancak kıyaslamaların çoğu, aracın sağladığı ek özellikleri test etmez. Hiyerarşi şöyledir: * **Uvicorn**: bir ASGI sunucusu - * **Starlette**: (Uvicorn'u kullanır) bir web microframeworkü - * **FastAPI**: (Starlette'i kullanır) data validation vb. ile API'lar oluşturmak için çeşitli ek özelliklere sahip bir API frameworkü + * **Starlette**: (Uvicorn'u kullanır) bir web mikroframeworkü + * **FastAPI**: (Starlette'i kullanır) veri doğrulama vb. çeşitli ek özelliklere sahip, API oluşturmak için kullanılan bir API mikroframeworkü * **Uvicorn**: - * Sunucunun kendisi dışında ekstra bir kod içermediği için en iyi performansa sahip olacaktır - * Direkt olarak Uvicorn'da bir uygulama yazmazsınız. Bu, en azından Starlette tarafından sağlanan tüm kodu (veya **FastAPI**) az çok içermesi gerektiği anlamına gelir. Ve eğer bunu yaptıysanız, son uygulamanız bir framework kullanmak ve uygulama kodlarını ve bugları en aza indirmekle aynı ek yüke sahip olacaktır. + * Sunucunun kendisi dışında ekstra bir kod içermediği için en iyi performansa sahip olacaktır. + * Doğrudan Uvicorn ile bir uygulama yazmazsınız. Bu, yazdığınız kodun en azından Starlette tarafından sağlanan tüm kodu (veya **FastAPI**) az çok içermesi gerektiği anlamına gelir. Eğer bunu yaptıysanız, son uygulamanız bir framework kullanmak ve uygulama kodlarını ve hataları en aza indirmekle aynı ek yüke sahip olacaktır. * Eğer Uvicorn'u karşılaştırıyorsanız, Daphne, Hypercorn, uWSGI, vb. uygulama sunucuları ile karşılaştırın. * **Starlette**: - * Uvicorn'dan sonraki en iyi performansa sahip olacak. Aslında, Starlette çalışmak için Uvicorn'u kullanıyor. Dolayısıyla, muhtemelen daha fazla kod çalıştırmak zorunda kaldığında Uvicorn'dan sadece "daha yavaş" olabilir. - * Ancak routing based on paths ile vb. basit web uygulamaları oluşturmak için araçlar sağlar. - * Eğer Starlette'i karşılaştırıyorsanız, Sanic, Flask, Django, vb. frameworkler (veya microframeworkler) ile karşılaştırın. + * Uvicorn'dan sonraki en iyi performansa sahip olacaktır. İşin aslı, Starlette çalışmak için Uvicorn'u kullanıyor. Dolayısıyla, daha fazla kod çalıştırmaası gerektiğinden muhtemelen Uvicorn'dan sadece "daha yavaş" olabilir. + * Ancak yol bazlı yönlendirme vb. basit web uygulamaları oluşturmak için araçlar sağlar. + * Eğer Starlette'i karşılaştırıyorsanız, Sanic, Flask, Django, vb. frameworkler (veya mikroframeworkler) ile karşılaştırın. * **FastAPI**: - * Starlette'in Uvicorn'u kullandığı ve ondan daha hızlı olamayacağı gibi, **FastAPI** da Starlette'i kullanır, bu yüzden ondan daha hızlı olamaz. - * FastAPI, Starlette'e ek olarak daha fazla özellik sunar. Data validation ve serialization gibi API'lar oluştururken neredeyse ve her zaman ihtiyaç duyduğunuz özellikler. Ve bunu kullanarak, ücretsiz olarak otomatik dokümantasyon elde edersiniz (otomatik dokümantasyon çalışan uygulamalara ek yük getirmez, başlangıçta oluşturulur). - * FastAPI'ı kullanmadıysanız ve Starlette'i doğrudan kullandıysanız (veya başka bir araç, Sanic, Flask, Responder, vb.) tüm data validation'ı ve serialization'ı kendiniz sağlamanız gerekir. Dolayısıyla, son uygulamanız FastAPI kullanılarak oluşturulmuş gibi hâlâ aynı ek yüke sahip olacaktır. Çoğu durumda, uygulamalarda yazılan kodun büyük çoğunluğunu data validation ve serialization oluşturur. - * Dolayısıyla, FastAPI'ı kullanarak geliştirme süresinden, buglardan, kod satırlarından tasarruf edersiniz ve muhtemelen kullanmasaydınız aynı performansı (veya daha iyisini) elde edersiniz. (hepsini kodunuza uygulamak zorunda kalacağınız gibi) - * Eğer FastAPI'ı karşılaştırıyorsanız, Flask-apispec, NestJS, Molten, vb. gibi data validation, serialization ve dokümantasyon sağlayan bir web uygulaması frameworkü ile (veya araç setiyle) karşılaştırın. Entegre otomatik data validation, serialization ve dokümantasyon içeren frameworkler. + * Starlette'in Uvicorn'u kullandığı ve ondan daha hızlı olamayacağı gibi, **FastAPI**'da Starlette'i kullanır, dolayısıyla ondan daha hızlı olamaz. + * FastAPI, Starlette'e ek olarak daha fazla özellik sunar. Bunlar veri doğrulama ve dönüşümü gibi API'lar oluştururken neredeyse ve her zaman ihtiyaç duyduğunuz özelliklerdir. Ve bunu kullanarak, ücretsiz olarak otomatik dokümantasyon elde edersiniz (otomatik dokümantasyon çalışan uygulamalara ek yük getirmez, başlangıçta oluşturulur). + * FastAPI'ı kullanmadıysanız ve Starlette'i doğrudan kullandıysanız (veya başka bir araç, Sanic, Flask, Responder, vb.) tüm veri doğrulama ve dönüştürme araçlarını kendiniz geliştirmeniz gerekir. Dolayısıyla, son uygulamanız FastAPI kullanılarak oluşturulmuş gibi hâlâ aynı ek yüke sahip olacaktır. Çoğu durumda, uygulamalarda yazılan kodun büyük bir kısmını veri doğrulama ve dönüştürme kodları oluşturur. + * Dolayısıyla, FastAPI'ı kullanarak geliştirme süresinden, hatalardan, kod satırlarından tasarruf edersiniz ve kullanmadığınız durumda (birçok özelliği geliştirmek zorunda kalmakla birlikte) muhtemelen aynı performansı (veya daha iyisini) elde ederdiniz. + * Eğer FastAPI'ı karşılaştırıyorsanız, Flask-apispec, NestJS, Molten, vb. gibi veri doğrulama, dönüştürme ve dokümantasyon sağlayan bir web uygulaması frameworkü ile (veya araç setiyle) karşılaştırın. diff --git a/docs/tr/docs/external-links.md b/docs/tr/docs/external-links.md new file mode 100644 index 0000000000000..78eaf1729d80b --- /dev/null +++ b/docs/tr/docs/external-links.md @@ -0,0 +1,33 @@ +# Harici Bağlantılar ve Makaleler + +**FastAPI** sürekli büyüyen harika bir topluluğa sahiptir. + +**FastAPI** ile alakalı birçok yazı, makale, araç ve proje bulunmaktadır. + +Bunlardan bazılarının tamamlanmamış bir listesi aşağıda bulunmaktadır. + +!!! tip "İpucu" + Eğer **FastAPI** ile alakalı henüz burada listelenmemiş bir makale, proje, araç veya başka bir şeyiniz varsa, bunu eklediğiniz bir Pull Request oluşturabilirsiniz. + +{% for section_name, section_content in external_links.items() %} + +## {{ section_name }} + +{% for lang_name, lang_content in section_content.items() %} + +### {{ lang_name }} + +{% for item in lang_content %} + +* {{ item.title }} by {{ item.author }}. + +{% endfor %} +{% endfor %} +{% endfor %} + +## Projeler + +`fastapi` konulu en son GitHub projeleri: + +
+
diff --git a/docs/tr/docs/fastapi-people.md b/docs/tr/docs/fastapi-people.md index 3e459036aa75b..6dd4ec0611659 100644 --- a/docs/tr/docs/fastapi-people.md +++ b/docs/tr/docs/fastapi-people.md @@ -1,10 +1,15 @@ +--- +hide: + - navigation +--- + # FastAPI Topluluğu FastAPI, her kökenden insanı ağırlayan harika bir topluluğa sahip. ## Yazan - Geliştiren -Hey! 👋 +Merhaba! 👋 İşte bu benim: @@ -12,38 +17,37 @@ Hey! 👋
{% for user in people.maintainers %} -
@{{ user.login }}
Answers: {{ user.answers }}
Pull Requests: {{ user.prs }}
+
@{{ user.login }}
Cevaplar: {{ user.answers }}
Pull Request'ler: {{ user.prs }}
{% endfor %}
{% endif %} -Ben **FastAPI** 'nin yazarı ve geliştiricisiyim. Bununla ilgili daha fazla bilgiyi şurada okuyabilirsiniz: - [FastAPI yardım - yardım al - Yazar ile iletişime geç](help-fastapi.md#connect-with-the-author){.internal-link target=_blank}. +Ben **FastAPI**'ın geliştiricisiyim. Bununla ilgili daha fazla bilgiyi şurada okuyabilirsiniz: [FastAPI yardım - yardım al - benimle iletişime geç](help-fastapi.md#connect-with-the-author){.internal-link target=_blank}. -... Burada size harika FastAPI topluluğunu göstermek istiyorum. +...burada size harika FastAPI topluluğunu göstermek istiyorum. --- -**FastAPI** topluluğundan destek alıyor. Ve katkıda bulunanları vurgulamak istiyorum. +**FastAPI**, topluluğundan çok destek alıyor. Ben de onların katkılarını vurgulamak istiyorum. -İşte o mükemmel insanlar: +Bu insanlar: -* [GitHubdaki sorunları (issues) çözmelerinde diğerlerine yardım et](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank}. -* [Pull Requests oluşturun](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}. -* Pull Requests 'leri gözden geçirin, [özelliklede çevirileri](contributing.md#translations){.internal-link target=_blank}. +* [GitHubdaki soruları cevaplayarak diğerlerine yardım ediyor](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}. +* [Pull Request'ler oluşturuyor](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}. +* Pull Request'leri gözden geçiriyorlar, [özellikle çeviriler için bu çok önemli](contributing.md#translations){.internal-link target=_blank}. -Onlara bir alkış. 👏 🙇 +Onları bir alkışlayalım. 👏 🙇 -## Geçen ayın en aktif kullanıcıları +## Geçen Ayın En Aktif Kullanıcıları -Bunlar geçen ay boyunca [GitHub' da başkalarına sorunlarında (issues) en çok yardımcı olan ](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank} kullanıcılar ☕ +Geçtiğimiz ay boyunca [GitHub'da diğerlerine en çok yardımcı olan](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} kullanıcılar. ☕ {% if people %}
-{% for user in people.last_month_active %} +{% for user in people.last_month_experts[:10] %} -
@{{ user.login }}
Issues replied: {{ user.count }}
+
@{{ user.login }}
Cevaplanan soru sayısı: {{ user.count }}
{% endfor %}
@@ -53,57 +57,57 @@ Bunlar geçen ay boyunca [GitHub' da başkalarına sorunlarında (issues) en ço İşte **FastAPI Uzmanları**. 🤓 -Bunlar *tüm zamanlar boyunca* [GitHub' da başkalarına sorunlarında (issues) en çok yardımcı olan](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank} kullanıcılar. +Uzmanlarımız ise *tüm zamanlar boyunca* [GitHub'da insanların sorularına en çok yardımcı olan](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} insanlar. -Başkalarına yardım ederek uzman olduklarını kanıtladılar. ✨ +Bir çok kullanıcıya yardım ederek uzman olduklarını kanıtladılar! ✨ {% if people %}
-{% for user in people.experts %} +{% for user in people.experts[:50] %} -
@{{ user.login }}
Issues replied: {{ user.count }}
+
@{{ user.login }}
Cevaplanan soru sayısı: {{ user.count }}
{% endfor %}
{% endif %} -## En fazla katkıda bulunanlar +## En Fazla Katkıda Bulunanlar -işte **En fazla katkıda bulunanlar**. 👷 +Şimdi ise sıra **en fazla katkıda bulunanlar**da. 👷 -Bu kullanıcılar en çok [Pull Requests oluşturan](help-fastapi.md#create-a-pull-request){.internal-link target=_blank} ve onu kaynak koduna *birleştirenler*. +Bu kullanıcılar en fazla [kaynak koduyla birleştirilen Pull Request'lere](help-fastapi.md#create-a-pull-request){.internal-link target=_blank} sahip! -Kaynak koduna, belgelere, çevirilere vb. katkıda bulundular. 📦 +Kaynak koduna, dökümantasyona, çevirilere ve bir sürü şeye katkıda bulundular. 📦 {% if people %}
-{% for user in people.top_contributors %} +{% for user in people.top_contributors[:50] %} -
@{{ user.login }}
Pull Requests: {{ user.count }}
+
@{{ user.login }}
Pull Request sayısı: {{ user.count }}
{% endfor %}
{% endif %} -Çok fazla katkıda bulunan var (binden fazla), hepsini şurda görebilirsin: FastAPI GitHub Katkıda Bulunanlar. 👷 +Bunlar dışında katkıda bulunan, yüzden fazla, bir sürü insan var. Hepsini FastAPI GitHub Katkıda Bulunanlar sayfasında görebilirsin. 👷 -## En fazla inceleme yapanlar +## En Fazla Değerlendirme Yapanlar -İşte **En fazla inceleme yapanlar**. 🕵️ +İşte **en çok değerlendirme yapanlar**. 🕵️ -### Çeviri için İncelemeler +### Çeviri Değerlendirmeleri -Yalnızca birkaç dil konuşabiliyorum (ve çok da iyi değilim 😅). Bu yüzden döküman çevirilerini [**onaylama yetkisi**](contributing.md#translations){.internal-link target=_blank} siz inceleyenlere aittir. Sizler olmadan diğer birkaç dilde dokümantasyon olmazdı. +Yalnızca birkaç dil konuşabiliyorum (ve çok da iyi değilim 😅). Bu yüzden değerlendirme yapanların da döküman çevirilerini [**onaylama yetkisi**](contributing.md#translations){.internal-link target=_blank} var. Onlar olmasaydı çeşitli dillerde dökümantasyon da olmazdı. --- -**En fazla inceleme yapanlar** 🕵️ kodun, belgelerin ve özellikle **çevirilerin** kalitesini sağlamak için diğerlerinden daha fazla pull requests incelemiştir. +**En fazla değerlendirme yapanlar** 🕵️ kodun, dökümantasyonun ve özellikle **çevirilerin** Pull Request'lerini inceleyerek kalitesinden emin oldular. {% if people %}
-{% for user in people.top_reviewers %} +{% for user in people.top_translations_reviewers[:50] %} -
@{{ user.login }}
Reviews: {{ user.count }}
+
@{{ user.login }}
Değerlendirme sayısı: {{ user.count }}
{% endfor %}
@@ -113,66 +117,67 @@ Yalnızca birkaç dil konuşabiliyorum (ve çok da iyi değilim 😅). Bu yüzde işte **Sponsorlarımız**. 😎 -**FastAPI** ve diğer projelerde çalışmamı destekliyorlar, özellikle de GitHub Sponsorları. +Çoğunlukla GitHub Sponsorları aracılığıyla olmak üzere, **FastAPI** ve diğer projelerdeki çalışmalarımı destekliyorlar. + +{% if sponsors %} + +{% if sponsors.gold %} ### Altın Sponsorlar -{% if sponsors %} {% for sponsor in sponsors.gold -%} {% endfor %} {% endif %} +{% if sponsors.silver %} + ### Gümüş Sponsorlar -{% if sponsors %} {% for sponsor in sponsors.silver -%} {% endfor %} {% endif %} +{% if sponsors.bronze %} + ### Bronz Sponsorlar -{% if sponsors %} {% for sponsor in sponsors.bronze -%} {% endfor %} {% endif %} +{% endif %} + ### Bireysel Sponsorlar -{% if people %} -{% if people.sponsors_50 %} +{% if github_sponsors %} +{% for group in github_sponsors.sponsors %}
-{% for user in people.sponsors_50 %} - -{% endfor %} +{% for user in group %} +{% if user.login not in sponsors_badge.logins %} -
+ {% endif %} -{% endif %} - -{% if people %} -
-{% for user in people.sponsors %} - - {% endfor %}
+ +{% endfor %} {% endif %} -## Veriler hakkında - Teknik detaylar +## Veriler - Teknik detaylar Bu sayfanın temel amacı, topluluğun başkalarına yardım etme çabasını vurgulamaktır. -Özellikle normalde daha az görünür olan ve çoğu durumda daha zahmetli olan, diğerlerine sorunlar konusunda yardımcı olmak ve pull requests'leri gözden geçirmek gibi çabalar dahil. +Özellikle normalde daha az görünür olan ve çoğu durumda daha zahmetli olan, diğerlerine sorularında yardımcı olmak, çevirileri ve Pull Request'leri gözden geçirmek gibi çabalar dahil. -Veriler ayda bir hesaplanır, işte kaynak kodu okuyabilirsin :source code here. +Veriler ayda bir hesaplanır, kaynak kodu buradan okuyabilirsin. -Burada sponsorların katkılarını da tekrardan vurgulamak isterim. +Burada sponsorların katkılarını da vurguluyorum. -Ayrıca algoritmayı, bölümleri, eşikleri vb. güncelleme hakkımı da saklı tutarım (her ihtimale karşı 🤷). +Ayrıca algoritmayı, bölümleri, eşikleri vb. güncelleme hakkımı da saklı tutuyorum (her ihtimale karşı 🤷). diff --git a/docs/tr/docs/features.md b/docs/tr/docs/features.md index f8220fb58f66b..1cda8c7fbccda 100644 --- a/docs/tr/docs/features.md +++ b/docs/tr/docs/features.md @@ -27,7 +27,7 @@ OpenAPI standartlarına dayalı olan bir framework olarak, geliştiricilerin bir ### Sadece modern Python -Tamamiyle standartlar **Python 3.6**'nın type hintlerine dayanıyor (Pydantic'in sayesinde). Yeni bir syntax öğrenmene gerek yok. Sadece modern Python. +Tamamiyle standartlar **Python 3.8**'nın type hintlerine dayanıyor (Pydantic'in sayesinde). Yeni bir syntax öğrenmene gerek yok. Sadece modern Python. Eğer Python type hintlerini bilmiyorsan veya bir hatırlatmaya ihtiyacın var ise(FastAPI kullanmasan bile) şu iki dakikalık küçük bilgilendirici içeriğe bir göz at: [Python Types](python-types.md){.internal-link target=_blank}. @@ -182,7 +182,7 @@ Bütün entegrasyonlar kullanımı kolay olmak üzere (zorunluluklar ile beraber ## Pydantic özellikleri -**FastAPI** ile Pydantic tamamiyle uyumlu ve üzerine kurulu. Yani FastAPI üzerine ekleme yapacağınız herhangi bir Pydantic kodu da çalışacaktır. +**FastAPI** ile Pydantic tamamiyle uyumlu ve üzerine kurulu. Yani FastAPI üzerine ekleme yapacağınız herhangi bir Pydantic kodu da çalışacaktır. Bunlara Pydantic üzerine kurulu ORM databaseler ve , ODM kütüphaneler de dahil olmak üzere. @@ -197,8 +197,6 @@ Aynı şekilde, databaseden gelen objeyi de **direkt olarak isteğe** de tamamiy * Eğer Python typelarını nasıl kullanacağını biliyorsan Pydantic kullanmayı da biliyorsundur. * Kullandığın geliştirme araçları ile iyi çalışır **IDE/linter/brain**: * Pydantic'in veri yapıları aslında sadece senin tanımladığın classlar; Bu yüzden doğrulanmış dataların ile otomatik tamamlama, linting ve mypy'ı kullanarak sorunsuz bir şekilde çalışabilirsin -* **Hızlı**: - * Benchmarklarda, Pydantic'in diğer bütün test edilmiş bütün kütüphanelerden daha hızlı. * **En kompleks** yapıları bile doğrula: * Hiyerarşik Pydantic modellerinin kullanımı ile beraber, Python `typing`’s `List` and `Dict`, vs gibi şeyleri doğrula. * Doğrulayıcılar en kompleks data şemalarının bile temiz ve kolay bir şekilde tanımlanmasına izin veriyor, ve hepsi JSON şeması olarak dokümante ediliyor diff --git a/docs/tr/docs/help/index.md b/docs/tr/docs/help/index.md new file mode 100644 index 0000000000000..cef0914ce7a66 --- /dev/null +++ b/docs/tr/docs/help/index.md @@ -0,0 +1,3 @@ +# Yardım + +Yardım alın, yardım edin, katkıda bulunun, dahil olun. 🤝 diff --git a/docs/tr/docs/history-design-future.md b/docs/tr/docs/history-design-future.md new file mode 100644 index 0000000000000..1dd0e637f52b5 --- /dev/null +++ b/docs/tr/docs/history-design-future.md @@ -0,0 +1,79 @@ +# Geçmişi, Tasarımı ve Geleceği + +Bir süre önce, bir **FastAPI** kullanıcısı sordu: + +> Bu projenin geçmişi nedir? Birkaç hafta içinde hiçbir yerden harika bir şeye dönüşmüş gibi görünüyor [...] + +İşte o geçmişin bir kısmı. + +## Alternatifler + +Bir süredir karmaşık gereksinimlere sahip API'lar oluşturuyor (Makine Öğrenimi, dağıtık sistemler, asenkron işler, NoSQL veritabanları vb.) ve farklı geliştirici ekiplerini yönetiyorum. + +Bu süreçte birçok alternatifi araştırmak, test etmek ve kullanmak zorunda kaldım. + +**FastAPI**'ın geçmişi, büyük ölçüde önceden geliştirilen araçların geçmişini kapsıyor. + +[Alternatifler](alternatives.md){.internal-link target=_blank} bölümünde belirtildiği gibi: + +
+ +Başkalarının daha önceki çalışmaları olmasaydı, **FastAPI** var olmazdı. + +Geçmişte oluşturulan pek çok araç **FastAPI**'a ilham kaynağı olmuştur. + +Yıllardır yeni bir framework oluşturmaktan kaçınıyordum. Başlangıçta **FastAPI**'ın çözdüğü sorunları çözebilmek için pek çok farklı framework, eklenti ve araç kullanmayı denedim. + +Ancak bir noktada, geçmişteki diğer araçlardan en iyi fikirleri alarak bütün bu çözümleri kapsayan, ayrıca bütün bunları Python'ın daha önce mevcut olmayan özelliklerini (Python 3.6+ ile gelen tip belirteçleri) kullanarak yapan bir şey üretmekten başka bir seçenek kalmamıştı. + +
+ +## Araştırma + +Önceki alternatifleri kullanarak hepsinden bir şeyler öğrenip, fikirler alıp, bunları kendim ve çalıştığım geliştirici ekipler için en iyi şekilde birleştirebilme şansım oldu. + +Mesela, ideal olarak standart Python tip belirteçlerine dayanması gerektiği açıktı. + +Ayrıca, en iyi yaklaşım zaten mevcut olan standartları kullanmaktı. + +Sonuç olarak, **FastAPI**'ı kodlamaya başlamadan önce, birkaç ay boyunca OpenAPI, JSON Schema, OAuth2 ve benzerlerinin tanımlamalarını inceledim. İlişkilerini, örtüştükleri noktaları ve farklılıklarını anlamaya çalıştım. + +## Tasarım + +Sonrasında, (**FastAPI** kullanan bir geliştirici olarak) sahip olmak istediğim "API"ı tasarlamak için biraz zaman harcadım. + +Çeşitli fikirleri en popüler Python editörlerinde test ettim: PyCharm, VS Code, Jedi tabanlı editörler. + +Bu test, en son Python Developer Survey'ine göre, kullanıcıların yaklaşık %80'inin kullandığı editörleri kapsıyor. + +Bu da demek oluyor ki **FastAPI**, Python geliştiricilerinin %80'inin kullandığı editörlerle test edildi. Ve diğer editörlerin çoğu benzer şekilde çalıştığından, avantajları neredeyse tüm editörlerde çalışacaktır. + +Bu şekilde, kod tekrarını mümkün olduğunca azaltmak, her yerde otomatik tamamlama, tip ve hata kontrollerine sahip olmak için en iyi yolları bulabildim. + +Hepsi, tüm geliştiriciler için en iyi geliştirme deneyimini sağlayacak şekilde. + +## Gereksinimler + +Çeşitli alternatifleri test ettikten sonra, avantajlarından dolayı **Pydantic**'i kullanmaya karar verdim. + +Sonra, JSON Schema ile tamamen uyumlu olmasını sağlamak, kısıtlama bildirimlerini tanımlamanın farklı yollarını desteklemek ve birkaç editördeki testlere dayanarak editör desteğini (tip kontrolleri, otomatik tamamlama) geliştirmek için katkıda bulundum. + +Geliştirme sırasında, diğer ana gereksinim olan **Starlette**'e de katkıda bulundum. + +## Geliştirme + +**FastAPI**'ı oluşturmaya başladığımda, parçaların çoğu zaten yerindeydi, tasarım tanımlanmıştı, gereksinimler ve araçlar hazırdı, standartlar ve tanımlamalar hakkındaki bilgi net ve tazeydi. + +## Gelecek + +Şimdiye kadar, **FastAPI**'ın fikirleriyle birçok kişiye faydalı olduğu apaçık ortada. + +Birçok kullanım durumuna daha iyi uyduğu için, önceki alternatiflerin yerine seçiliyor. + +Ben ve ekibim dahil, birçok geliştirici ve ekip projelerinde **FastAPI**'ya bağlı. + +Tabi, geliştirilecek birçok özellik ve iyileştirme mevcut. + +**FastAPI**'ın önünde harika bir gelecek var. + +[Yardımlarınız](help-fastapi.md){.internal-link target=_blank} çok değerlidir. diff --git a/docs/tr/docs/how-to/index.md b/docs/tr/docs/how-to/index.md new file mode 100644 index 0000000000000..8ece2951580bd --- /dev/null +++ b/docs/tr/docs/how-to/index.md @@ -0,0 +1,11 @@ +# Nasıl Yapılır - Tarifler + +Burada çeşitli konular hakkında farklı tarifler veya "nasıl yapılır" kılavuzları yer alıyor. + +Bu fikirlerin büyük bir kısmı aşağı yukarı **bağımsız** olacaktır, çoğu durumda bunları sadece **projenize** hitap ediyorsa incelemelisiniz. + +Projeniz için ilginç ve yararlı görünen bir şey varsa devam edin ve inceleyin, aksi halde bunları atlayabilirsiniz. + +!!! tip "İpucu" + + **FastAPI**'ı düzgün (ve önerilen) şekilde öğrenmek istiyorsanız [Öğretici - Kullanıcı Rehberi](../tutorial/index.md){.internal-link target=_blank}'ni bölüm bölüm okuyun. diff --git a/docs/tr/docs/index.md b/docs/tr/docs/index.md index 2339337f341c6..afbb27f7dfc24 100644 --- a/docs/tr/docs/index.md +++ b/docs/tr/docs/index.md @@ -1,50 +1,48 @@ - -{!../../../docs/missing-translation.md!} - -

FastAPI

- FastAPI framework, yüksek performanslı, öğrenmesi kolay, geliştirmesi hızlı, kullanıma sunulmaya hazır. + FastAPI framework, yüksek performanslı, öğrenmesi oldukça kolay, kodlaması hızlı, kullanıma hazır

- - Test + + Test - - Coverage + + Coverage Package version + + Supported Python versions +

--- -**dokümantasyon**: https://fastapi.tiangolo.com +**Dokümantasyon**: https://fastapi.tiangolo.com -**Kaynak kodu**: https://github.com/tiangolo/fastapi +**Kaynak Kod**: https://github.com/tiangolo/fastapi --- -FastAPI, Python 3.6+'nın standart type hintlerine dayanan modern ve hızlı (yüksek performanslı) API'lar oluşturmak için kullanılabilecek web framework'ü. - -Ana özellikleri: +FastAPI, Python 3.8+'nin standart tip belirteçlerine dayalı, modern ve hızlı (yüksek performanslı) API'lar oluşturmak için kullanılabilecek web framework'tür. -* **Hızlı**: çok yüksek performanslı, **NodeJS** ve **Go** ile eşdeğer seviyede performans sağlıyor, (Starlette ve Pydantic sayesinde.) [Python'un en hızlı frameworklerinden bir tanesi.](#performans). -* **Kodlaması hızlı**: Yeni özellikler geliştirmek neredeyse %200 - %300 daha hızlı. * -* **Daha az bug**: Geliştirici (insan) kaynaklı hatalar neredeyse %40 azaltıldı. * -* **Sezgileri güçlü**: Editor (otomatik-tamamlama) desteği harika. Otomatik tamamlama her yerde. Debuglamak ile daha az zaman harcayacaksınız. -* **Kolay**: Öğrenmesi ve kullanması kolay olacak şekilde. Doküman okumak için harcayacağınız süre azaltıldı. -* **Kısa**: Kod tekrarını minimuma indirdik. Fonksiyon parametrelerinin tiplerini belirtmede farklı yollar sunarak karşılaşacağınız bug'ları azalttık. -* **Güçlü**: Otomatik dokümantasyon ile beraber, kullanıma hazır kod yaz. +Temel özellikleri şunlardır: -* **Standartlar belirli**: Tamamiyle API'ların açık standartlara bağlı ve (tam uyumlululuk içerisinde); OpenAPI (eski adıyla Swagger) ve JSON Schema. +* **Hızlı**: Çok yüksek performanslı, **NodeJS** ve **Go** ile eşit düzeyde (Starlette ve Pydantic sayesinde). [En hızlı Python framework'lerinden bir tanesidir](#performans). +* **Kodlaması Hızlı**: Geliştirme hızını yaklaşık %200 ile %300 aralığında arttırır. * +* **Daha az hata**: İnsan (geliştirici) kaynaklı hataları yaklaşık %40 azaltır. * +* **Sezgisel**: Muhteşem bir editör desteği. Her yerde otomatik tamamlama. Hata ayıklama ile daha az zaman harcayacaksınız. +* **Kolay**: Öğrenmesi ve kullanması kolay olacak şekilde tasarlandı. Doküman okuma ile daha az zaman harcayacaksınız. +* **Kısa**: Kod tekrarı minimize edildi. Her parametre tanımlamasında birden fazla özellik ve daha az hatayla karşılaşacaksınız. +* **Güçlü**: Otomatik ve etkileşimli dokümantasyon ile birlikte, kullanıma hazır kod elde edebilirsiniz. +* **Standard öncelikli**: API'lar için açık standartlara dayalı (ve tamamen uyumlu); OpenAPI (eski adıyla Swagger) ve JSON Schema. -* Bahsi geçen rakamsal ifadeler tamamiyle, geliştirme takımının kendi sundukları ürünü geliştirirken yaptıkları testlere dayanmakta. +* ilgili kanılar, dahili geliştirme ekibinin geliştirdikleri ürünlere yaptıkları testlere dayanmaktadır. -## Sponsors +## Sponsorlar @@ -59,74 +57,72 @@ Ana özellikleri: -Other sponsors +Diğer Sponsorlar ## Görüşler - -"_[...] Bugünlerde **FastAPI**'ı çok fazla kullanıyorum [...] Aslına bakarsanız **Microsoft'taki Machine Learning servislerimizin** hepsinde kullanmayı düşünüyorum. FastAPI ile geliştirdiğimiz servislerin bazıları çoktan **Windows**'un ana ürünlerine ve **Office** ürünlerine entegre edilmeye başlandı bile._" +"_[...] Bugünlerde **FastAPI**'ı çok fazla kullanıyorum. [...] Aslında bunu ekibimin **Microsoft'taki Machine Learning servislerinin** tamamında kullanmayı planlıyorum. Bunlardan bazıları **Windows**'un ana ürünlerine ve **Office** ürünlerine entegre ediliyor._"
Kabir Khan - Microsoft (ref)
--- - -"_**FastAPI**'ı **tahminlerimiz**'i sorgulanabilir hale getirmek için **REST** mimarisı ile beraber server üzerinde kullanmaya başladık._" - +"_**FastAPI**'ı **tahminlerimiz**'i sorgulanabilir hale getirecek bir **REST** sunucu oluşturmak için benimsedik/kullanmaya başladık._"
Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala - Uber (ref)
--- - -"_**Netflix** **kriz yönetiminde** orkestrasyon yapabilmek için geliştirdiği yeni framework'ü **Dispatch**'in, açık kaynak versiyonunu paylaşmaktan gurur duyuyor. [**FastAPI** ile yapıldı.]_" +"_**Netflix**, **kriz yönetiminde** orkestrasyon yapabilmek için geliştirdiği yeni framework'ü **Dispatch**'in, açık kaynak sürümünü paylaşmaktan gurur duyuyor. [**FastAPI** ile yapıldı.]_"
Kevin Glisson, Marc Vilanova, Forest Monsen - Netflix (ref)
--- - "_**FastAPI** için ayın üzerindeymişcesine heyecanlıyım. Çok eğlenceli!_" -
Brian Okken - Python Bytes podcast host (ref)
--- -"_Dürüst olmak gerekirse, geliştirdiğin şey bir çok açıdan çok sağlam ve parlak gözüküyor. Açıkcası benim **Hug**'ı tasarlarken yapmaya çalıştığım şey buydu - bunu birisinin başardığını görmek gerçekten çok ilham verici._" +"_Dürüst olmak gerekirse, inşa ettiğiniz şey gerçekten sağlam ve profesyonel görünüyor. Birçok açıdan **Hug**'ın olmasını istediğim şey tam da bu - böyle bir şeyi inşa eden birini görmek gerçekten ilham verici._" -
Timothy Crosley - Hug'ın Yaratıcısı (ref)
+
Timothy Crosley - Hug'ın Yaratıcısı (ref)
--- -"_Eğer REST API geliştirmek için **modern bir framework** öğrenme arayışında isen, **FastAPI**'a bir göz at [...] Hızlı, kullanımı ve öğrenmesi kolay. [...]_" +"_Eğer REST API geliştirmek için **modern bir framework** öğrenme arayışında isen, **FastAPI**'a bir göz at [...] Hızlı, kullanımı ve öğrenmesi kolay. [...]_" -"_Biz **API** servislerimizi **FastAPI**'a geçirdik [...] Sizin de beğeneceğinizi düşünüyoruz. [...]_" +"_**API** servislerimizi **FastAPI**'a taşıdık [...] Sizin de beğeneceğinizi düşünüyoruz. [...]_" +
Ines Montani - Matthew Honnibal - Explosion AI kurucuları - spaCy yaratıcıları (ref) - (ref)
+ +--- +"_Python ile kullanıma hazır bir API oluşturmak isteyen herhangi biri için, **FastAPI**'ı şiddetle tavsiye ederim. **Harika tasarlanmış**, **kullanımı kolay** ve **yüksek ölçeklenebilir**, API odaklı geliştirme stratejimizin **ana bileşeni** haline geldi ve Virtual TAC Engineer gibi birçok otomasyon ve servisi yönetiyor._" -
Ines Montani - Matthew Honnibal - Explosion AI kurucuları - spaCy yaratıcıları (ref) - (ref)
+
Deon Pillsbury - Cisco (ref)
--- -## **Typer**, komut satırı uygulamalarının FastAPI'ı +## Komut Satırı Uygulamalarının FastAPI'ı: **Typer** -Eğer API yerine komut satırı uygulaması geliştiriyor isen **Typer**'a bir göz at. +Eğer API yerine, terminalde kullanılmak üzere bir komut satırı uygulaması geliştiriyorsanız **Typer**'a göz atabilirsiniz. -**Typer** kısaca FastAPI'ın küçük kız kardeşi. Komut satırı uygulamalarının **FastAPI'ı** olması hedeflendi. ⌨️ 🚀 +**Typer** kısaca FastAPI'ın küçük kardeşi. Ve hedefi komut satırı uygulamalarının **FastAPI'ı** olmak. ⌨️ 🚀 ## Gereksinimler -Python 3.7+ +Python 3.8+ FastAPI iki devin omuzları üstünde duruyor: * Web tarafı için Starlette. -* Data tarafı için Pydantic. +* Data tarafı için Pydantic. -## Yükleme +## Kurulum
@@ -138,7 +134,7 @@ $ pip install fastapi
-Uygulamanı kullanılabilir hale getirmek için Uvicorn ya da Hypercorn gibi bir ASGI serverına ihtiyacın olacak. +Uygulamamızı kullanılabilir hale getirmek için Uvicorn ya da Hypercorn gibi bir ASGI sunucusuna ihtiyacımız olacak.
@@ -152,9 +148,9 @@ $ pip install "uvicorn[standard]" ## Örnek -### Şimdi dene +### Kodu Oluşturalım -* `main.py` adında bir dosya oluştur : +* `main.py` adında bir dosya oluşturup içine şu kodu yapıştıralım: ```Python from typing import Union @@ -177,9 +173,9 @@ def read_item(item_id: int, q: Union[str, None] = None):
Ya da async def... -Eğer kodunda `async` / `await` var ise, `async def` kullan: +Eğer kodunuzda `async` / `await` varsa, `async def` kullanalım: -```Python hl_lines="9 14" +```Python hl_lines="9 14" from typing import Union from fastapi import FastAPI @@ -199,13 +195,13 @@ async def read_item(item_id: int, q: Union[str, None] = None): **Not**: -Eğer ne olduğunu bilmiyor isen _"Acelen mi var?"_ kısmını oku `async` ve `await`. +Eğer bu konu hakkında bilginiz yoksa `async` ve `await` dokümantasyonundaki _"Aceleniz mi var?"_ kısmını kontrol edebilirsiniz.
-### Çalıştır +### Kodu Çalıştıralım -Serverı aşağıdaki komut ile çalıştır: +Sunucuyu aşağıdaki komutla çalıştıralım:
@@ -222,56 +218,56 @@ INFO: Application startup complete.
-Çalıştırdığımız uvicorn main:app --reload hakkında... +uvicorn main:app --reload komutuyla ilgili... -`uvicorn main:app` şunları ifade ediyor: +`uvicorn main:app` komutunu şu şekilde açıklayabiliriz: * `main`: dosya olan `main.py` (yani Python "modülü"). -* `app`: ise `main.py` dosyasının içerisinde oluşturduğumuz `app = FastAPI()` 'a denk geliyor. -* `--reload`: ise kodda herhangi bir değişiklik yaptığımızda serverın yapılan değişiklerileri algılayıp, değişiklikleri siz herhangi bir şey yapmadan uygulamasını sağlıyor. +* `app`: ise `main.py` dosyasının içerisinde `app = FastAPI()` satırında oluşturduğumuz `FastAPI` nesnesi. +* `--reload`: kod değişikliklerinin ardından sunucuyu otomatik olarak yeniden başlatır. Bu parameteyi sadece geliştirme aşamasında kullanmalıyız.
-### Dokümantasyonu kontrol et +### Şimdi de Kontrol Edelim -Browserını aç ve şu linke git http://127.0.0.1:8000/items/5?q=somequery. +Tarayıcımızda şu bağlantıyı açalım http://127.0.0.1:8000/items/5?q=somequery. -Bir JSON yanıtı göreceksin: +Aşağıdaki gibi bir JSON yanıtıyla karşılaşacağız: ```JSON {"item_id": 5, "q": "somequery"} ``` -Az önce oluşturduğun API: +Az önce oluşturduğumuz API: -* `/` ve `/items/{item_id}` adreslerine HTTP talebi alabilir hale geldi. -* İki _adresde_ `GET` operasyonlarını (HTTP _metodları_ olarakta bilinen) yapabilir hale geldi. -* `/items/{item_id}` _adresi_ ayrıca bir `item_id` _adres parametresine_ sahip ve bu bir `int` olmak zorunda. -* `/items/{item_id}` _adresi_ opsiyonel bir `str` _sorgu paramtersine_ sahip bu da `q`. +* `/` ve `/items/{item_id}` _yollarına_ HTTP isteği alabilir. +* İki _yolda_ `GET` operasyonlarını (HTTP _metodları_ olarak da bilinen) kabul ediyor. +* `/items/{item_id}` _yolu_ `item_id` adında bir _yol parametresine_ sahip ve bu parametre `int` değer almak zorundadır. +* `/items/{item_id}` _yolu_ `q` adında bir _yol parametresine_ sahip ve bu parametre opsiyonel olmakla birlikte, `str` değer almak zorundadır. -### İnteraktif API dokümantasyonu +### Etkileşimli API Dokümantasyonu -Şimdi http://127.0.0.1:8000/docs adresine git. +Şimdi http://127.0.0.1:8000/docs bağlantısını açalım. -Senin için otomatik oluşturulmuş(Swagger UI tarafından sağlanan) interaktif bir API dokümanı göreceksin: +Swagger UI tarafından sağlanan otomatik etkileşimli bir API dokümantasyonu göreceğiz: ![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) -### Alternatif API dokümantasyonu +### Alternatif API Dokümantasyonu -Şimdi http://127.0.0.1:8000/redoc adresine git. +Şimdi http://127.0.0.1:8000/redoc bağlantısını açalım. -Senin için alternatif olarak (ReDoc tarafından sağlanan) bir API dokümantasyonu daha göreceksin: +ReDoc tarafından sağlanan otomatik dokümantasyonu göreceğiz: ![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) -## Örnek bir değişiklik +## Örneği Güncelleyelim -Şimdi `main.py` dosyasını değiştirelim ve body ile `PUT` talebi alabilir hale getirelim. +Şimdi `main.py` dosyasını, `PUT` isteğiyle birlikte bir gövde alacak şekilde değiştirelim. -Şimdi Pydantic sayesinde, Python'un standart tiplerini kullanarak bir body tanımlayacağız. +Gövdeyi Pydantic sayesinde standart python tiplerini kullanarak tanımlayalım. -```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 @@ -301,41 +297,41 @@ def update_item(item_id: int, item: Item): return {"item_name": item.name, "item_id": item_id} ``` -Server otomatik olarak yeniden başlamalı (çünkü yukarıda `uvicorn`'u çalıştırırken `--reload` parametresini kullandık.). +Sunucu otomatik olarak yeniden başlamış olmalı (çünkü yukarıda `uvicorn` komutuyla birlikte `--reload` parametresini kullandık). -### İnteraktif API dokümantasyonu'nda değiştirme yapmak +### Etkileşimli API Dokümantasyonundaki Değişimi Görelim -Şimdi http://127.0.0.1:8000/docs bağlantısına tekrar git. +Şimdi http://127.0.0.1:8000/docs bağlantısına tekrar gidelim. -* İnteraktif API dokümantasyonu, yeni body ile beraber çoktan yenilenmiş olması lazım: +* Etkileşimli API dokümantasyonu, yeni gövdede dahil olmak üzere otomatik olarak güncellenmiş olacak: ![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) -* "Try it out"a tıkla, bu senin API parametleri üzerinde deneme yapabilmene izin veriyor: +* "Try it out" butonuna tıklayalım, bu işlem API parametleri üzerinde değişiklik yapmamıza ve doğrudan API ile etkileşime geçmemize imkan sağlayacak: ![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png) -* Şimdi "Execute" butonuna tıkla, kullanıcı arayüzü otomatik olarak API'ın ile bağlantı kurarak ona bu parametreleri gönderecek ve sonucu karşına getirecek. +* Şimdi "Execute" butonuna tıklayalım, kullanıcı arayüzü API'ımız ile bağlantı kurup parametreleri gönderecek ve sonucu ekranımıza getirecek: ![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png) -### Alternatif API dokümantasyonunda değiştirmek +### Alternatif API Dokümantasyonundaki Değişimi Görelim -Şimdi ise http://127.0.0.1:8000/redoc adresine git. +Şimdi ise http://127.0.0.1:8000/redoc bağlantısına tekrar gidelim. -* Alternatif dokümantasyonda koddaki değişimler ile beraber kendini yeni query ve body ile güncelledi. +* Alternatif dokümantasyonda yaptığımız değişiklikler ile birlikte yeni sorgu parametresi ve gövde bilgisi ile güncelemiş olacak: ![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) ### Özet -Özetleyecek olursak, URL, sorgu veya request body'deki parametrelerini fonksiyon parametresi olarak kullanıyorsun. Bu parametrelerin veri tiplerini bir kere belirtmen yeterli. +Özetlemek gerekirse, parametrelerin, gövdenin, vb. veri tiplerini fonksiyon parametreleri olarak **bir kere** tanımlıyoruz. -Type-hinting işlemini Python dilindeki standart veri tipleri ile yapabilirsin +Bu işlemi standart modern Python tipleriyle yapıyoruz. -Yeni bir syntax'e alışmana gerek yok, metodlar ve classlar zaten spesifik kütüphanelere ait. +Yeni bir sözdizimi yapısını, bir kütüphane özel metod veya sınıfları öğrenmeye gerek yoktur. -Sadece standart **Python 3.6+**. +Hepsi sadece **Python 3.8+** standartlarına dayalıdır. Örnek olarak, `int` tanımlamak için: @@ -343,64 +339,64 @@ Sadece standart **Python 3.6+**. item_id: int ``` -ya da daha kompleks `Item` tipi: +ya da daha kompleks herhangi bir python modelini tanımlayabiliriz, örneğin `Item` modeli için: ```Python item: Item ``` -...sadece kısa bir parametre tipi belirtmekle beraber, sahip olacakların: +...ve sadece kısa bir parametre tipi belirterek elde ettiklerimiz: -* Editör desteği dahil olmak üzere: +* Editör desteğiyle birlikte: * Otomatik tamamlama. - * Tip sorguları. -* Datanın tipe uyumunun sorgulanması: - * Eğer data geçersiz ise, otomatik olarak hataları ayıklar. - * Çok derin JSON objelerinde bile veri tipi sorgusu yapar. -* Gelen verinin dönüşümünü aşağıdaki veri tiplerini kullanarak gerçekleştirebiliyor. + * Tip kontrolü. +* Veri Doğrulama: + * Veri geçerli değilse, otomatik olarak açıklayıcı hatalar gösterir. + * Çok derin JSON nesnelerinde bile doğrulama yapar. +* Gelen verinin dönüşümünü aşağıdaki veri tiplerini kullanarak gerçekleştirir: * JSON. - * Path parametreleri. - * Query parametreleri. - * Cookies. + * Yol parametreleri. + * Sorgu parametreleri. + * Çerezler. * Headers. - * Forms. - * Files. -* Giden verinin dönüşümünü aşağıdaki veri tiplerini kullanarak gerçekleştirebiliyor (JSON olarak): - * Python tiplerinin (`str`, `int`, `float`, `bool`, `list`, vs) çevirisi. - * `datetime` objesi. - * `UUID` objesi. + * Formlar. + * Dosyalar. +* Giden verinin dönüşümünü aşağıdaki veri tiplerini kullanarak gerçekleştirir (JSON olarak): + * Python tiplerinin (`str`, `int`, `float`, `bool`, `list`, vb) dönüşümü. + * `datetime` nesnesi. + * `UUID` nesnesi. * Veritabanı modelleri. - * ve daha fazlası... -* 2 alternatif kullanıcı arayüzü dahil olmak üzere, otomatik interaktif API dokümanu: + * ve çok daha fazlası... +* 2 alternatif kullanıcı arayüzü dahil olmak üzere, otomatik etkileşimli API dokümantasyonu sağlar: * Swagger UI. * ReDoc. --- -Az önceki kod örneğine geri dönelim, **FastAPI**'ın yapacaklarına bir bakış atalım: +Az önceki örneğe geri dönelim, **FastAPI**'ın yapacaklarına bir bakış atalım: -* `item_id`'nin `GET` ve `PUT` talepleri içinde olup olmadığının doğruluğunu kontol edecek. -* `item_id`'nin tipinin `int` olduğunu `GET` ve `PUT` talepleri içinde olup olmadığının doğruluğunu kontol edecek. - * Eğer `GET` ve `PUT` içinde yok ise ve `int` değil ise, sebebini belirten bir hata mesajı gösterecek -* Opsiyonel bir `q` parametresinin `GET` talebi için (`http://127.0.0.1:8000/items/foo?q=somequery` içinde) olup olmadığını kontrol edecek +* `item_id`'nin `GET` ve `PUT` istekleri için, yolda olup olmadığının kontol edecek. +* `item_id`'nin `GET` ve `PUT` istekleri için, tipinin `int` olduğunu doğrulayacak. + * Eğer değilse, sebebini belirten bir hata mesajı gösterecek. +* Opsiyonel bir `q` parametresinin `GET` isteği içinde (`http://127.0.0.1:8000/items/foo?q=somequery` gibi) olup olmadığını kontrol edecek * `q` parametresini `= None` ile oluşturduğumuz için, opsiyonel bir parametre olacak. - * Eğer `None` olmasa zorunlu bir parametre olacak idi (bu yüzden body'de `PUT` parametresi var). -* `PUT` talebi için `/items/{item_id}`'nin body'sini, JSON olarak okuyor: - * `name` adında bir parametetre olup olmadığını ve var ise onun `str` olup olmadığını kontol ediyor. - * `price` adında bir parametetre olup olmadığını ve var ise onun `float` olup olmadığını kontol ediyor. - * `is_offer` adında bir parametetre olup olmadığını ve var ise onun `bool` olup olmadığını kontol ediyor. - * Bunların hepsini en derin JSON modellerinde bile yapacaktır. -* Bütün veri tiplerini otomatik olarak JSON'a çeviriyor veya tam tersi. -* Her şeyi dokümanlayıp, çeşitli yerlerde: - * İnteraktif dokümantasyon sistemleri. - * Otomatik alıcı kodu üretim sistemlerinde ve çeşitli dillerde. -* İki ayrı web arayüzüyle direkt olarak interaktif bir dokümantasyon sunuyor. + * Eğer `None` olmasa zorunlu bir parametre olacaktı (`PUT` metodunun gövdesinde olduğu gibi). +* `PUT` isteği için `/items/{item_id}`'nin gövdesini, JSON olarak doğrulayıp okuyacak: + * `name` adında zorunlu bir parametre olup olmadığını ve varsa tipinin `str` olup olmadığını kontol edecek. + * `price` adında zorunlu bir parametre olup olmadığını ve varsa tipinin `float` olup olmadığını kontol edecek. + * `is_offer` adında opsiyonel bir parametre olup olmadığını ve varsa tipinin `float` olup olmadığını kontol edecek. + * Bunların hepsi en derin JSON nesnelerinde bile çalışacak. +* Verilerin JSON'a ve JSON'ın python nesnesine dönüşümü otomatik olarak yapılacak. +* Her şeyi OpenAPI ile uyumlu bir şekilde otomatik olarak dokümanlayacak ve bunlarda aşağıdaki gibi kullanılabilecek: + * Etkileşimli dokümantasyon sistemleri. + * Bir çok programlama dili için otomatik istemci kodu üretim sistemleri. +* İki ayrı etkileşimli dokümantasyon arayüzünü doğrudan sağlayacak. --- -Henüz yüzeysel bir bakış attık, fakat sen çoktan çalışma mantığını anladın. +Daha yeni başladık ama çalışma mantığını çoktan anlamış oldunuz. -Şimdi aşağıdaki satırı değiştirmeyi dene: +Şimdi aşağıdaki satırı değiştirmeyi deneyin: ```Python return {"item_name": item.name, "item_id": item_id} @@ -418,22 +414,22 @@ Henüz yüzeysel bir bakış attık, fakat sen çoktan çalışma mantığını ... "item_price": item.price ... ``` -...şimdi editör desteğinin nasıl veri tiplerini bildiğini ve otomatik tamamladığını gör: +...ve editörünün veri tiplerini bildiğini ve otomatik tamamladığını göreceksiniz: ![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) -Daha fazla örnek ve özellik için Tutorial - User Guide sayfasını git. +Daha fazal özellik içeren, daha eksiksiz bir örnek için Öğretici - Kullanıcı Rehberi sayfasını ziyaret edebilirsin. -**Spoiler**: Öğretici - Kullanıcı rehberi şunları içeriyor: +**Spoiler**: Öğretici - Kullanıcı rehberi şunları içerir: -* **Parameterlerini** nasıl **headers**, **cookies**, **form fields** ve **files** olarak deklare edebileceğini. -* `maximum_length` ya da `regex` gibi şeylerle nasıl **doğrulama** yapabileceğini. -* Çok güçlü ve kullanımı kolay **Zorunluluk Entegrasyonu** oluşturmayı. -* Güvenlik ve kimlik doğrulama, **JWT tokenleri**'yle beraber **OAuth2** desteği, ve **HTTP Basic** doğrulaması. -* İleri seviye fakat ona göre oldukça basit olan **derince oluşturulmuş JSON modelleri** (Pydantic sayesinde). +* **Parameterlerin**, **headers**, **çerezler**, **form alanları** ve **dosyalar** olarak tanımlanması. +* `maximum_length` ya da `regex` gibi **doğrulama kısıtlamalarının** nasıl yapılabileceği. +* Çok güçlü ve kullanımı kolay **Bağımlılık Enjeksiyonu** sistemi oluşturmayı. +* Güvenlik ve kimlik doğrulama, **JWT tokenleri** ile **OAuth2** desteği, ve **HTTP Basic** doğrulaması. +* İleri seviye fakat bir o kadarda basit olan **çok derin JSON modelleri** (Pydantic sayesinde). +* **GraphQL** entegrasyonu: Strawberry ve diğer kütüphaneleri kullanarak. * Diğer ekstra özellikler (Starlette sayesinde): - * **WebSockets** - * **GraphQL** + * **WebSocketler** * HTTPX ve `pytest` sayesinde aşırı kolay testler. * **CORS** * **Cookie Sessions** @@ -441,33 +437,34 @@ Daha fazla örnek ve özellik için Python'un en hızlı frameworklerinden birisi , sadece Starlette ve Uvicorn'dan daha yavaş ki FastAPI bunların üzerine kurulu. +Bağımsız TechEmpower kıyaslamaları gösteriyor ki, Uvicorn ile çalıştırılan **FastAPI** uygulamaları en hızlı Python framework'lerinden birisi, sadece Starlette ve Uvicorn'dan yavaş, ki FastAPI bunların üzerine kurulu bir kütüphanedir. -Daha fazla bilgi için, bu bölüme bir göz at Benchmarks. +Daha fazla bilgi için, bu bölüme bir göz at Kıyaslamalar. -## Opsiyonel gereksinimler +## Opsiyonel Gereksinimler Pydantic tarafında kullanılan: * email_validator - email doğrulaması için. +* pydantic-settings - ayar yönetimi için. +* pydantic-extra-types - Pydantic ile birlikte kullanılabilecek ek tipler için. Starlette tarafında kullanılan: -* httpx - Eğer `TestClient` kullanmak istiyorsan gerekli. -* jinja2 - Eğer kendine ait template konfigürasyonu oluşturmak istiyorsan gerekli -* python-multipart - Form kullanmak istiyorsan gerekli ("dönüşümü"). +* httpx - Eğer `TestClient` yapısını kullanacaksanız gereklidir. +* jinja2 - Eğer varsayılan template konfigürasyonunu kullanacaksanız gereklidir. +* python-multipart - Eğer `request.form()` ile form dönüşümü desteğini kullanacaksanız gereklidir. * itsdangerous - `SessionMiddleware` desteği için gerekli. * pyyaml - `SchemaGenerator` desteği için gerekli (Muhtemelen FastAPI kullanırken ihtiyacınız olmaz). -* graphene - `GraphQLApp` desteği için gerekli. -* ujson - `UJSONResponse` kullanmak istiyorsan gerekli. +* ujson - `UJSONResponse` kullanacaksanız gerekli. Hem FastAPI hem de Starlette tarafından kullanılan: -* uvicorn - oluşturduğumuz uygulamayı bir web sunucusuna servis etmek için gerekli -* orjson - `ORJSONResponse` kullanmak istiyor isen gerekli. +* uvicorn - oluşturduğumuz uygulamayı servis edecek web sunucusu görevini üstlenir. +* orjson - `ORJSONResponse` kullanacaksanız gereklidir. Bunların hepsini `pip install fastapi[all]` ile yükleyebilirsin. ## Lisans -Bu proje, MIT lisansı şartlarına göre lisanslanmıştır. +Bu proje, MIT lisansı şartları altında lisanslanmıştır. diff --git a/docs/tr/docs/learn/index.md b/docs/tr/docs/learn/index.md new file mode 100644 index 0000000000000..52e3aa54df9f5 --- /dev/null +++ b/docs/tr/docs/learn/index.md @@ -0,0 +1,5 @@ +# Öğren + +**FastAPI** öğrenmek için giriş bölümleri ve öğreticiler burada yer alıyor. + +Burayı, bir **kitap**, bir **kurs**, ve FastAPI öğrenmenin **resmi** ve önerilen yolu olarak düşünülebilirsiniz. 😎 diff --git a/docs/tr/docs/newsletter.md b/docs/tr/docs/newsletter.md new file mode 100644 index 0000000000000..22ca1b1e2949e --- /dev/null +++ b/docs/tr/docs/newsletter.md @@ -0,0 +1,5 @@ +# FastAPI ve Arkadaşları Bülteni + + + + diff --git a/docs/tr/docs/project-generation.md b/docs/tr/docs/project-generation.md new file mode 100644 index 0000000000000..75e3ae3397fd4 --- /dev/null +++ b/docs/tr/docs/project-generation.md @@ -0,0 +1,84 @@ +# Proje oluşturma - Şablonlar + +Başlamak için bir proje oluşturucu kullanabilirsiniz, çünkü sizin için önceden yapılmış birçok başlangıç ​​kurulumu, güvenlik, veritabanı ve temel API endpoinlerini içerir. + +Bir proje oluşturucu, her zaman kendi ihtiyaçlarınıza göre güncellemeniz ve uyarlamanız gereken esnek bir kuruluma sahip olacaktır, ancak bu, projeniz için iyi bir başlangıç ​​noktası olabilir. + +## Full Stack FastAPI PostgreSQL + +GitHub: https://github.com/tiangolo/full-stack-fastapi-postgresql + +### Full Stack FastAPI PostgreSQL - Özellikler + +* Full **Docker** entegrasyonu (Docker based). +* Docker Swarm Mode ile deployment. +* **Docker Compose** entegrasyonu ve lokal geliştirme için optimizasyon. +* Uvicorn ve Gunicorn ile **Production ready** Python web server'ı. +* Python **FastAPI** backend: + * **Hızlı**: **NodeJS** ve **Go** ile eşit, çok yüksek performans (Starlette ve Pydantic'e teşekkürler). + * **Sezgisel**: Editor desteğı. Otomatik tamamlama. Daha az debugging. + * **Kolay**: Kolay öğrenip kolay kullanmak için tasarlandı. Daha az döküman okuma daha çok iş. + * **Kısa**: Minimum kod tekrarı. Her parametre bildiriminde birden çok özellik. + * **Güçlü**: Production-ready. Otomatik interaktif dökümantasyon. + * **Standartlara dayalı**: API'ler için açık standartlara dayanır (ve tamamen uyumludur): OpenAPI ve JSON Şeması. + * **Birçok diger özelliği** dahili otomatik doğrulama, serialization, interaktif dokümantasyon, OAuth2 JWT token ile authentication, vb. +* **Güvenli şifreleme** . +* **JWT token** kimlik doğrulama. +* **SQLAlchemy** models (Flask dan bağımsızdır. Celery worker'ları ile kullanılabilir). +* Kullanıcılar için temel başlangıç ​​modeli (gerektiği gibi değiştirin ve kaldırın). +* **Alembic** migration. +* **CORS** (Cross Origin Resource Sharing). +* **Celery** worker'ları ile backend içerisinden seçilen işleri çalıştırabilirsiniz. +* **Pytest**'e dayalı, Docker ile entegre REST backend testleri ile veritabanından bağımsız olarak tam API etkileşimini test edebilirsiniz. Docker'da çalıştığı için her seferinde sıfırdan yeni bir veri deposu oluşturabilir (böylece ElasticSearch, MongoDB, CouchDB veya ne istersen kullanabilirsin ve sadece API'nin çalışıp çalışmadığını test edebilirsin). +* Atom Hydrogen veya Visual Studio Code Jupyter gibi uzantılarla uzaktan veya Docker içi geliştirme için **Jupyter Çekirdekleri** ile kolay Python entegrasyonu. +* **Vue** ile frontend: + * Vue CLI ile oluşturulmuş. + * Dahili **JWT kimlik doğrulama**. + * Dahili Login. + * Login sonrası, Kontrol paneli. + * Kullanıcı oluşturma ve düzenleme kontrol paneli + * Kendi kendine kullanıcı sürümü. + * **Vuex**. + * **Vue-router**. + * **Vuetify** güzel material design kompanentleri için. + * **TypeScript**. + * **Nginx** tabanlı Docker sunucusu (Vue-router için yapılandırılmış). + * Docker ile multi-stage yapı, böylece kodu derlemeniz, kaydetmeniz veya işlemeniz gerekmez. + * Derleme zamanında Frontend testi (devre dışı bırakılabilir). + * Mümkün olduğu kadar modüler yapılmıştır, bu nedenle kutudan çıktığı gibi çalışır, ancak Vue CLI ile yeniden oluşturabilir veya ihtiyaç duyduğunuz şekilde oluşturabilir ve istediğinizi yeniden kullanabilirsiniz. +* **PGAdmin** PostgreSQL database admin tool'u, PHPMyAdmin ve MySQL ile kolayca değiştirilebilir. +* **Flower** ile Celery job'larını monitörleme. +* **Traefik** ile backend ve frontend arasında yük dengeleme, böylece her ikisini de aynı domain altında, path ile ayrılmış, ancak farklı kapsayıcılar tarafından sunulabilirsiniz. +* Let's Encrypt **HTTPS** sertifikalarının otomatik oluşturulması dahil olmak üzere Traefik entegrasyonu. +* GitLab **CI** (sürekli entegrasyon), backend ve frontend testi dahil. + +## Full Stack FastAPI Couchbase + +GitHub: https://github.com/tiangolo/full-stack-fastapi-couchbase + +⚠️ **UYARI** ⚠️ + +Sıfırdan bir projeye başlıyorsanız alternatiflerine bakın. + +Örneğin, Full Stack FastAPI PostgreSQL daha iyi bir alternatif olabilir, aktif olarak geliştiriliyor ve kullanılıyor. Ve yeni özellik ve ilerlemelere sahip. + +İsterseniz Couchbase tabanlı generator'ı kullanmakta özgürsünüz, hala iyi çalışıyor olmalı ve onunla oluşturulmuş bir projeniz varsa bu da sorun değil (ve muhtemelen zaten ihtiyaçlarınıza göre güncellediniz). + +Bununla ilgili daha fazla bilgiyi repo belgelerinde okuyabilirsiniz. + +## Full Stack FastAPI MongoDB + +... müsaitliğime ve diğer faktörlere bağlı olarak daha sonra gelebilir. 😅 🎉 + +## Machine Learning modelleri, spaCy ve FastAPI + +GitHub: https://github.com/microsoft/cookiecutter-spacy-fastapi + +### Machine Learning modelleri, spaCy ve FastAPI - Features + +* **spaCy** NER model entegrasyonu. +* **Azure Cognitive Search** yerleşik istek biçimi. +* Uvicorn ve Gunicorn ile **Production ready** Python web server'ı. +* Dahili **Azure DevOps** Kubernetes (AKS) CI/CD deployment. +* **Multilingual**, Proje kurulumu sırasında spaCy'nin yerleşik dillerinden birini kolayca seçin. +* **Esnetilebilir** diğer frameworkler (Pytorch, Tensorflow) ile de çalışır sadece spaCy değil. diff --git a/docs/tr/docs/python-types.md b/docs/tr/docs/python-types.md index 3b9ab905079e5..a0d32c86e5cc6 100644 --- a/docs/tr/docs/python-types.md +++ b/docs/tr/docs/python-types.md @@ -265,7 +265,7 @@ Ve yine bütün editör desteğini alırsınız: ## Pydantic modelleri -Pydantic veri doğrulaması yapmak için bir Python kütüphanesidir. +Pydantic veri doğrulaması yapmak için bir Python kütüphanesidir. Verilerin "biçimini" niteliklere sahip sınıflar olarak düzenlersiniz. @@ -282,7 +282,7 @@ Resmi Pydantic dokümanlarından alınmıştır: ``` !!! info - Daha fazla şey öğrenmek için Pydantic'i takip edin. + Daha fazla şey öğrenmek için Pydantic'i takip edin. **FastAPI** tamamen Pydantic'e dayanmaktadır. diff --git a/docs/tr/docs/resources/index.md b/docs/tr/docs/resources/index.md new file mode 100644 index 0000000000000..fc71a9ca1bd6b --- /dev/null +++ b/docs/tr/docs/resources/index.md @@ -0,0 +1,3 @@ +# Kaynaklar + +Ek kaynaklar, dış bağlantılar, makaleler ve daha fazlası. ✈️ diff --git a/docs/tr/docs/tutorial/first-steps.md b/docs/tr/docs/tutorial/first-steps.md new file mode 100644 index 0000000000000..e66f730342a49 --- /dev/null +++ b/docs/tr/docs/tutorial/first-steps.md @@ -0,0 +1,333 @@ +# İlk Adımlar + +En sade FastAPI dosyası şu şekilde görünür: + +```Python +{!../../../docs_src/first_steps/tutorial001.py!} +``` + +Yukarıdaki içeriği bir `main.py` dosyasına kopyalayalım. + +Uygulamayı çalıştıralım: + +
+ +```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 "Not" + `uvicorn main:app` komutunu şu şekilde açıklayabiliriz: + + * `main`: dosya olan `main.py` (yani Python "modülü"). + * `app`: ise `main.py` dosyasının içerisinde `app = FastAPI()` satırında oluşturduğumuz `FastAPI` nesnesi. + * `--reload`: kod değişikliklerinin ardından sunucuyu otomatik olarak yeniden başlatır. Bu parameteyi sadece geliştirme aşamasında kullanmalıyız. + +Çıktı olarak şöyle bir satır ile karşılaşacaksınız: + +```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 çalıştığı bağlantıyı gösterir. + +### Kontrol Edelim + +Tarayıcınızı açıp http://127.0.0.1:8000 bağlantısına gidin. + +Şu şekilde bir JSON yanıtı ile karşılaşacağız: + +```JSON +{"message": "Hello World"} +``` + +### Etkileşimli API Dokümantasyonu + +Şimdi http://127.0.0.1:8000/docs bağlantısını açalım. + +Swagger UI tarafından sağlanan otomatik etkileşimli bir API dokümantasyonu göreceğiz: + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +### Alternatif API Dokümantasyonu + +Şimdi http://127.0.0.1:8000/redoc bağlantısını açalım. + +ReDoc tarafından sağlanan otomatik dokümantasyonu göreceğiz: + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +### OpenAPI + +**FastAPI**, **OpenAPI** standardını kullanarak tüm API'ınızın tamamını tanımlayan bir "şema" oluşturur. + +#### "Şema" + +"Şema", bir şeyin tanımı veya açıklamasıdır. Geliştirilen koddan ziyade soyut bir açıklamadır. + +#### API "Şeması" + +Bu durumda, OpenAPI, API şemasını nasıl tanımlayacağınızı belirten bir şartnamedir. + +Bu şema tanımı, API yollarınızla birlikte yollarınızın aldığı olası parametreler gibi tanımlamaları içerir. + +#### Veri "Şeması" + +"Şema" terimi, JSON içeriği gibi bazı verilerin şeklini de ifade edebilir. + +Bu durumda, JSON özellikleri ve sahip oldukları veri türleri gibi anlamlarına gelir. + +#### OpenAPI ve 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` Dosyasına Göz At + +Ham OpenAPI şemasının nasıl göründüğünü merak ediyorsanız, FastAPI otomatik olarak tüm API'ınızın tanımlamalarını içeren bir JSON (şeması) oluşturur. + +Bu şemayı direkt olarak http://127.0.0.1:8000/openapi.json bağlantısından görüntüleyebilirsiniz. + +Aşağıdaki gibi başlayan bir JSON ile karşılaşacaksınız: + +```JSON +{ + "openapi": "3.1.0", + "info": { + "title": "FastAPI", + "version": "0.1.0" + }, + "paths": { + "/items/": { + "get": { + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + + + +... +``` + +#### OpenAPI Ne İşe Yarar? + +OpenAPI şeması, FastAPI projesinde bulunan iki etkileşimli dokümantasyon sistemine güç veren şeydir. + +OpenAPI'ya dayalı düzinelerce alternatif etkileşimli dokümantasyon aracı mevcuttur. **FastAPI** ile oluşturulmuş uygulamanıza bu alternatiflerden herhangi birini kolayca ekleyebilirsiniz. + +Ayrıca, API'ınızla iletişim kuracak önyüz, mobil veya IoT uygulamaları gibi istemciler için otomatik olarak kod oluşturabilirsiniz. + +## Adım Adım Özetleyelim + +### Adım 1: `FastAPI`yı Projemize Dahil Edelim + +```Python hl_lines="1" +{!../../../docs_src/first_steps/tutorial001.py!} +``` + +`FastAPI`, API'niz için tüm işlevselliği sağlayan bir Python sınıfıdır. + +!!! note "Teknik Detaylar" + `FastAPI` doğrudan `Starlette`'i miras alan bir sınıftır. + + Starlette'in tüm işlevselliğini `FastAPI` ile de kullanabilirsiniz. + +### Adım 2: Bir `FastAPI` "Örneği" Oluşturalım + +```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'yı oluşturmak için ana etkileşim noktası olacaktır. + +Bu `app` değişkeni, `uvicorn` komutunda atıfta bulunulan değişkenin ta kendisidir. + +
+ +```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 yerleştirirseniz eğer `uvicorn` komutunu şu şekilde çalıştırabilirsiniz: + +
+ +```console +$ uvicorn main:my_awesome_api --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +### Adım 3: Bir *Yol Operasyonu* Oluşturalım + +#### Yol + +Burada "yol" bağlantıda bulunan ilk `/` ile başlayan ve sonrasında gelen kısmı ifade eder. + +Yani, şu şekilde bir bağlantıda: + +``` +https://example.com/items/foo +``` + +... yol şöyle olur: + +``` +/items/foo +``` + +!!! info "Bilgi" + "Yol" genellikle "endpoint" veya "route" olarak adlandırılır. + +Bir API oluştururken, "yol", "kaynaklar" ile "endişeleri" ayırmanın ana yöntemidir. + +#### Operasyonlar + +Burada "operasyon" HTTP "metodlarından" birini ifade eder. + +Bunlardan biri: + +* `POST` +* `GET` +* `PUT` +* `DELETE` + +...veya daha az kullanılan diğerleri: + +* `OPTIONS` +* `HEAD` +* `PATCH` +* `TRACE` + +HTTP protokolünde, bu "metodlardan" birini (veya daha fazlasını) kullanarak her bir yol ile iletişim kurabilirsiniz. + +--- + +API oluştururkan, belirli bir amaca hizmet eden belirli HTTP metodlarını kullanırsınız. + +Normalde kullanılan: + +* `POST`: veri oluşturmak. +* `GET`: veri okumak. +* `PUT`: veriyi güncellemek. +* `DELETE`: veriyi silmek. + +Bu nedenle, OpenAPI'da HTTP metodlarından her birine "operasyon" denir. + +Biz de onları "**operasyonlar**" olarak adlandıracağız. + +#### Bir *Yol Operasyonu Dekoratörü* Tanımlayalım + +```Python hl_lines="6" +{!../../../docs_src/first_steps/tutorial001.py!} +``` + +`@app.get("/")` dekoratörü, **FastAPI**'a hemen altındaki fonksiyonun aşağıdaki durumlardan sorumlu olduğunu söyler: + +* get operasyonu ile +* `/` yoluna gelen istekler + +!!! info "`@decorator` Bilgisi" + Python'da `@something` sözdizimi "dekoratör" olarak adlandırılır. + + Dekoratörler, dekoratif bir şapka gibi (sanırım terim buradan geliyor) fonksiyonların üzerlerine yerleştirilirler. + + Bir "dekoratör" hemen altında bulunan fonksiyonu alır ve o fonksiyon ile bazı işlemler gerçekleştirir. + + Bizim durumumuzda, kullandığımız dekoratör, **FastAPI**'a altındaki fonksiyonun `/` yoluna gelen `get` metodlu isteklerden sorumlu olduğunu söyler. + + Bu bir **yol operasyonu dekoratörüdür**. + +Ayrıca diğer operasyonları da kullanabilirsiniz: + +* `@app.post()` +* `@app.put()` +* `@app.delete()` + +Daha az kullanılanları da kullanabilirsiniz: + +* `@app.options()` +* `@app.head()` +* `@app.patch()` +* `@app.trace()` + +!!! tip "İpucu" + Her işlemi (HTTP metod) istediğiniz gibi kullanmakta özgürsünüz. + + **FastAPI** herhangi bir özel amacı veya anlamı olması konusunda ısrarcı olmaz. + + Buradaki bilgiler bir gereklilik değil, bir kılavuz olarak sunulmaktadır. + + Mesela GraphQL kullanırkan genelde tüm işlemleri yalnızca `POST` operasyonunu kullanarak gerçekleştirirsiniz. + +### Adım 4: **Yol Operasyonu Fonksiyonunu** Tanımlayın + +Aşağıdaki, bizim **yol operasyonu fonksiyonumuzdur**: + +* **yol**: `/` +* **operasyon**: `get` +* **fonksiyon**: "dekoratör"ün (`@app.get("/")`'in) altındaki fonksiyondur. + +```Python hl_lines="7" +{!../../../docs_src/first_steps/tutorial001.py!} +``` + +Bu bir Python fonksiyonudur. + +Bu fonksiyon bir `GET` işlemi kullanılarak "`/`" bağlantısına bir istek geldiğinde **FastAPI** tarafından çağrılır. + +Bu durumda bu fonksiyon bir `async` fonksiyondur. + +--- + +Bu fonksiyonu `async def` yerine normal bir fonksiyon olarak da tanımlayabilirsiniz. + +```Python hl_lines="7" +{!../../../docs_src/first_steps/tutorial003.py!} +``` + +!!! note "Not" + Eğer farkı bilmiyorsanız, [Async: *"Aceleniz mi var?"*](../async.md#in-a-hurry){.internal-link target=_blank} sayfasını kontrol edebilirsiniz. + +### Adım 5: İçeriği Geri Döndürün + +```Python hl_lines="8" +{!../../../docs_src/first_steps/tutorial001.py!} +``` + +Bir `dict`, `list` veya `str`, `int` gibi tekil değerler döndürebilirsiniz. + +Ayrıca, Pydantic modelleri de döndürebilirsiniz (bu konu ileriki aşamalarda irdelenecektir). + +Otomatik olarak JSON'a dönüştürülecek (ORM'ler vb. dahil) başka birçok nesne ve model vardır. En beğendiklerinizi kullanmayı deneyin, yüksek ihtimalle destekleniyordur. + +## Özet + +* `FastAPI`'yı projemize dahil ettik. +* Bir `app` örneği oluşturduk. +* Bir **yol operasyonu dekoratörü** (`@app.get("/")` gibi) yazdık. +* Bir **yol operasyonu fonksiyonu** (`def root(): ...` gibi) yazdık. +* Geliştirme sunucumuzu (`uvicorn main:app --reload` gibi) çalıştırdık. diff --git a/docs/tr/docs/tutorial/first_steps.md b/docs/tr/docs/tutorial/first_steps.md deleted file mode 100644 index b39802f5d6bf1..0000000000000 --- a/docs/tr/docs/tutorial/first_steps.md +++ /dev/null @@ -1,336 +0,0 @@ -# İlk Adımlar - -En basit FastAPI dosyası şu şekildedir: - -```Python -{!../../../docs_src/first_steps/tutorial001.py!} -``` - -Bunu bir `main.py` dosyasına kopyalayın. - -Projeyi çalıştırın: - -
- -```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: - -![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) - -### 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: - -![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) - -### 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) -``` - -
- -### Adım 3: *Path işlemleri* oluşturmak - -#### Path - -Burada "Path" URL'de ilk "\" ile başlayan son bölümü ifade eder. - -Yani, şu şekilde bir URL'de: - -``` -https://example.com/items/foo -``` - -... path şöyle olabilir: - -``` -/items/foo -``` - -!!! info - Genellikle bir "path", "endpoint" veya "route" olarak adlandırılabilir. - -Bir API oluştururken, "path", "resource" ile "concern" ayırmanın ana yoludur. - -#### İşlemler - -Burada "işlem" HTTP methodlarından birini ifade eder. - -Onlardan biri: - -* `POST` -* `GET` -* `PUT` -* `DELETE` - -... ve daha egzotik olanları: - -* `OPTIONS` -* `HEAD` -* `PATCH` -* `TRACE` - -HTTP protokolünde, bu "methodlardan" birini (veya daha fazlasını) kullanarak her path ile iletişim kurabilirsiniz. - ---- - -API'lerinizi oluştururkan, belirli bir işlemi gerçekleştirirken belirli HTTP methodlarını kullanırsınız. - -Normalde kullanılan: - -* `POST`: veri oluşturmak. -* `GET`: veri okumak. -* `PUT`: veriyi güncellemek. -* `DELETE`: veriyi silmek. - -Bu nedenle, OpenAPI'de HTTP methodlarından her birine "işlem" denir. - -Bizde onlara "**işlemler**" diyeceğiz. - -#### Bir *Path işlem decoratorleri* tanımlanmak - -```Python hl_lines="6" -{!../../../docs_src/first_steps/tutorial001.py!} -``` - -`@app.get("/")` **FastAPI'ye** aşağıdaki fonksiyonun adresine giden istekleri işlemekten sorumlu olduğunu söyler: - -* path `/` -* get işlemi kullanılarak - - -!!! info "`@decorator` Bilgisi" - Python `@something` şeklinde ifadeleri "decorator" olarak adlandırır. - - Decoratoru bir fonksiyonun üzerine koyarsınız. Dekoratif bir şapka gibi (Sanırım terim buradan gelmektedir). - - Bir "decorator" fonksiyonu alır ve bazı işlemler gerçekleştir. - - Bizim durumumzda decarator **FastAPI'ye** fonksiyonun bir `get` işlemi ile `/` pathine geldiğini söyler. - - Bu **path işlem decoratordür** - -Ayrıca diğer işlemleri de kullanabilirsiniz: - -* `@app.post()` -* `@app.put()` -* `@app.delete()` - -Ve daha egzotik olanları: - -* `@app.options()` -* `@app.head()` -* `@app.patch()` -* `@app.trace()` - -!!! tip - Her işlemi (HTTP method) istediğiniz gibi kullanmakta özgürsünüz. - - **FastAPI** herhangi bir özel anlamı zorlamaz. - - Buradaki bilgiler bir gereklilik değil, bir kılavuz olarak sunulmaktadır. - - Örneğin, GraphQL kullanırkan normalde tüm işlemleri yalnızca `POST` işlemini kullanarak gerçekleştirirsiniz. - -### Adım 4: **path işlem fonksiyonunu** tanımlayın - -Aşağıdakiler bizim **path işlem fonksiyonlarımızdır**: - -* **path**: `/` -* **işlem**: `get` -* **function**: "decorator"ün altındaki fonksiyondur (`@app.get("/")` altında). - -```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial001.py!} -``` - -Bu bir Python fonksiyonudur. - -Bir `GET` işlemi kullanarak "`/`" URL'sine bir istek geldiğinde **FastAPI** tarafından çağrılır. - -Bu durumda bir `async` fonksiyonudur. - ---- - -Bunu `async def` yerine normal bir fonksiyon olarakta tanımlayabilirsiniz. - -```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial003.py!} -``` - -!!! note - - Eğer farkı bilmiyorsanız, [Async: *"Acelesi var?"*](../async.md#in-a-hurry){.internal-link target=_blank} kontrol edebilirsiniz. - -### Adım 5: İçeriği geri döndürün - - -```Python hl_lines="8" -{!../../../docs_src/first_steps/tutorial001.py!} -``` - -Bir `dict`, `list` döndürebilir veya `str`, `int` gibi tekil değerler döndürebilirsiniz. - -Ayrıca, Pydantic modellerini de döndürebilirsiniz. (Bununla ilgili daha sonra ayrıntılı bilgi göreceksiniz.) - -Otomatik olarak JSON'a dönüştürülecek(ORM'ler vb. dahil) başka birçok nesne ve model vardır. En beğendiklerinizi kullanmayı deneyin, yüksek ihtimalle destekleniyordur. - -## Özet - -* `FastAPI`'yi içe aktarın. -* Bir `app` örneği oluşturun. -* **path işlem decorator** yazın. (`@app.get("/")` gibi) -* **path işlem fonksiyonu** yazın. (`def root(): ...` gibi) -* Development sunucunuzu çalıştırın. (`uvicorn main:app --reload` gibi) diff --git a/docs/tr/docs/tutorial/path-params.md b/docs/tr/docs/tutorial/path-params.md new file mode 100644 index 0000000000000..c19023645201c --- /dev/null +++ b/docs/tr/docs/tutorial/path-params.md @@ -0,0 +1,254 @@ +# Yol Parametreleri + +Yol "parametrelerini" veya "değişkenlerini" Python string biçimlemede kullanılan sözdizimi ile tanımlayabilirsiniz. + +```Python hl_lines="6-7" +{!../../../docs_src/path_params/tutorial001.py!} +``` + +Yol parametresi olan `item_id`'nin değeri, fonksiyonunuza `item_id` argümanı olarak aktarılacaktır. + +Eğer bu örneği çalıştırıp http://127.0.0.1:8000/items/foo sayfasına giderseniz, şöyle bir çıktı ile karşılaşırsınız: + +```JSON +{"item_id":"foo"} +``` + +## Tip İçeren Yol Parametreleri + +Standart Python tip belirteçlerini kullanarak yol parametresinin tipini fonksiyonun içerisinde tanımlayabilirsiniz. + +```Python hl_lines="7" +{!../../../docs_src/path_params/tutorial002.py!} +``` + +Bu durumda, `item_id` bir `int` olarak tanımlanacaktır. + +!!! check "Ek bilgi" + Bu sayede, fonksiyon içerisinde hata denetimi, kod tamamlama gibi konularda editör desteğine kavuşacaksınız. + +## Veri Dönüşümü + +Eğer bu örneği çalıştırıp tarayıcınızda http://127.0.0.1:8000/items/3 sayfasını açarsanız, şöyle bir yanıt ile karşılaşırsınız: + +```JSON +{"item_id":3} +``` + +!!! check "Ek bilgi" + Dikkatinizi çekerim ki, fonksiyonunuzun aldığı (ve döndürdüğü) değer olan `3` bir string `"3"` değil aksine bir Python `int`'idir. + + Bu tanımlamayla birlikte, **FastAPI** size otomatik istek "ayrıştırma" özelliği sağlar. + +## Veri Doğrulama + +Eğer tarayıcınızda http://127.0.0.1:8000/items/foo sayfasını açarsanız, şuna benzer güzel bir HTTP hatası ile karşılaşırsınız: + +```JSON +{ + "detail": [ + { + "type": "int_parsing", + "loc": [ + "path", + "item_id" + ], + "msg": "Input should be a valid integer, unable to parse string as an integer", + "input": "foo", + "url": "https://errors.pydantic.dev/2.1/v/int_parsing" + } + ] +} +``` + +Çünkü burada `item_id` yol parametresi `int` tipinde bir değer beklerken `"foo"` yani `string` tipinde bir değer almıştı. + +Aynı hata http://127.0.0.1:8000/items/4.2 sayfasında olduğu gibi `int` yerine `float` bir değer verseydik de ortaya çıkardı. + +!!! check "Ek bilgi" + Böylece, aynı Python tip tanımlaması ile birlikte, **FastAPI** veri doğrulama özelliği sağlar. + + Dikkatinizi çekerim ki, karşılaştığınız hata, doğrulamanın geçersiz olduğu mutlak noktayı da açık bir şekilde belirtiyor. + + Bu özellik, API'ınızla iletişime geçen kodu geliştirirken ve ayıklarken inanılmaz derecede yararlı olacaktır. + +## Dokümantasyon + +Ayrıca, tarayıcınızı http://127.0.0.1:8000/docs adresinde açarsanız, aşağıdaki gibi otomatik ve interaktif bir API dökümantasyonu ile karşılaşırsınız: + + + +!!! check "Ek bilgi" + Üstelik, sadece aynı Python tip tanımlaması ile, **FastAPI** size otomatik ve interaktif (Swagger UI ile entegre) bir dokümantasyon sağlar. + + Dikkatinizi çekerim ki, yol parametresi integer olarak tanımlanmıştır. + +## Standartlara Dayalı Avantajlar, Alternatif Dokümantasyon + +Oluşturulan şema OpenAPI standardına uygun olduğu için birçok uyumlu araç mevcuttur. + +Bu sayede, **FastAPI**'ın bizzat kendisi http://127.0.0.1:8000/redoc sayfasından erişebileceğiniz alternatif (ReDoc kullanan) bir API dokümantasyonu sağlar: + + + +Aynı şekilde, farklı diller için kod türetme araçları da dahil olmak üzere çok sayıda uyumlu araç bulunur. + +## Pydantic + +Tüm veri doğrulamaları Pydantic tarafından arka planda gerçekleştirilir, bu sayede tüm avantajlardan faydalanabilirsiniz. Böylece, emin ellerde olduğunuzu hissedebilirsiniz. + +Aynı tip tanımlamalarını `str`, `float`, `bool` ve diğer karmaşık veri tipleri ile kullanma imkanınız vardır. + +Bunlardan birkaçı, bu eğitimin ileriki bölümlerinde irdelenmiştir. + +## Sıralama Önem Arz Eder + +*Yol operasyonları* tasarlarken sabit yol barındıran durumlar ile karşılaşabilirsiniz. + +Farz edelim ki `/users/me` yolu geçerli kullanıcı hakkında bilgi almak için kullanılıyor olsun. + +Benzer şekilde `/users/{user_id}` gibi tanımlanmış ve belirli bir kullanıcı hakkında veri almak için kullanıcının ID bilgisini kullanan bir yolunuz da mevcut olabilir. + +*Yol operasyonları* sıralı bir şekilde gözden geçirildiğinden dolayı `/users/me` yolunun `/users/{user_id}` yolundan önce tanımlanmış olmasından emin olmanız gerekmektedir: + +```Python hl_lines="6 11" +{!../../../docs_src/path_params/tutorial003.py!} +``` + +Aksi halde, `/users/{user_id}` yolu `"me"` değerinin `user_id` parametresi için gönderildiğini "düşünerek" `/users/me` ile de eşleşir. + +Benzer şekilde, bir yol operasyonunu yeniden tanımlamanız mümkün değildir: + +```Python hl_lines="6 11" +{!../../../docs_src/path_params/tutorial003b.py!} +``` + +Yol, ilk kısım ile eşleştiğinden dolayı her koşulda ilk yol operasyonu kullanılacaktır. + +## Ön Tanımlı Değerler + +Eğer *yol parametresi* alan bir *yol operasyonunuz* varsa ve alabileceği *yol parametresi* değerlerinin ön tanımlı olmasını istiyorsanız, standart Python `Enum` tipini kullanabilirsiniz. + +### Bir `Enum` Sınıfı Oluşturalım + +`Enum` sınıfını projemize dahil edip `str` ile `Enum` sınıflarını miras alan bir alt sınıf yaratalım. + +`str` sınıfı miras alındığından dolayı, API dokümanı, değerlerin `string` tipinde olması gerektiğini anlayabilecek ve doğru bir şekilde işlenecektir. + +Sonrasında, sınıf içerisinde, mevcut ve geçerli değerler olacak olan sabit değerli özelliklerini oluşturalım: + +```Python hl_lines="1 6-9" +{!../../../docs_src/path_params/tutorial005.py!} +``` + +!!! info "Bilgi" + 3.4 sürümünden beri enumerationlar (ya da enumlar) Python'da mevcuttur. + +!!! tip "İpucu" + Merak ediyorsanız söyleyeyim, "AlexNet", "ResNet" ve "LeNet" isimleri Makine Öğrenmesi modellerini temsil eder. + +### Bir *Yol Parametresi* Tanımlayalım + +Sonrasında, yarattığımız enum sınıfını (`ModelName`) kullanarak tip belirteci aracılığıyla bir *yol parametresi* oluşturalım: + +```Python hl_lines="16" +{!../../../docs_src/path_params/tutorial005.py!} +``` + +### Dokümana Göz Atalım + +*Yol parametresi* için mevcut değerler ön tanımlı olduğundan dolayı, interaktif döküman onları güzel bir şekilde gösterebilir: + + + +### Python *Enumerationları* ile Çalışmak + +*Yol parametresinin* değeri bir *enumeration üyesi* olacaktır. + +#### *Enumeration Üyelerini* Karşılaştıralım + +Parametreyi, yarattığınız enum olan `ModelName` içerisindeki *enumeration üyesi* ile karşılaştırabilirsiniz: + +```Python hl_lines="17" +{!../../../docs_src/path_params/tutorial005.py!} +``` + +#### *Enumeration Değerini* Edinelim + +`model_name.value` veya genel olarak `your_enum_member.value` tanımlarını kullanarak (bu durumda bir `str` olan) gerçek değere ulaşabilirsiniz: + +```Python hl_lines="20" +{!../../../docs_src/path_params/tutorial005.py!} +``` + +!!! tip "İpucu" + `"lenet"` değerine `ModelName.lenet.value` tanımı ile de ulaşabilirsiniz. + +#### *Enumeration Üyelerini* Döndürelim + +JSON gövdesine (örneğin bir `dict`) gömülü olsalar bile *yol operasyonundaki* *enum üyelerini* döndürebilirsiniz. + +Bu üyeler istemciye iletilmeden önce kendilerine karşılık gelen değerlerine (bu durumda string) dönüştürüleceklerdir: + +```Python hl_lines="18 21 23" +{!../../../docs_src/path_params/tutorial005.py!} +``` + +İstemci tarafında şuna benzer bir JSON yanıtı ile karşılaşırsınız: + +```JSON +{ + "model_name": "alexnet", + "message": "Deep Learning FTW!" +} +``` + +## Yol İçeren Yol Parametreleri + +Farz edelim ki elinizde `/files/{file_path}` isminde bir *yol operasyonu* var. + +Fakat `file_path` değerinin `home/johndoe/myfile.txt` gibi bir *yol* barındırmasını istiyorsunuz. + +Sonuç olarak, oluşturmak istediğin URL `/files/home/johndoe/myfile.txt` gibi bir şey olacaktır. + +### OpenAPI Desteği + +Test etmesi ve tanımlaması zor senaryolara sebebiyet vereceğinden dolayı OpenAPI, *yol* barındıran *yol parametrelerini* tanımlayacak bir çözüm sunmuyor. + +Ancak bunu, Starlette kütüphanesinin dahili araçlarından birini kullanarak **FastAPI**'da gerçekleştirebilirsiniz. + +Parametrenin bir yol içermesi gerektiğini belirten herhangi bir doküman eklemememize rağmen dokümanlar yine de çalışacaktır. + +### Yol Dönüştürücü + +Direkt olarak Starlette kütüphanesinden gelen bir opsiyon sayesinde aşağıdaki gibi *yol* içeren bir *yol parametresi* bağlantısı tanımlayabilirsiniz: + +``` +/files/{file_path:path} +``` + +Bu durumda, parametrenin adı `file_path` olacaktır ve son kısım olan `:path` kısmı, parametrenin herhangi bir *yol* ile eşleşmesi gerektiğini belirtecektir. + +Böylece şunun gibi bir kullanım yapabilirsiniz: + +```Python hl_lines="6" +{!../../../docs_src/path_params/tutorial004.py!} +``` + +!!! tip "İpucu" + Parametrenin başında `/home/johndoe/myfile.txt` yolunda olduğu gibi (`/`) işareti ile birlikte kullanmanız gerektiği durumlar olabilir. + + Bu durumda, URL, `files` ile `home` arasında iki eğik çizgiye (`//`) sahip olup `/files//home/johndoe/myfile.txt` gibi gözükecektir. + +## Özet + +**FastAPI** ile kısa, sezgisel ve standart Python tip tanımlamaları kullanarak şunları elde edersiniz: + +* Editör desteği: hata denetimi, otomatik tamamlama, vb. +* Veri "dönüştürme" +* Veri doğrulama +* API tanımlamaları ve otomatik dokümantasyon + +Ve sadece, bunları bir kez tanımlamanız yeterli. + +Diğer frameworkler ile karşılaştırıldığında (ham performans dışında), üstte anlatılan durum muhtemelen **FastAPI**'ın göze çarpan başlıca avantajıdır. diff --git a/docs/tr/docs/tutorial/query-params.md b/docs/tr/docs/tutorial/query-params.md new file mode 100644 index 0000000000000..aa3915557c8aa --- /dev/null +++ b/docs/tr/docs/tutorial/query-params.md @@ -0,0 +1,227 @@ +# Sorgu Parametreleri + +Fonksiyonda yol parametrelerinin parçası olmayan diğer tanımlamalar otomatik olarak "sorgu" parametresi olarak yorumlanır. + +```Python hl_lines="9" +{!../../../docs_src/query_params/tutorial001.py!} +``` + +Sorgu, bağlantıdaki `?` kısmından sonra gelen ve `&` işareti ile ayrılan anahtar-değer çiftlerinin oluşturduğu bir kümedir. + +Örneğin, aşağıdaki bağlantıda: + +``` +http://127.0.0.1:8000/items/?skip=0&limit=10 +``` + +...sorgu parametreleri şunlardır: + +* `skip`: değeri `0`'dır +* `limit`: değeri `10`'dır + +Parametreler bağlantının bir parçası oldukları için doğal olarak string olarak değerlendirilirler. + +Fakat, Python tipleri ile tanımlandıkları zaman (yukarıdaki örnekte `int` oldukları gibi), parametreler o tiplere dönüştürülür ve o tipler çerçevesinde doğrulanırlar. + +Yol parametreleri için geçerli olan her türlü işlem aynı şekilde sorgu parametreleri için de geçerlidir: + +* Editör desteği (şüphesiz) +* Veri "ayrıştırma" +* Veri doğrulama +* Otomatik dokümantasyon + +## Varsayılanlar + +Sorgu parametreleri, adres yolunun sabit bir parçası olmadıklarından dolayı isteğe bağlı ve varsayılan değere sahip olabilirler. + +Yukarıdaki örnekte `skip=0` ve `limit=10` varsayılan değere sahiplerdir. + +Yani, aşağıdaki bağlantıya gitmek: + +``` +http://127.0.0.1:8000/items/ +``` + +şu adrese gitmek ile aynı etkiye sahiptir: + +``` +http://127.0.0.1:8000/items/?skip=0&limit=10 +``` + +Ancak, mesela şöyle bir adresi ziyaret ederseniz: + +``` +http://127.0.0.1:8000/items/?skip=20 +``` + +Fonksiyonunuzdaki parametre değerleri aşağıdaki gibi olacaktır: + +* `skip=20`: çünkü bağlantıda böyle tanımlandı. +* `limit=10`: çünkü varsayılan değer buydu. + +## İsteğe Bağlı Parametreler + +Aynı şekilde, varsayılan değerlerini `None` olarak atayarak isteğe bağlı parametreler tanımlayabilirsiniz: + +=== "Python 3.10+" + + ```Python hl_lines="7" + {!> ../../../docs_src/query_params/tutorial002_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9" + {!> ../../../docs_src/query_params/tutorial002.py!} + ``` + +Bu durumda, `q` fonksiyon parametresi isteğe bağlı olacak ve varsayılan değer olarak `None` alacaktır. + +!!! check "Ek bilgi" + Ayrıca, dikkatinizi çekerim ki; **FastAPI**, `item_id` parametresinin bir yol parametresi olduğunu ve `q` parametresinin yol değil bir sorgu parametresi olduğunu fark edecek kadar beceriklidir. + +## Sorgu Parametresi Tip Dönüşümü + +Aşağıda görüldüğü gibi dönüştürülmek üzere `bool` tipleri de tanımlayabilirsiniz: + +=== "Python 3.10+" + + ```Python hl_lines="7" + {!> ../../../docs_src/query_params/tutorial003_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9" + {!> ../../../docs_src/query_params/tutorial003.py!} + ``` + +Bu durumda, eğer şu adrese giderseniz: + +``` +http://127.0.0.1:8000/items/foo?short=1 +``` + +veya + +``` +http://127.0.0.1:8000/items/foo?short=True +``` + +veya + +``` +http://127.0.0.1:8000/items/foo?short=true +``` + +veya + +``` +http://127.0.0.1:8000/items/foo?short=on +``` + +veya + +``` +http://127.0.0.1:8000/items/foo?short=yes +``` + +veya adres, herhangi farklı bir harf varyasyonu içermesi durumuna rağmen (büyük harf, sadece baş harfi büyük kelime, vb.) fonksiyonunuz, `bool` tipli `short` parametresini `True` olarak algılayacaktır. Aksi halde `False` olarak algılanacaktır. + + +## Çoklu Yol ve Sorgu Parametreleri + +**FastAPI** neyin ne olduğunu ayırt edebileceğinden dolayı aynı anda birden fazla yol ve sorgu parametresi tanımlayabilirsiniz. + +Ve parametreleri, herhangi bir sıraya koymanıza da gerek yoktur. + +İsimlerine göre belirleneceklerdir: + +=== "Python 3.10+" + + ```Python hl_lines="6 8" + {!> ../../../docs_src/query_params/tutorial004_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="8 10" + {!> ../../../docs_src/query_params/tutorial004.py!} + ``` + +## Zorunlu Sorgu Parametreleri + +Türü yol olmayan bir parametre (şu ana kadar sadece sorgu parametrelerini gördük) için varsayılan değer tanımlarsanız o parametre zorunlu olmayacaktır. + +Parametre için belirli bir değer atamak istemeyip parametrenin sadece isteğe bağlı olmasını istiyorsanız değerini `None` olarak atayabilirsiniz. + +Fakat, bir sorgu parametresini zorunlu yapmak istiyorsanız varsayılan bir değer atamamanız yeterli olacaktır: + +```Python hl_lines="6-7" +{!../../../docs_src/query_params/tutorial005.py!} +``` + +Burada `needy` parametresi `str` tipinden oluşan zorunlu bir sorgu parametresidir. + +Eğer tarayıcınızda şu bağlantıyı: + +``` +http://127.0.0.1:8000/items/foo-item +``` + +...`needy` parametresini eklemeden açarsanız şuna benzer bir hata ile karşılaşırsınız: + +```JSON +{ + "detail": [ + { + "type": "missing", + "loc": [ + "query", + "needy" + ], + "msg": "Field required", + "input": null, + "url": "https://errors.pydantic.dev/2.1/v/missing" + } + ] +} +``` + +`needy` zorunlu bir parametre olduğundan dolayı bağlantıda tanımlanması gerekir: + +``` +http://127.0.0.1:8000/items/foo-item?needy=sooooneedy +``` + +...bu iş görür: + +```JSON +{ + "item_id": "foo-item", + "needy": "sooooneedy" +} +``` + +Ve elbette, bazı parametreleri zorunlu, bazılarını varsayılan değerli ve bazılarını tamamen opsiyonel olarak tanımlayabilirsiniz: + +=== "Python 3.10+" + + ```Python hl_lines="8" + {!> ../../../docs_src/query_params/tutorial006_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="10" + {!> ../../../docs_src/query_params/tutorial006.py!} + ``` + +Bu durumda, 3 tane sorgu parametresi var olacaktır: + +* `needy`, zorunlu bir `str`. +* `skip`, varsayılan değeri `0` olan bir `int`. +* `limit`, isteğe bağlı bir `int`. + +!!! tip "İpucu" + Ayrıca, [Yol Parametrelerinde](path-params.md#predefined-values){.internal-link target=_blank} de kullanıldığı şekilde `Enum` sınıfından faydalanabilirsiniz. diff --git a/docs/uk/docs/alternatives.md b/docs/uk/docs/alternatives.md new file mode 100644 index 0000000000000..bdb62513e0dab --- /dev/null +++ b/docs/uk/docs/alternatives.md @@ -0,0 +1,412 @@ +# Альтернативи, натхнення та порівняння + +Що надихнуло на створення **FastAPI**, який він у порінянні з іншими альтернативами та чого він у них навчився. + +## Вступ + +**FastAPI** не існувало б, якби не попередні роботи інших. + +Раніше було створено багато інструментів, які надихнули на його створення. + +Я кілька років уникав створення нового фреймворку. Спочатку я спробував вирішити всі функції, охоплені **FastAPI**, використовуючи багато різних фреймворків, плагінів та інструментів. + +Але в якийсь момент не було іншого виходу, окрім створення чогось, що надавало б усі ці функції, взявши найкращі ідеї з попередніх інструментів і поєднавши їх найкращим чином, використовуючи мовні функції, які навіть не були доступні раніше (Python 3.6+ підказки типів). + +## Попередні інструменти + +### Django + +Це найпопулярніший фреймворк Python, який користується широкою довірою. Він використовується для створення таких систем, як Instagram. + +Він відносно тісно пов’язаний з реляційними базами даних (наприклад, MySQL або PostgreSQL), тому мати базу даних NoSQL (наприклад, Couchbase, MongoDB, Cassandra тощо) як основний механізм зберігання не дуже просто. + +Він був створений для створення HTML у серверній частині, а не для створення API, які використовуються сучасним інтерфейсом (як-от React, Vue.js і Angular) або іншими системами (як-от IoT пристрої), які спілкуються з ним. + +### Django REST Framework + +Фреймворк Django REST був створений як гнучкий інструментарій для створення веб-інтерфейсів API використовуючи Django в основі, щоб покращити його можливості API. + +Його використовують багато компаній, включаючи Mozilla, Red Hat і Eventbrite. + +Це був один із перших прикладів **автоматичної документації API**, і саме це була одна з перших ідей, яка надихнула на «пошук» **FastAPI**. + +!!! Примітка + Django REST Framework створив Том Крісті. Той самий творець Starlette і Uvicorn, на яких базується **FastAPI**. + + +!!! Перегляньте "Надихнуло **FastAPI** на" + Мати автоматичний веб-інтерфейс документації API. + +### Flask + +Flask — це «мікрофреймворк», він не включає інтеграцію бази даних, а також багато речей, які за замовчуванням є в Django. + +Ця простота та гнучкість дозволяють використовувати бази даних NoSQL як основну систему зберігання даних. + +Оскільки він дуже простий, він порівняно легкий та інтуїтивний для освоєння, хоча в деяких моментах документація стає дещо технічною. + +Він також зазвичай використовується для інших програм, яким не обов’язково потрібна база даних, керування користувачами або будь-яка з багатьох функцій, які є попередньо вбудованими в Django. Хоча багато з цих функцій можна додати за допомогою плагінів. + +Відокремлення частин було ключовою особливістю, яку я хотів зберегти, при цьому залишаючись «мікрофреймворком», який можна розширити, щоб охопити саме те, що потрібно. + +Враховуючи простоту Flask, він здавався хорошим підходом для створення API. Наступним, що знайшов, був «Django REST Framework» для Flask. + +!!! Переглянте "Надихнуло **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") +``` + +Відповідна операція *роуту* API FastAPI може виглядати так: + +```Python hl_lines="1" +@app.get("/some/url") +def read_url(): + return {"message": "Hello World"} +``` + +Зверніть увагу на схожість у `requests.get(...)` і `@app.get(...)`. + +!!! Перегляньте "Надихнуло **FastAPI** на" + * Майте простий та інтуїтивно зрозумілий API. + * Використовуйте імена (операції) методів HTTP безпосередньо, простим та інтуїтивно зрозумілим способом. + * Розумні параметри за замовчуванням, але потужні налаштування. + + +### Swagger / OpenAPI + +Головною функцією, яку я хотів від Django REST Framework, була автоматична API документація. + +Потім я виявив, що існує стандарт для документування API з використанням JSON (або YAML, розширення JSON) під назвою Swagger. + +І вже був створений веб-інтерфейс користувача для Swagger API. Отже, можливість генерувати документацію Swagger для API дозволить використовувати цей веб-інтерфейс автоматично. + +У якийсь момент Swagger було передано Linux Foundation, щоб перейменувати його на OpenAPI. + +Тому, коли говорять про версію 2.0, прийнято говорити «Swagger», а про версію 3+ «OpenAPI». + +!!! Перегляньте "Надихнуло **FastAPI** на" + Прийняти і використовувати відкритий стандарт для специфікацій API замість спеціальної схеми. + + Інтегрувати інструменти інтерфейсу на основі стандартів: + + * Інтерфейс Swagger + * ReDoc + + Ці два було обрано через те, що вони досить популярні та стабільні, але, виконавши швидкий пошук, ви можете знайти десятки додаткових альтернативних інтерфейсів для OpenAPI (які можна використовувати з **FastAPI**). + +### Фреймворки REST для Flask + +Існує кілька фреймворків Flask REST, але, витративши час і роботу на їх дослідження, я виявив, що багато з них припинено або залишено, з кількома постійними проблемами, які зробили їх непридатними. + +### Marshmallow + +Однією з головних функцій, необхідних для систем API, є "серіалізація", яка бере дані з коду (Python) і перетворює їх на щось, що можна надіслати через мережу. Наприклад, перетворення об’єкта, що містить дані з бази даних, на об’єкт JSON. Перетворення об’єктів `datetime` на строки тощо. + +Іншою важливою функцією, необхідною для API, є перевірка даних, яка забезпечує дійсність даних за певними параметрами. Наприклад, що деяке поле є `int`, а не деяка випадкова строка. Це особливо корисно для вхідних даних. + +Без системи перевірки даних вам довелося б виконувати всі перевірки вручну, у коді. + +Marshmallow створено для забезпечення цих функцій. Це чудова бібліотека, і я часто нею користувався раніше. + +Але він був створений до того, як існували підказки типу Python. Отже, щоб визначити кожну схему, вам потрібно використовувати спеціальні утиліти та класи, надані Marshmallow. + +!!! Перегляньте "Надихнуло **FastAPI** на" + Використовувати код для автоматичного визначення "схем", які надають типи даних і перевірку. + +### Webargs + +Іншою важливою функцією, необхідною для API, є аналіз даних із вхідних запитів. + +Webargs — це інструмент, створений, щоб забезпечити це поверх кількох фреймворків, включаючи Flask. + +Він використовує Marshmallow в основі для перевірки даних. І створений тими ж розробниками. + +Це чудовий інструмент, і я також часто використовував його, перш ніж створити **FastAPI**. + +!!! Інформація + Webargs був створений тими ж розробниками Marshmallow. + +!!! Перегляньте "Надихнуло **FastAPI** на" + Мати автоматичну перевірку даних вхідного запиту. + +### APISpec + +Marshmallow і Webargs забезпечують перевірку, аналіз і серіалізацію як плагіни. + +Але документація досі відсутня. Потім було створено APISpec. + +Це плагін для багатьох фреймворків (також є плагін для Starlette). + +Принцип роботи полягає в тому, що ви пишете визначення схеми, використовуючи формат YAML, у docstring кожної функції, що обробляє маршрут. + +І він генерує схеми OpenAPI. + +Так це працює у Flask, Starlette, Responder тощо. + +Але потім ми знову маємо проблему наявності мікросинтаксису всередині Python строки (великий YAML). + +Редактор тут нічим не може допомогти. І якщо ми змінимо параметри чи схеми Marshmallow і забудемо також змінити цю строку документа YAML, згенерована схема буде застарілою. + +!!! Інформація + APISpec був створений тими ж розробниками Marshmallow. + + +!!! Перегляньте "Надихнуло **FastAPI** на" + Підтримувати відкритий стандарт API, OpenAPI. + +### Flask-apispec + +Це плагін Flask, який об’єднує Webargs, Marshmallow і APISpec. + +Він використовує інформацію з Webargs і Marshmallow для автоматичного створення схем OpenAPI за допомогою APISpec. + +Це чудовий інструмент, дуже недооцінений. Він має бути набагато популярнішим, ніж багато плагінів Flask. Це може бути пов’язано з тим, що його документація надто стисла й абстрактна. + +Це вирішило необхідність писати YAML (інший синтаксис) всередині рядків документів Python. + +Ця комбінація Flask, Flask-apispec із Marshmallow і Webargs була моїм улюбленим бекенд-стеком до створення **FastAPI**. + +Їі використання призвело до створення кількох генераторів повного стека Flask. Це основний стек, який я (та кілька зовнішніх команд) використовував досі: + +* https://github.com/tiangolo/full-stack +* https://github.com/tiangolo/full-stack-flask-couchbase +* https://github.com/tiangolo/full-stack-flask-couchdb + +І ці самі генератори повного стеку були основою [**FastAPI** генераторів проектів](project-generation.md){.internal-link target=_blank}. + +!!! Інформація + Flask-apispec був створений тими ж розробниками Marshmallow. + +!!! Перегляньте "Надихнуло **FastAPI** на" + Створення схеми OpenAPI автоматично з того самого коду, який визначає серіалізацію та перевірку. + +### NestJS (та Angular) + +Це навіть не Python, NestJS — це фреймворк NodeJS JavaScript (TypeScript), натхненний Angular. + +Це досягає чогось подібного до того, що можна зробити з Flask-apispec. + +Він має інтегровану систему впровадження залежностей, натхненну Angular two. Він потребує попередньої реєстрації «injectables» (як і всі інші системи впровадження залежностей, які я знаю), тому це збільшує багатослівність та повторення коду. + +Оскільки параметри описані за допомогою типів TypeScript (подібно до підказок типу Python), підтримка редактора досить хороша. + +Але оскільки дані TypeScript не зберігаються після компіляції в JavaScript, вони не можуть покладатися на типи для визначення перевірки, серіалізації та документації одночасно. Через це та деякі дизайнерські рішення, щоб отримати перевірку, серіалізацію та автоматичну генерацію схеми, потрібно додати декоратори в багатьох місцях. Таким чином код стає досить багатослівним. + +Він не дуже добре обробляє вкладені моделі. Отже, якщо тіло JSON у запиті є об’єктом JSON із внутрішніми полями, які, у свою чергу, є вкладеними об’єктами JSON, його неможливо належним чином задокументувати та перевірити. + +!!! Перегляньте "Надихнуло **FastAPI** на" + Використовувати типи Python, щоб мати чудову підтримку редактора. + + Мати потужну систему впровадження залежностей. Знайдіть спосіб звести до мінімуму повторення коду. + +### Sanic + +Це був один із перших надзвичайно швидких фреймворків Python на основі `asyncio`. Він був дуже схожий на Flask. + +!!! Примітка "Технічні деталі" + Він використовував `uvloop` замість стандартного циклу Python `asyncio`. Ось що зробило його таким швидким. + + Це явно надихнуло Uvicorn і Starlette, які зараз швидші за Sanic у відкритих тестах. + +!!! Перегляньте "Надихнуло **FastAPI** на" + Знайти спосіб отримати божевільну продуктивність. + + Ось чому **FastAPI** базується на Starlette, оскільки це найшвидша доступна структура (перевірена тестами сторонніх розробників). + +### Falcon + +Falcon — ще один високопродуктивний фреймворк Python, він розроблений як мінімальний і працює як основа інших фреймворків, таких як Hug. + +Він розроблений таким чином, щоб мати функції, які отримують два параметри, один «запит» і один «відповідь». Потім ви «читаєте» частини запиту та «записуєте» частини у відповідь. Через такий дизайн неможливо оголосити параметри запиту та тіла за допомогою стандартних підказок типу Python як параметри функції. + +Таким чином, перевірка даних, серіалізація та документація повинні виконуватися в коді, а не автоматично. Або вони повинні бути реалізовані як фреймворк поверх Falcon, як Hug. Така сама відмінність спостерігається в інших фреймворках, натхненних дизайном Falcon, що мають один об’єкт запиту та один об’єкт відповіді як параметри. + +!!! Перегляньте "Надихнуло **FastAPI** на" + Знайти способи отримати чудову продуктивність. + + Разом із Hug (оскільки Hug базується на Falcon) надихнув **FastAPI** оголосити параметр `response` у функціях. + + Хоча у FastAPI це необов’язково, і використовується в основному для встановлення заголовків, файлів cookie та альтернативних кодів стану. + +### Molten + +Я відкрив для себе Molten на перших етапах створення **FastAPI**. І він має досить схожі ідеї: + +* Базується на підказках типу Python. +* Перевірка та документація цих типів. +* Система впровадження залежностей. + +Він не використовує перевірку даних, серіалізацію та бібліотеку документації сторонніх розробників, як Pydantic, він має свою власну. Таким чином, ці визначення типів даних не можна було б використовувати повторно так легко. + +Це вимагає трохи більш докладних конфігурацій. І оскільки він заснований на WSGI (замість ASGI), він не призначений для використання високопродуктивних інструментів, таких як Uvicorn, Starlette і Sanic. + +Система впровадження залежностей вимагає попередньої реєстрації залежностей, і залежності вирішуються на основі оголошених типів. Отже, неможливо оголосити більше ніж один «компонент», який надає певний тип. + +Маршрути оголошуються в одному місці з використанням функцій, оголошених в інших місцях (замість використання декораторів, які можна розмістити безпосередньо поверх функції, яка обробляє кінцеву точку). Це ближче до того, як це робить Django, ніж до Flask (і Starlette). Він розділяє в коді речі, які відносно тісно пов’язані. + +!!! Перегляньте "Надихнуло **FastAPI** на" + Визначити додаткові перевірки для типів даних, використовуючи значення "за замовчуванням" атрибутів моделі. Це покращує підтримку редактора, а раніше вона була недоступна в Pydantic. + + Це фактично надихнуло оновити частини Pydantic, щоб підтримувати той самий стиль оголошення перевірки (всі ці функції вже доступні в Pydantic). + +### Hug + +Hug був одним із перших фреймворків, який реалізував оголошення типів параметрів API за допомогою підказок типу Python. Це була чудова ідея, яка надихнула інші інструменти зробити те саме. + +Він використовував спеціальні типи у своїх оголошеннях замість стандартних типів Python, але це все одно був величезний крок вперед. + +Це також був один із перших фреймворків, який генерував спеціальну схему, що оголошувала весь API у JSON. + +Він не базувався на таких стандартах, як OpenAPI та JSON Schema. Тому було б непросто інтегрувати його з іншими інструментами, як-от Swagger UI. Але знову ж таки, це була дуже інноваційна ідея. + +Він має цікаву незвичайну функцію: використовуючи ту саму структуру, можна створювати API, а також CLI. + +Оскільки він заснований на попередньому стандарті для синхронних веб-фреймворків Python (WSGI), він не може працювати з Websockets та іншими речами, хоча він також має високу продуктивність. + +!!! Інформація + Hug створив Тімоті Крослі, той самий творець `isort`, чудовий інструмент для автоматичного сортування імпорту у файлах Python. + +!!! Перегляньте "Надихнуло **FastAPI** на" + Hug надихнув частину APIStar і був одним із найбільш перспективних інструментів, поряд із APIStar. + + Hug надихнув **FastAPI** на використання підказок типу Python для оголошення параметрів і автоматичного створення схеми, що визначає API. + + Hug надихнув **FastAPI** оголосити параметр `response` у функціях для встановлення заголовків і файлів cookie. + +### APIStar (<= 0,5) + +Безпосередньо перед тим, як вирішити створити **FastAPI**, я знайшов сервер **APIStar**. Він мав майже все, що я шукав, і мав чудовий дизайн. + +Це була одна з перших реалізацій фреймворку, що використовує підказки типу Python для оголошення параметрів і запитів, яку я коли-небудь бачив (до NestJS і Molten). Я знайшов його більш-менш одночасно з Hug. Але APIStar використовував стандарт OpenAPI. + +Він мав автоматичну перевірку даних, серіалізацію даних і генерацію схеми OpenAPI на основі підказок того самого типу в кількох місцях. + +Визначення схеми тіла не використовували ті самі підказки типу Python, як Pydantic, воно було трохи схоже на Marshmallow, тому підтримка редактора була б не такою хорошою, але все ж APIStar був найкращим доступним варіантом. + +Він мав найкращі показники продуктивності на той час (перевершив лише Starlette). + +Спочатку він не мав автоматичного веб-інтерфейсу документації API, але я знав, що можу додати до нього інтерфейс користувача Swagger. + +Він мав систему введення залежностей. Він вимагав попередньої реєстрації компонентів, як і інші інструменти, розглянуті вище. Але все одно це була чудова функція. + +Я ніколи не міг використовувати його в повноцінному проекті, оскільки він не мав інтеграції безпеки, тому я не міг замінити всі функції, які мав, генераторами повного стеку на основі Flask-apispec. У моїх невиконаних проектах я мав створити запит на вилучення, додавши цю функцію. + +Але потім фокус проекту змінився. + +Це вже не був веб-фреймворк API, оскільки творцю потрібно було зосередитися на Starlette. + +Тепер APIStar — це набір інструментів для перевірки специфікацій OpenAPI, а не веб-фреймворк. + +!!! Інформація + APIStar створив Том Крісті. Той самий хлопець, який створив: + + * Django REST Framework + * Starlette (на якому базується **FastAPI**) + * Uvicorn (використовується Starlette і **FastAPI**) + +!!! Перегляньте "Надихнуло **FastAPI** на" + Існувати. + + Ідею оголошення кількох речей (перевірки даних, серіалізації та документації) за допомогою тих самих типів Python, які в той же час забезпечували чудову підтримку редактора, я вважав геніальною ідеєю. + + І після тривалого пошуку подібної структури та тестування багатьох різних альтернатив, APIStar став найкращим доступним варіантом. + + Потім APIStar перестав існувати як сервер, і було створено Starlette, який став новою кращою основою для такої системи. Це стало останнім джерелом натхнення для створення **FastAPI**. Я вважаю **FastAPI** «духовним спадкоємцем» APIStar, удосконалюючи та розширюючи функції, систему введення тексту та інші частини на основі досвіду, отриманого від усіх цих попередніх інструментів. + +## Використовується **FastAPI** + +### Pydantic + +Pydantic — це бібліотека для визначення перевірки даних, серіалізації та документації (за допомогою схеми JSON) на основі підказок типу Python. + +Це робить його надзвичайно інтуїтивним. + +Його можна порівняти з Marshmallow. Хоча він швидший за Marshmallow у тестах. Оскільки він базується на тих самих підказках типу Python, підтримка редактора чудова. + +!!! Перегляньте "**FastAPI** використовує його для" + Виконання перевірки всіх даних, серіалізації даних і автоматичної документацію моделі (на основі схеми JSON). + + Потім **FastAPI** бере ці дані схеми JSON і розміщує їх у OpenAPI, окремо від усіх інших речей, які він робить. + +### Starlette + +Starlette — це легкий фреймворк/набір інструментів ASGI, який ідеально підходить для створення високопродуктивних asyncio сервісів. + +Він дуже простий та інтуїтивно зрозумілий. Його розроблено таким чином, щоб його можна було легко розширювати та мати модульні компоненти. + +Він має: + +* Серйозно вражаючу продуктивність. +* Підтримку WebSocket. +* Фонові завдання в процесі. +* Події запуску та завершення роботи. +* Тестового клієнта, побудований на HTTPX. +* CORS, GZip, статичні файли, потокові відповіді. +* Підтримку сеансів і файлів cookie. +* 100% покриття тестом. +* 100% анотовану кодову базу. +* Кілька жорстких залежностей. + +Starlette наразі є найшвидшим фреймворком Python із перевірених. Перевершує лише Uvicorn, який є не фреймворком, а сервером. + +Starlette надає всі основні функції веб-мікрофреймворку. + +Але він не забезпечує автоматичної перевірки даних, серіалізації чи документації. + +Це одна з головних речей, які **FastAPI** додає зверху, все на основі підказок типу Python (з використанням Pydantic). Це, а також система впровадження залежностей, утиліти безпеки, створення схеми OpenAPI тощо. + +!!! Примітка "Технічні деталі" + ASGI — це новий «стандарт», який розробляється членами основної команди Django. Це ще не «стандарт Python» (PEP), хоча вони в процесі цього. + + Тим не менш, він уже використовується як «стандарт» кількома інструментами. Це значно покращує сумісність, оскільки ви можете переключити Uvicorn на будь-який інший сервер ASGI (наприклад, Daphne або Hypercorn), або ви можете додати інструменти, сумісні з ASGI, як-от `python-socketio`. + +!!! Перегляньте "**FastAPI** використовує його для" + Керування всіма основними веб-частинами. Додавання функцій зверху. + + Сам клас `FastAPI` безпосередньо успадковує клас `Starlette`. + + Отже, усе, що ви можете робити зі Starlette, ви можете робити це безпосередньо за допомогою **FastAPI**, оскільки це, по суті, Starlette на стероїдах. + +### Uvicorn + +Uvicorn — це блискавичний сервер ASGI, побудований на uvloop і httptools. + +Це не веб-фреймворк, а сервер. Наприклад, він не надає інструментів для маршрутизації. Це те, що фреймворк на кшталт Starlette (або **FastAPI**) забезпечить поверх нього. + +Це рекомендований сервер для Starlette і **FastAPI**. + +!!! Перегляньте "**FastAPI** рекомендує це як" + Основний веб-сервер для запуску програм **FastAPI**. + + Ви можете поєднати його з Gunicorn, щоб мати асинхронний багатопроцесний сервер. + + Додаткову інформацію див. у розділі [Розгортання](deployment/index.md){.internal-link target=_blank}. + +## Орієнтири та швидкість + +Щоб зрозуміти, порівняти та побачити різницю між Uvicorn, Starlette і FastAPI, перегляньте розділ про [Бенчмарки](benchmarks.md){.internal-link target=_blank}. diff --git a/docs/uk/docs/fastapi-people.md b/docs/uk/docs/fastapi-people.md new file mode 100644 index 0000000000000..f7d0220b595a0 --- /dev/null +++ b/docs/uk/docs/fastapi-people.md @@ -0,0 +1,178 @@ +# Люди FastAPI + +FastAPI має дивовижну спільноту, яка вітає людей різного походження. + +## Творець – Супроводжувач + +Привіт! 👋 + +Це я: + +{% if people %} +
+{% for user in people.maintainers %} + +
@{{ user.login }}
Answers: {{ user.answers }}
Pull Requests: {{ user.prs }}
+{% endfor %} + +
+{% 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 %} +
+{% for user in people.last_month_experts[:10] %} + +
@{{ user.login }}
Issues replied: {{ user.count }}
+{% endfor %} + +
+{% endif %} + +## Експерти + +Ось **експерти FastAPI**. 🤓 + +Це користувачі, які [найбільше допомагали іншим із проблемами (запитаннями) у GitHub](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank} протягом *всього часу*. + +Вони зарекомендували себе як експерти, допомагаючи багатьом іншим. ✨ + +{% if people %} +
+{% for user in people.experts[:50] %} + +
@{{ user.login }}
Issues replied: {{ user.count }}
+{% endfor %} + +
+{% endif %} + +## Найкращі контрибютори + +Ось **Найкращі контрибютори**. 👷 + +Ці користувачі [створили найбільшу кількість пул реквестів](help-fastapi.md#create-a-pull-request){.internal-link target=_blank} які були *змержені*. + +Вони надали програмний код, документацію, переклади тощо. 📦 + +{% if people %} +
+{% for user in people.top_contributors[:50] %} + +
@{{ user.login }}
Pull Requests: {{ user.count }}
+{% endfor %} + +
+{% endif %} + +Є багато інших контрибюторів (більше сотні), їх усіх можна побачити на сторінці FastAPI GitHub Contributors. 👷 + +## Найкращі рецензенти + +Ці користувачі є **Найкращими рецензентами**. 🕵️ + +### Рецензенти на переклади + +Я розмовляю лише кількома мовами (і не дуже добре 😅). Отже, рецензенти – це ті, хто має [**повноваження схвалювати переклади**](contributing.md#translations){.internal-link target=_blank} документації. Без них не було б документації кількома іншими мовами. + +--- + +**Найкращі рецензенти** 🕵️ переглянули більшість пул реквестів від інших, забезпечуючи якість коду, документації і особливо **перекладів**. + +{% if people %} +
+{% for user in people.top_translations_reviewers[:50] %} + +
@{{ user.login }}
Reviews: {{ user.count }}
+{% endfor %} + +
+{% endif %} + +## Спонсори + +Це **Спонсори**. 😎 + +Вони підтримують мою роботу з **FastAPI** (та іншими), переважно через GitHub Sponsors. + +{% if sponsors %} + +{% if sponsors.gold %} + +### Золоті спонсори + +{% for sponsor in sponsors.gold -%} + +{% endfor %} +{% endif %} + +{% if sponsors.silver %} + +### Срібні спонсори + +{% for sponsor in sponsors.silver -%} + +{% endfor %} +{% endif %} + +{% if sponsors.bronze %} + +### Бронзові спонсори + +{% for sponsor in sponsors.bronze -%} + +{% endfor %} +{% endif %} + +{% endif %} + +### Індивідуальні спонсори + +{% if github_sponsors %} +{% for group in github_sponsors.sponsors %} + +
+ +{% for user in group %} +{% if user.login not in sponsors_badge.logins %} + + + +{% endif %} +{% endfor %} + +
+ +{% endfor %} +{% endif %} + +## Про дані - технічні деталі + +Основна мета цієї сторінки – висвітлити зусилля спільноти, щоб допомогти іншим. + +Особливо враховуючи зусилля, які зазвичай менш помітні, а в багатьох випадках більш важкі, як-от допомога іншим із проблемами та перегляд пул реквестів перекладів. + +Дані розраховуються щомісяця, ви можете ознайомитися з вихідним кодом тут. + +Тут я також підкреслюю внески спонсорів. + +Я також залишаю за собою право оновлювати алгоритми підрахунку, види рейтингів, порогові значення тощо (про всяк випадок 🤷). diff --git a/docs/uk/docs/index.md b/docs/uk/docs/index.md new file mode 100644 index 0000000000000..32f1f544a23f4 --- /dev/null +++ b/docs/uk/docs/index.md @@ -0,0 +1,465 @@ +

+ FastAPI +

+

+ Готовий до продакшину, високопродуктивний, простий у вивченні та швидкий для написання коду фреймворк +

+

+ + Test + + + Coverage + + + Package version + + + Supported Python versions + +

+ +--- + +**Документація**: https://fastapi.tiangolo.com + +**Програмний код**: https://github.com/tiangolo/fastapi + +--- + +FastAPI - це сучасний, швидкий (високопродуктивний), вебфреймворк для створення API за допомогою Python 3.8+,в основі якого лежить стандартна анотація типів Python. + +Ключові особливості: + +* **Швидкий**: Дуже висока продуктивність, на рівні з **NodeJS** та **Go** (завдяки Starlette та Pydantic). [Один із найшвидших фреймворків](#performance). + +* **Швидке написання коду**: Пришвидшує розробку функціоналу приблизно на 200%-300%. * +* **Менше помилок**: Зменшить кількість помилок спричинених людиною (розробником) на 40%. * +* **Інтуїтивний**: Чудова підтримка редакторами коду. Доповнення всюди. Зменште час на налагодження. +* **Простий**: Спроектований, для легкого використання та навчання. Знадобиться менше часу на читання документації. +* **Короткий**: Зведе до мінімуму дублювання коду. Кожен оголошений параметр може виконувати кілька функцій. +* **Надійний**: Ви матимете стабільний код готовий до продакшину з автоматичною інтерактивною документацією. +* **Стандартизований**: Оснований та повністю сумісний з відкритими стандартами для API: OpenAPI (попередньо відомий як Swagger) та JSON Schema. + +* оцінка на основі тестів внутрішньої команди розробників, створення продуктових застосунків. + +## Спонсори + + + +{% if sponsors %} +{% for sponsor in sponsors.gold -%} + +{% endfor -%} +{%- for sponsor in sponsors.silver -%} + +{% endfor %} +{% endif %} + + + +Other sponsors + +## Враження + +"_[...] 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._" + +
Kabir Khan - Microsoft (ref)
+ +--- + +"_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!_" + +
Brian Okken - Python Bytes podcast host (ref)
+ +--- + +"_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._" + +
Timothy Crosley - Hug creator (ref)
+ +--- + +"_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 [...]_" + +
Ines Montani - Matthew Honnibal - Explosion AI founders - spaCy creators (ref) - (ref)
+ +--- + +## **Typer**, FastAPI CLI + + + +Створюючи CLI застосунок для використання в терміналі, замість веб-API зверніть увагу на **Typer**. + +**Typer** є молодшим братом FastAPI. І це **FastAPI для CLI**. ⌨️ 🚀 + +## Вимоги + +Python 3.8+ + +FastAPI стоїть на плечах гігантів: + +* Starlette для web частини. +* Pydantic для частини даних. + +## Вставновлення + +
+ +```console +$ pip install fastapi + +---> 100% +``` + +
+ +Вам також знадобиться сервер ASGI для продакшину, наприклад Uvicorn або Hypercorn. + +
+ +```console +$ pip install uvicorn[standard] + +---> 100% +``` + +
+ +## Приклад + +### Створіть + +* Створіть файл `main.py` з: + +```Python +from typing import Union + +from fastapi import FastAPI + +app = FastAPI() + + +@app.get("/") +def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} +``` + +
+Або використайте async def... + +Якщо ваш код використовує `async` / `await`, скористайтеся `async def`: + +```Python hl_lines="9 14" +from typing import Union + +from fastapi import FastAPI + +app = FastAPI() + + +@app.get("/") +async def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +async def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} +``` + +**Примітка**: + +Стикнувшись з проблемами, не зайвим буде ознайомитися з розділом _"In a hurry?"_ про `async` та `await` у документації. + +
+ +### Запустіть + +Запустіть server з: + +
+ +```console +$ uvicorn main:app --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +INFO: Started reloader process [28720] +INFO: Started server process [28722] +INFO: Waiting for application startup. +INFO: Application startup complete. +``` + +
+ +
+Про команди uvicorn main:app --reload... + +Команда `uvicorn main:app` посилається на: + +* `main`: файл `main.py` ("Модуль" Python). +* `app`: об’єкт створений усередині `main.py` рядком `app = FastAPI()`. +* `--reload`: перезапускає сервер після зміни коду. Використовуйте виключно для розробки. + +
+ +### Перевірте + +Відкрийте браузер та введіть адресу http://127.0.0.1:8000/items/5?q=somequery. + +Ви побачите у відповідь подібний JSON: + +```JSON +{"item_id": 5, "q": "somequery"} +``` + +Ви вже створили API, який: + +* Отримує HTTP запити за _шляхами_ `/` та `/items/{item_id}`. +* Обидва _шляхи_ приймають `GET` операції (також відомі як HTTP _методи_). +* _Шлях_ `/items/{item_id}` містить _параметр шляху_ `item_id` який має бути типу `int`. +* _Шлях_ `/items/{item_id}` містить необовʼязковий `str` _параметр запиту_ `q`. + +### Інтерактивні документації API + +Перейдемо сюди http://127.0.0.1:8000/docs. + +Ви побачите автоматичну інтерактивну API документацію (створену завдяки Swagger UI): + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +### Альтернативні документації API + +Тепер перейдемо сюди http://127.0.0.1:8000/redoc. + +Ви побачите альтернативну автоматичну документацію (створену завдяки ReDoc): + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +## Приклад оновлення + +Тепер модифікуйте файл `main.py`, щоб отримати вміст запиту `PUT`. + +Оголошуйте вміст запиту за допомогою стандартних типів Python завдяки Pydantic. + +```Python hl_lines="4 9-12 25-27" +from typing import Union + +from fastapi import FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Item(BaseModel): + name: str + price: float + is_offer: Union[bool, None] = None + + +@app.get("/") +def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} + + +@app.put("/items/{item_id}") +def update_item(item_id: int, item: Item): + return {"item_name": item.name, "item_id": item_id} +``` + +Сервер повинен автоматично перезавантажуватися (тому що Ви додали `--reload` до `uvicorn` команди вище). + +### Оновлення інтерактивної API документації + +Тепер перейдемо сюди http://127.0.0.1:8000/docs. + +* Інтерактивна документація API буде автоматично оновлена, включаючи новий вміст: + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) + +* Натисніть кнопку "Try it out", це дозволить вам заповнити параметри та безпосередньо взаємодіяти з API: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png) + +* Потім натисніть кнопку "Execute", інтерфейс користувача зв'яжеться з вашим API, надішле параметри, у відповідь отримає результати та покаже їх на екрані: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png) + +### Оновлення альтернативної API документації + +Зараз перейдемо http://127.0.0.1:8000/redoc. + +* Альтернативна документація також показуватиме новий параметр і вміст запиту: + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) + +### Підсумки + +Таким чином, Ви **один раз** оголошуєте типи параметрів, тіла тощо, як параметри функції. + +Ви робите це за допомогою стандартних сучасних типів Python. + +Вам не потрібно вивчати новий синтаксис, методи чи класи конкретної бібліотеки тощо. + +Використовуючи стандартний **Python 3.8+**. + +Наприклад, для `int`: + +```Python +item_id: int +``` + +або для більш складної моделі `Item`: + +```Python +item: Item +``` + +...і з цим єдиним оголошенням Ви отримуєте: + +* Підтримку редактора, включаючи: + * Варіанти заповнення. + * Перевірку типів. +* Перевірку даних: + * Автоматичні та зрозумілі помилки, у разі некоректних даних. + * Перевірка навіть для JSON з високим рівнем вкладеності. +* Перетворення вхідних даних: з мережі до даних і типів Python. Читання з: + * JSON. + * Параметрів шляху. + * Параметрів запиту. + * Cookies. + * Headers. + * Forms. + * Файлів. +* Перетворення вихідних даних: з типів і даних Python до мережевих даних (як JSON): + * Конвертація Python типів (`str`, `int`, `float`, `bool`, `list`, тощо). + * `datetime` об'єкти. + * `UUID` об'єкти. + * Моделі бази даних. + * ...та багато іншого. +* Автоматичну інтерактивну документацію API, включаючи 2 альтернативні інтерфейси користувача: + * Swagger UI. + * ReDoc. + +--- + +Повертаючись до попереднього прикладу коду, **FastAPI**: + +* Підтвердить наявність `item_id` у шляху для запитів `GET` та `PUT`. +* Підтвердить, що `item_id` має тип `int` для запитів `GET` and `PUT`. + * Якщо це не так, клієнт побачить корисну, зрозумілу помилку. +* Перевірить, чи є необов'язковий параметр запиту з назвою `q` (а саме `http://127.0.0.1:8000/items/foo?q=somequery`) для запитів `GET`. + * Оскільки параметр `q` оголошено як `= None`, він необов'язковий. + * За відсутності `None` він був би обов'язковим (як і вміст у випадку з `PUT`). +* Для запитів `PUT` із `/items/{item_id}`, читає вміст як JSON: + * Перевірить, чи має обов'язковий атрибут `name` тип `str`. + * Перевірить, чи має обов'язковий атрибут `price` тип `float`. + * Перевірить, чи існує необов'язковий атрибут `is_offer` та чи має він тип `bool`. + * Усе це також працюватиме для глибоко вкладених об'єктів JSON. +* Автоматично конвертує із та в JSON. +* Документує все за допомогою OpenAPI, який може бути використано в: + * Інтерактивних системах документації. + * Системах автоматичної генерації клієнтського коду для багатьох мов. +* Надає безпосередньо 2 вебінтерфейси інтерактивної документації. + +--- + +Ми лише трішки доторкнулися до коду, але Ви вже маєте уявлення про те, як все працює. + +Спробуйте змінити рядок: + +```Python + return {"item_name": item.name, "item_id": item_id} +``` + +...із: + +```Python + ... "item_name": item.name ... +``` + +...на: + +```Python + ... "item_price": item.price ... +``` + +...і побачите, як ваш редактор автоматично заповнюватиме атрибути та знатиме їхні типи: + +![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) + +Для більш повного ознайомлення з додатковими функціями, перегляньте Туторіал - Посібник Користувача. + +**Spoiler alert**: туторіал - посібник користувача містить: + +* Оголошення **параметрів** з інших місць як: **headers**, **cookies**, **form fields** та **files**. +* Як встановити **перевірку обмежень** як `maximum_length` або `regex`. +* Дуже потужна і проста у використанні система **Ін'єкція Залежностей**. +* Безпека та автентифікація, включаючи підтримку **OAuth2** з **JWT tokens** та **HTTP Basic** автентифікацію. +* Досконаліші (але однаково прості) техніки для оголошення **глибоко вкладених моделей JSON** (завдяки Pydantic). +* Багато додаткових функцій (завдяки Starlette) як-от: + * **WebSockets** + * надзвичайно прості тести на основі HTTPX та `pytest` + * **CORS** + * **Cookie Sessions** + * ...та більше. + +## Продуктивність + +Незалежні тести TechEmpower показують що застосунки **FastAPI**, які працюють під керуванням Uvicorn є одними з найшвидших серед доступних фреймворків в Python, поступаючись лише Starlette та Uvicorn (які внутрішньо використовуються в FastAPI). (*) + +Щоб дізнатися більше про це, перегляньте розділ Benchmarks. + +## Необов'язкові залежності + +Pydantic використовує: + +* email_validator - для валідації електронної пошти. +* pydantic-settings - для управління налаштуваннями. +* pydantic-extra-types - для додаткових типів, що можуть бути використані з Pydantic. + + +Starlette використовує: + +* httpx - Необхідно, якщо Ви хочете використовувати `TestClient`. +* jinja2 - Необхідно, якщо Ви хочете використовувати шаблони як конфігурацію за замовчуванням. +* python-multipart - Необхідно, якщо Ви хочете підтримувати "розбір" форми за допомогою `request.form()`. +* itsdangerous - Необхідно для підтримки `SessionMiddleware`. +* pyyaml - Необхідно для підтримки Starlette `SchemaGenerator` (ймовірно, вам це не потрібно з FastAPI). +* ujson - Необхідно, якщо Ви хочете використовувати `UJSONResponse`. + +FastAPI / Starlette використовують: + +* uvicorn - для сервера, який завантажує та обслуговує вашу програму. +* orjson - Необхідно, якщо Ви хочете використовувати `ORJSONResponse`. + +Ви можете встановити все це за допомогою `pip install fastapi[all]`. + +## Ліцензія + +Цей проєкт ліцензовано згідно з умовами ліцензії MIT. diff --git a/docs/uk/docs/python-types.md b/docs/uk/docs/python-types.md new file mode 100644 index 0000000000000..e767db2fbc223 --- /dev/null +++ b/docs/uk/docs/python-types.md @@ -0,0 +1,448 @@ +# Вступ до типів Python + +Python підтримує додаткові "підказки типу" ("type hints") (також звані "анотаціями типу" ("type annotations")). + +Ці **"type hints"** є спеціальним синтаксисом, що дозволяє оголошувати тип змінної. + +За допомогою оголошення типів для ваших змінних, редактори та інструменти можуть надати вам кращу підтримку. + +Це просто **швидкий посібник / нагадування** про анотації типів у Python. Він покриває лише мінімум, необхідний щоб використовувати їх з **FastAPI**... що насправді дуже мало. + +**FastAPI** повністю базується на цих анотаціях типів, вони дають йому багато переваг. + +Але навіть якщо ви ніколи не використаєте **FastAPI**, вам буде корисно дізнатись трохи про них. + +!!! note + Якщо ви експерт у Python і ви вже знаєте усе про анотації типів - перейдіть до наступного розділу. + +## Мотивація + +Давайте почнемо з простого прикладу: + +```Python +{!../../../docs_src/python_types/tutorial001.py!} +``` + +Виклик цієї програми виводить: + +``` +John Doe +``` + +Функція виконує наступне: + +* Бере `first_name` та `last_name`. +* Конвертує кожну літеру кожного слова у верхній регістр за допомогою `title()`. +* Конкатенує їх разом із пробілом по середині. + +```Python hl_lines="2" +{!../../../docs_src/python_types/tutorial001.py!} +``` + +### Редагуйте це + +Це дуже проста програма. + +Але тепер уявіть, що ви писали це з нуля. + +У певний момент ви розпочали б визначення функції, у вас були б готові параметри... + +Але тоді вам потрібно викликати "той метод, який переводить першу літеру у верхній регістр". + +Це буде `upper`? Чи `uppercase`? `first_uppercase`? `capitalize`? + +Тоді ви спробуєте давнього друга програміста - автозаповнення редактора коду. + +Ви надрукуєте перший параметр функції, `first_name`, тоді крапку (`.`), а тоді натиснете `Ctrl+Space`, щоб запустити автозаповнення. + +Але, на жаль, ви не отримаєте нічого корисного: + + + +### Додайте типи + +Давайте змінимо один рядок з попередньої версії. + +Ми змінимо саме цей фрагмент, параметри функції, з: + +```Python + first_name, last_name +``` + +на: + +```Python + first_name: str, last_name: str +``` + +Ось і все. + +Це "type hints": + +```Python hl_lines="1" +{!../../../docs_src/python_types/tutorial002.py!} +``` + +Це не те саме, що оголошення значень за замовчуванням, як це було б з: + +```Python + first_name="john", last_name="doe" +``` + +Це зовсім інше. + +Ми використовуємо двокрапку (`:`), не дорівнює (`=`). + +І додавання анотації типу зазвичай не змінює того, що сталось би без них. + +Але тепер, уявіть що ви посеред процесу створення функції, але з анотаціями типів. + +В цей же момент, ви спробуєте викликати автозаповнення з допомогою `Ctrl+Space` і побачите: + + + +Разом з цим, ви можете прокручувати, переглядати опції, допоки ви не знайдете одну, що звучить схоже: + + + +## Більше мотивації + +Перевірте цю функцію, вона вже має анотацію типу: + +```Python hl_lines="1" +{!../../../docs_src/python_types/tutorial003.py!} +``` + +Оскільки редактор знає типи змінних, ви не тільки отримаєте автозаповнення, ви також отримаєте перевірку помилок: + + + +Тепер ви знаєте, щоб виправити це, вам потрібно перетворити `age` у строку з допомогою `str(age)`: + +```Python hl_lines="2" +{!../../../docs_src/python_types/tutorial004.py!} +``` + +## Оголошення типів + +Щойно ви побачили основне місце для оголошення анотацій типу. Як параметри функції. + +Це також основне місце, де ви б їх використовували у **FastAPI**. + +### Прості типи + +Ви можете оголошувати усі стандартні типи у Python, не тільки `str`. + +Ви можете використовувати, наприклад: + +* `int` +* `float` +* `bool` +* `bytes` + +```Python hl_lines="1" +{!../../../docs_src/python_types/tutorial005.py!} +``` + +### Generic-типи з параметрами типів + +Існують деякі структури даних, які можуть містити інші значення, наприклад `dict`, `list`, `set` та `tuple`. І внутрішні значення також можуть мати свій тип. + +Ці типи, які мають внутрішні типи, називаються "**generic**" типами. І оголосити їх можна навіть із внутрішніми типами. + +Щоб оголосити ці типи та внутрішні типи, ви можете використовувати стандартний модуль Python `typing`. Він існує спеціально для підтримки анотацій типів. + +#### Новіші версії Python + +Синтаксис із використанням `typing` **сумісний** з усіма версіями, від Python 3.6 до останніх, включаючи Python 3.9, Python 3.10 тощо. + +У міру розвитку Python **новіші версії** мають покращену підтримку анотацій типів і в багатьох випадках вам навіть не потрібно буде імпортувати та використовувати модуль `typing` для оголошення анотацій типу. + +Якщо ви можете вибрати новішу версію Python для свого проекту, ви зможете скористатися цією додатковою простотою. Дивіться кілька прикладів нижче. + +#### List (список) + +Наприклад, давайте визначимо змінну, яка буде `list` із `str`. + +=== "Python 3.8 і вище" + + З модуля `typing`, імпортуємо `List` (з великої літери `L`): + + ``` Python hl_lines="1" + {!> ../../../docs_src/python_types/tutorial006.py!} + ``` + + Оголосимо змінну з тим самим синтаксисом двокрапки (`:`). + + Як тип вкажемо `List`, який ви імпортували з `typing`. + + Оскільки список є типом, який містить деякі внутрішні типи, ви поміщаєте їх у квадратні дужки: + + ```Python hl_lines="4" + {!> ../../../docs_src/python_types/tutorial006.py!} + ``` + +=== "Python 3.9 і вище" + + Оголосимо змінну з тим самим синтаксисом двокрапки (`:`). + + Як тип вкажемо `list`. + + Оскільки список є типом, який містить деякі внутрішні типи, ви поміщаєте їх у квадратні дужки: + + ```Python hl_lines="1" + {!> ../../../docs_src/python_types/tutorial006_py39.py!} + ``` + +!!! info + Ці внутрішні типи в квадратних дужках називаються "параметрами типу". + + У цьому випадку, `str` це параметр типу переданий у `List` (або `list` у Python 3.9 і вище). + +Це означає: "змінна `items` це `list`, і кожен з елементів у цьому списку - `str`". + +!!! tip + Якщо ви використовуєте Python 3.9 і вище, вам не потрібно імпортувати `List` з `typing`, ви можете використовувати натомість тип `list`. + +Зробивши це, ваш редактор може надати підтримку навіть під час обробки елементів зі списку: + + + +Без типів цього майже неможливо досягти. + +Зверніть увагу, що змінна `item` є одним із елементів у списку `items`. + +І все ж редактор знає, що це `str`, і надає підтримку для цього. + +#### Tuple and Set (кортеж та набір) + +Ви повинні зробити те ж саме, щоб оголосити `tuple` і `set`: + +=== "Python 3.8 і вище" + + ```Python hl_lines="1 4" + {!> ../../../docs_src/python_types/tutorial007.py!} + ``` + +=== "Python 3.9 і вище" + + ```Python hl_lines="1" + {!> ../../../docs_src/python_types/tutorial007_py39.py!} + ``` + +Це означає: + +* Змінна `items_t` це `tuple` з 3 елементами, `int`, ще `int`, та `str`. +* Змінна `items_s` це `set`, і кожен його елемент типу `bytes`. + +#### Dict (словник) + +Щоб оголосити `dict`, вам потрібно передати 2 параметри типу, розділені комами. + +Перший параметр типу для ключа у `dict`. + +Другий параметр типу для значення у `dict`: + +=== "Python 3.8 і вище" + + ```Python hl_lines="1 4" + {!> ../../../docs_src/python_types/tutorial008.py!} + ``` + +=== "Python 3.9 і вище" + + ```Python hl_lines="1" + {!> ../../../docs_src/python_types/tutorial008_py39.py!} + ``` + +Це означає: + +* Змінна `prices` це `dict`: + * Ключі цього `dict` типу `str` (наприклад, назва кожного елементу). + * Значення цього `dict` типу `float` (наприклад, ціна кожного елементу). + +#### Union (об'єднання) + +Ви можете оголосити, що змінна може бути будь-яким із **кількох типів**, наприклад, `int` або `str`. + +У Python 3.6 і вище (включаючи Python 3.10) ви можете використовувати тип `Union` з `typing` і вставляти в квадратні дужки можливі типи, які можна прийняти. + +У Python 3.10 також є **альтернативний синтаксис**, у якому ви можете розділити можливі типи за допомогою вертикальної смуги (`|`). + +=== "Python 3.8 і вище" + + ```Python hl_lines="1 4" + {!> ../../../docs_src/python_types/tutorial008b.py!} + ``` + +=== "Python 3.10 і вище" + + ```Python hl_lines="1" + {!> ../../../docs_src/python_types/tutorial008b_py310.py!} + ``` + +В обох випадках це означає, що `item` може бути `int` або `str`. + +#### Possibly `None` (Optional) + +Ви можете оголосити, що значення може мати тип, наприклад `str`, але також може бути `None`. + +У Python 3.6 і вище (включаючи Python 3.10) ви можете оголосити його, імпортувавши та використовуючи `Optional` з модуля `typing`. + +```Python hl_lines="1 4" +{!../../../docs_src/python_types/tutorial009.py!} +``` + +Використання `Optional[str]` замість просто `str` дозволить редактору допомогти вам виявити помилки, коли ви могли б вважати, що значенням завжди є `str`, хоча насправді воно також може бути `None`. + +`Optional[Something]` насправді є скороченням для `Union[Something, None]`, вони еквівалентні. + +Це також означає, що в Python 3.10 ви можете використовувати `Something | None`: + +=== "Python 3.8 і вище" + + ```Python hl_lines="1 4" + {!> ../../../docs_src/python_types/tutorial009.py!} + ``` + +=== "Python 3.8 і вище - альтернатива" + + ```Python hl_lines="1 4" + {!> ../../../docs_src/python_types/tutorial009b.py!} + ``` + +=== "Python 3.10 і вище" + + ```Python hl_lines="1" + {!> ../../../docs_src/python_types/tutorial009_py310.py!} + ``` + +#### Generic типи + +Ці типи, які приймають параметри типу у квадратних дужках, називаються **Generic types** or **Generics**, наприклад: + +=== "Python 3.8 і вище" + + * `List` + * `Tuple` + * `Set` + * `Dict` + * `Union` + * `Optional` + * ...та інші. + +=== "Python 3.9 і вище" + + Ви можете використовувати ті самі вбудовані типи, як generic (з квадратними дужками та типами всередині): + + * `list` + * `tuple` + * `set` + * `dict` + + І те саме, що й у Python 3.8, із модуля `typing`: + + * `Union` + * `Optional` + * ...та інші. + +=== "Python 3.10 і вище" + + Ви можете використовувати ті самі вбудовані типи, як generic (з квадратними дужками та типами всередині): + + * `list` + * `tuple` + * `set` + * `dict` + + І те саме, що й у Python 3.8, із модуля `typing`: + + * `Union` + * `Optional` (так само як у Python 3.8) + * ...та інші. + + У Python 3.10, як альтернатива використанню `Union` та `Optional`, ви можете використовувати вертикальну смугу (`|`) щоб оголосити об'єднання типів. + +### Класи як типи + +Ви також можете оголосити клас як тип змінної. + +Скажімо, у вас є клас `Person` з імʼям: + +```Python hl_lines="1-3" +{!../../../docs_src/python_types/tutorial010.py!} +``` + +Потім ви можете оголосити змінну типу `Person`: + +```Python hl_lines="6" +{!../../../docs_src/python_types/tutorial010.py!} +``` + +І знову ж таки, ви отримуєте всю підтримку редактора: + + + +## Pydantic моделі + +Pydantic це бібліотека Python для валідації даних. + +Ви оголошуєте «форму» даних як класи з атрибутами. + +І кожен атрибут має тип. + +Потім ви створюєте екземпляр цього класу з деякими значеннями, і він перевірить ці значення, перетворить їх у відповідний тип (якщо є потреба) і надасть вам об’єкт з усіма даними. + +І ви отримуєте всю підтримку редактора з цим отриманим об’єктом. + +Приклад з документації Pydantic: + +=== "Python 3.8 і вище" + + ```Python + {!> ../../../docs_src/python_types/tutorial011.py!} + ``` + +=== "Python 3.9 і вище" + + ```Python + {!> ../../../docs_src/python_types/tutorial011_py39.py!} + ``` + +=== "Python 3.10 і вище" + + ```Python + {!> ../../../docs_src/python_types/tutorial011_py310.py!} + ``` + +!!! info + Щоб дізнатись більше про Pydantic, перегляньте його документацію. + +**FastAPI** повністю базується на Pydantic. + +Ви побачите набагато більше цього всього на практиці в [Tutorial - User Guide](tutorial/index.md){.internal-link target=_blank}. + +## Анотації типів у **FastAPI** + +**FastAPI** використовує ці підказки для виконання кількох речей. + +З **FastAPI** ви оголошуєте параметри з підказками типу, і отримуєте: + +* **Підтримку редактора**. +* **Перевірку типів**. + +...і **FastAPI** використовує ті самі оголошення для: + +* **Визначення вимог**: з параметрів шляху запиту, параметрів запиту, заголовків, тіл, залежностей тощо. +* **Перетворення даних**: із запиту в необхідний тип. +* **Перевірка даних**: що надходять від кожного запиту: + * Генерування **автоматичних помилок**, що повертаються клієнту, коли дані недійсні. +* **Документування** API за допомогою OpenAPI: + * який потім використовується для автоматичної інтерактивної документації користувальницьких інтерфейсів. + +Все це може здатися абстрактним. Не хвилюйтеся. Ви побачите все це в дії в [Туторіал - Посібник користувача](tutorial/index.md){.internal-link target=_blank}. + +Важливо те, що за допомогою стандартних типів Python в одному місці (замість того, щоб додавати більше класів, декораторів тощо), **FastAPI** зробить багато роботи за вас. + +!!! info + Якщо ви вже пройшли весь навчальний посібник і повернулися, щоб дізнатися більше про типи, ось хороший ресурс "шпаргалка" від `mypy`. diff --git a/docs/uk/docs/tutorial/body-fields.md b/docs/uk/docs/tutorial/body-fields.md new file mode 100644 index 0000000000000..eee993cbe3616 --- /dev/null +++ b/docs/uk/docs/tutorial/body-fields.md @@ -0,0 +1,116 @@ +# Тіло - Поля + +Так само як ви можете визначати додаткову валідацію та метадані у параметрах *функції обробки шляху* за допомогою `Query`, `Path` та `Body`, ви можете визначати валідацію та метадані всередині моделей Pydantic за допомогою `Field` від Pydantic. + +## Імпорт `Field` + +Спочатку вам потрібно імпортувати це: + +=== "Python 3.10+" + + ```Python hl_lines="4" + {!> ../../../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.8+" + + ```Python hl_lines="4" + {!> ../../../docs_src/body_fields/tutorial001_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip + Варто користуватись `Annotated` версією, якщо це можливо. + + ```Python hl_lines="2" + {!> ../../../docs_src/body_fields/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + Варто користуватись `Annotated` версією, якщо це можливо. + + ```Python hl_lines="4" + {!> ../../../docs_src/body_fields/tutorial001.py!} + ``` + +!!! warning + Зверніть увагу, що `Field` імпортується прямо з `pydantic`, а не з `fastapi`, як всі інші (`Query`, `Path`, `Body` тощо). + +## Оголошення атрибутів моделі + +Ви можете використовувати `Field` з атрибутами моделі: + +=== "Python 3.10+" + + ```Python hl_lines="11-14" + {!> ../../../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.8+" + + ```Python hl_lines="12-15" + {!> ../../../docs_src/body_fields/tutorial001_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip + Варто користуватись `Annotated` версією, якщо це можливо.. + + ```Python hl_lines="9-12" + {!> ../../../docs_src/body_fields/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + Варто користуватись `Annotated` версією, якщо це можливо.. + + ```Python hl_lines="11-14" + {!> ../../../docs_src/body_fields/tutorial001.py!} + ``` + +`Field` працює так само, як `Query`, `Path` і `Body`, у нього такі самі параметри тощо. + +!!! note "Технічні деталі" + Насправді, `Query`, `Path` та інші, що ви побачите далі, створюють об'єкти підкласів загального класу `Param`, котрий сам є підкласом класу `FieldInfo` з Pydantic. + + І `Field` від Pydantic також повертає екземпляр `FieldInfo`. + + `Body` також безпосередньо повертає об'єкти підкласу `FieldInfo`. І є інші підкласи, які ви побачите пізніше, що є підкласами класу Body. + + Пам'ятайте, що коли ви імпортуєте 'Query', 'Path' та інше з 'fastapi', вони фактично є функціями, які повертають спеціальні класи. + +!!! tip + Зверніть увагу, що кожен атрибут моделі із типом, значенням за замовчуванням та `Field` має ту саму структуру, що й параметр *функції обробки шляху*, з `Field` замість `Path`, `Query` і `Body`. + +## Додавання додаткової інформації + +Ви можете визначити додаткову інформацію у `Field`, `Query`, `Body` тощо. І вона буде включена у згенеровану JSON схему. + +Ви дізнаєтеся більше про додавання додаткової інформації пізніше у документації, коли вивчатимете визначення прикладів. + +!!! warning + Додаткові ключі, передані в `Field`, також будуть присутні у згенерованій схемі OpenAPI для вашого додатка. + Оскільки ці ключі не обов'язково можуть бути частиною специфікації OpenAPI, деякі інструменти OpenAPI, наприклад, [OpenAPI валідатор](https://validator.swagger.io/), можуть не працювати з вашою згенерованою схемою. + +## Підсумок + +Ви можете використовувати `Field` з Pydantic для визначення додаткових перевірок та метаданих для атрибутів моделі. + +Ви також можете використовувати додаткові іменовані аргументи для передачі додаткових метаданих JSON схеми. diff --git a/docs/uk/docs/tutorial/body.md b/docs/uk/docs/tutorial/body.md new file mode 100644 index 0000000000000..11e94e929935d --- /dev/null +++ b/docs/uk/docs/tutorial/body.md @@ -0,0 +1,213 @@ +# Тіло запиту + +Коли вам потрібно надіслати дані з клієнта (скажімо, браузера) до вашого API, ви надсилаєте їх як **тіло запиту**. + +Тіло **запиту** — це дані, надіслані клієнтом до вашого API. Тіло **відповіді** — це дані, які ваш API надсилає клієнту. + +Ваш API майже завжди має надсилати тіло **відповіді**. Але клієнтам не обов’язково потрібно постійно надсилати тіла **запитів**. + +Щоб оголосити тіло **запиту**, ви використовуєте Pydantic моделі з усією їх потужністю та перевагами. + +!!! info + Щоб надіслати дані, ви повинні використовувати один із: `POST` (більш поширений), `PUT`, `DELETE` або `PATCH`. + + Надсилання тіла із запитом `GET` має невизначену поведінку в специфікаціях, проте воно підтримується FastAPI лише для дуже складних/екстремальних випадків використання. + + Оскільки це не рекомендується, інтерактивна документація з Swagger UI не відображатиме документацію для тіла запиту під час використання `GET`, і проксі-сервери в середині можуть не підтримувати її. + +## Імпортуйте `BaseModel` від Pydantic + +Спочатку вам потрібно імпортувати `BaseModel` з `pydantic`: + +=== "Python 3.8 і вище" + + ```Python hl_lines="4" + {!> ../../../docs_src/body/tutorial001.py!} + ``` + +=== "Python 3.10 і вище" + + ```Python hl_lines="2" + {!> ../../../docs_src/body/tutorial001_py310.py!} + ``` + +## Створіть свою модель даних + +Потім ви оголошуєте свою модель даних як клас, який успадковується від `BaseModel`. + +Використовуйте стандартні типи Python для всіх атрибутів: + +=== "Python 3.8 і вище" + + ```Python hl_lines="7-11" + {!> ../../../docs_src/body/tutorial001.py!} + ``` + +=== "Python 3.10 і вище" + + ```Python hl_lines="5-9" + {!> ../../../docs_src/body/tutorial001_py310.py!} + ``` + +Так само, як і при оголошенні параметрів запиту, коли атрибут моделі має значення за замовчуванням, він не є обов’язковим. В іншому випадку це потрібно. Використовуйте `None`, щоб зробити його необов'язковим. + +Наприклад, ця модель вище оголошує JSON "`об'єкт`" (або Python `dict`), як: + +```JSON +{ + "name": "Foo", + "description": "An optional description", + "price": 45.2, + "tax": 3.5 +} +``` + +...оскільки `description` і `tax` є необов'язковими (зі значенням за замовчуванням `None`), цей JSON "`об'єкт`" також буде дійсним: + +```JSON +{ + "name": "Foo", + "price": 45.2 +} +``` + +## Оголоси її як параметр + +Щоб додати модель даних до вашої *операції шляху*, оголосіть її так само, як ви оголосили параметри шляху та запиту: + +=== "Python 3.8 і вище" + + ```Python hl_lines="18" + {!> ../../../docs_src/body/tutorial001.py!} + ``` + +=== "Python 3.10 і вище" + + ```Python hl_lines="16" + {!> ../../../docs_src/body/tutorial001_py310.py!} + ``` + +...і вкажіть її тип як модель, яку ви створили, `Item`. + +## Результати + +Лише з цим оголошенням типу Python **FastAPI** буде: + +* Читати тіло запиту як JSON. +* Перетворювати відповідні типи (якщо потрібно). +* Валідувати дані. + * Якщо дані недійсні, він поверне гарну та чітку помилку, вказуючи, де саме і які дані були неправильними. +* Надавати отримані дані у параметрі `item`. + * Оскільки ви оголосили його у функції як тип `Item`, ви також матимете всю підтримку редактора (автозаповнення, тощо) для всіх атрибутів та їх типів. +* Генерувати JSON Schema визначення для вашої моделі, ви також можете використовувати їх де завгодно, якщо це має сенс для вашого проекту. +* Ці схеми будуть частиною згенерованої схеми OpenAPI і використовуватимуться автоматичною документацією інтерфейсу користувача. + +## Автоматична документація + +Схеми JSON ваших моделей будуть частиною вашої схеми, згенерованої OpenAPI, і будуть показані в інтерактивній API документації: + + + +А також використовуватимуться в API документації всередині кожної *операції шляху*, якій вони потрібні: + + + +## Підтримка редактора + +У вашому редакторі, всередині вашої функції, ви будете отримувати підказки типу та завершення скрізь (це б не сталося, якби ви отримали `dict` замість моделі Pydantic): + + + +Ви також отримуєте перевірку помилок на наявність операцій з неправильним типом: + + + +Це не випадково, весь каркас був побудований навколо цього дизайну. + +І він був ретельно перевірений на етапі проектування, перед будь-яким впровадженням, щоб переконатися, що він працюватиме з усіма редакторами. + +Були навіть деякі зміни в самому Pydantic, щоб підтримати це. + +Попередні скріншоти були зроблені у Visual Studio Code. + +Але ви отримаєте ту саму підтримку редактора у PyCharm та більшість інших редакторів Python: + + + +!!! tip + Якщо ви використовуєте PyCharm як ваш редактор, ви можете використати Pydantic PyCharm Plugin. + + Він покращує підтримку редакторів для моделей Pydantic за допомогою: + + * автозаповнення + * перевірки типу + * рефакторингу + * пошуку + * інспекції + +## Використовуйте модель + +Усередині функції ви можете отримати прямий доступ до всіх атрибутів об’єкта моделі: + +=== "Python 3.8 і вище" + + ```Python hl_lines="21" + {!> ../../../docs_src/body/tutorial002.py!} + ``` + +=== "Python 3.10 і вище" + + ```Python hl_lines="19" + {!> ../../../docs_src/body/tutorial002_py310.py!} + ``` + +## Тіло запиту + параметри шляху + +Ви можете одночасно оголошувати параметри шляху та тіло запиту. + +**FastAPI** розпізнає, що параметри функції, які відповідають параметрам шляху, мають бути **взяті з шляху**, а параметри функції, які оголошуються як моделі Pydantic, **взяті з тіла запиту**. + +=== "Python 3.8 і вище" + + ```Python hl_lines="17-18" + {!> ../../../docs_src/body/tutorial003.py!} + ``` + +=== "Python 3.10 і вище" + + ```Python hl_lines="15-16" + {!> ../../../docs_src/body/tutorial003_py310.py!} + ``` + +## Тіло запиту + шлях + параметри запиту + +Ви також можете оголосити параметри **тіло**, **шлях** і **запит** одночасно. + +**FastAPI** розпізнає кожен з них і візьме дані з потрібного місця. + +=== "Python 3.8 і вище" + + ```Python hl_lines="18" + {!> ../../../docs_src/body/tutorial004.py!} + ``` + +=== "Python 3.10 і вище" + + ```Python hl_lines="16" + {!> ../../../docs_src/body/tutorial004_py310.py!} + ``` + +Параметри функції будуть розпізнаватися наступним чином: + +* Якщо параметр також оголошено в **шляху**, він використовуватиметься як параметр шляху. +* Якщо параметр має **сингулярний тип** (наприклад, `int`, `float`, `str`, `bool` тощо), він буде інтерпретуватися як параметр **запиту**. +* Якщо параметр оголошується як тип **Pydantic моделі**, він інтерпретується як **тіло** запиту. + +!!! note + FastAPI буде знати, що значення "q" не є обов'язковим через значення за замовчуванням "= None". + + `Optional` у `Optional[str]` не використовується FastAPI, але дозволить вашому редактору надати вам кращу підтримку та виявляти помилки. + +## Без Pydantic + +Якщо ви не хочете використовувати моделі Pydantic, ви також можете використовувати параметри **Body**. Перегляньте документацію для [Тіло – Кілька параметрів: сингулярні значення в тілі](body-multiple-params.md#singular-values-in-body){.internal-link target=_blank}. diff --git a/docs/uk/docs/tutorial/cookie-params.md b/docs/uk/docs/tutorial/cookie-params.md new file mode 100644 index 0000000000000..199b938397bc4 --- /dev/null +++ b/docs/uk/docs/tutorial/cookie-params.md @@ -0,0 +1,96 @@ +# Параметри Cookie + +Ви можете визначити параметри Cookie таким же чином, як визначаються параметри `Query` і `Path`. + +## Імпорт `Cookie` + +Спочатку імпортуйте `Cookie`: + +=== "Python 3.10+" + + ```Python hl_lines="3" + {!> ../../../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.8+" + + ```Python hl_lines="3" + {!> ../../../docs_src/cookie_params/tutorial001_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip + Бажано використовувати `Annotated` версію, якщо це можливо. + + ```Python hl_lines="1" + {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + Бажано використовувати `Annotated` версію, якщо це можливо. + + ```Python hl_lines="3" + {!> ../../../docs_src/cookie_params/tutorial001.py!} + ``` + +## Визначення параметрів `Cookie` + +Потім визначте параметри cookie, використовуючи таку ж конструкцію як для `Path` і `Query`. + +Перше значення це значення за замовчуванням, ви можете також передати всі додаткові параметри валідації чи анотації: + +=== "Python 3.10+" + + ```Python hl_lines="9" + {!> ../../../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.8+" + + ```Python hl_lines="10" + {!> ../../../docs_src/cookie_params/tutorial001_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip + Бажано використовувати `Annotated` версію, якщо це можливо. + + ```Python hl_lines="7" + {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + Бажано використовувати `Annotated` версію, якщо це можливо. + + ```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/uk/docs/tutorial/encoder.md b/docs/uk/docs/tutorial/encoder.md new file mode 100644 index 0000000000000..b6583341f3df3 --- /dev/null +++ b/docs/uk/docs/tutorial/encoder.md @@ -0,0 +1,42 @@ +# JSON Compatible Encoder + +Існують випадки, коли вам може знадобитися перетворити тип даних (наприклад, модель Pydantic) в щось сумісне з JSON (наприклад, `dict`, `list`, і т. д.). + +Наприклад, якщо вам потрібно зберегти це в базі даних. + +Для цього, **FastAPI** надає `jsonable_encoder()` функцію. + +## Використання `jsonable_encoder` + +Давайте уявимо, що у вас є база даних `fake_db`, яка приймає лише дані, сумісні з JSON. + +Наприклад, вона не приймає об'єкти типу `datetime`, оскільки вони не сумісні з JSON. + +Отже, об'єкт типу `datetime` потрібно перетворити в рядок `str`, який містить дані в ISO форматі. + +Тим самим способом ця база даних не прийматиме об'єкт типу Pydantic model (об'єкт з атрибутами), а лише `dict`. + +Ви можете використовувати `jsonable_encoder` для цього. + +Вона приймає об'єкт, такий як Pydantic model, і повертає його версію, сумісну з JSON: + +=== "Python 3.10+" + + ```Python hl_lines="4 21" + {!> ../../../docs_src/encoder/tutorial001_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="5 22" + {!> ../../../docs_src/encoder/tutorial001.py!} + ``` + +У цьому прикладі вона конвертує Pydantic model у `dict`, а `datetime` у `str`. + +Результат виклику цієї функції - це щось, що можна кодувати з використанням стандарту Python `json.dumps()`. + +Вона не повертає велику строку `str`, яка містить дані у форматі JSON (як строка). Вона повертає стандартну структуру даних Python (наприклад `dict`) із значеннями та підзначеннями, які є сумісними з JSON. + +!!! Примітка + `jsonable_encoder` фактично використовується **FastAPI** внутрішньо для перетворення даних. Проте вона корисна в багатьох інших сценаріях. diff --git a/docs/uk/docs/tutorial/extra-data-types.md b/docs/uk/docs/tutorial/extra-data-types.md new file mode 100644 index 0000000000000..01852803ad0b9 --- /dev/null +++ b/docs/uk/docs/tutorial/extra-data-types.md @@ -0,0 +1,130 @@ +# Додаткові типи даних + +До цього часу, ви використовували загальнопоширені типи даних, такі як: + +* `int` +* `float` +* `str` +* `bool` + +Але можна також використовувати більш складні типи даних. + +І ви все ще матимете ті ж можливості, які були показані до цього: + +* Чудова підтримка редактора. +* Конвертація даних з вхідних запитів. +* Конвертація даних для відповіді. +* Валідація даних. +* Автоматична анотація та документація. + +## Інші типи даних + +Ось додаткові типи даних для використання: + +* `UUID`: + * Стандартний "Універсальний Унікальний Ідентифікатор", який часто використовується як ідентифікатор у багатьох базах даних та системах. + * У запитах та відповідях буде представлений як `str`. +* `datetime.datetime`: + * Пайтонівський `datetime.datetime`. + * У запитах та відповідях буде представлений як `str` в форматі ISO 8601, як: `2008-09-15T15:53:00+05:00`. +* `datetime.date`: + * Пайтонівський `datetime.date`. + * У запитах та відповідях буде представлений як `str` в форматі ISO 8601, як: `2008-09-15`. +* `datetime.time`: + * Пайтонівський `datetime.time`. + * У запитах та відповідях буде представлений як `str` в форматі ISO 8601, як: `14:23:55.003`. +* `datetime.timedelta`: + * Пайтонівський `datetime.timedelta`. + * У запитах та відповідях буде представлений як `float` загальної кількості секунд. + * Pydantic також дозволяє представляти це як "ISO 8601 time diff encoding", більше інформації дивись у документації. +* `frozenset`: + * У запитах і відповідях це буде оброблено так само, як і `set`: + * У запитах список буде зчитано, дублікати будуть видалені та він буде перетворений на `set`. + * У відповідях, `set` буде перетворений на `list`. + * Згенерована схема буде вказувати, що значення `set` є унікальними (з використанням JSON Schema's `uniqueItems`). +* `bytes`: + * Стандартний Пайтонівський `bytes`. + * У запитах і відповідях це буде оброблено як `str`. + * Згенерована схема буде вказувати, що це `str` з "форматом" `binary`. +* `Decimal`: + * Стандартний Пайтонівський `Decimal`. + * У запитах і відповідях це буде оброблено так само, як і `float`. +* Ви можете перевірити всі дійсні типи даних Pydantic тут: типи даних Pydantic. + +## Приклад + +Ось приклад *path operation* з параметрами, використовуючи деякі з вищезазначених типів. + +=== "Python 3.10+" + + ```Python hl_lines="1 3 12-16" + {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="1 3 12-16" + {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="1 3 13-17" + {!> ../../../docs_src/extra_data_types/tutorial001_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip + Бажано використовувати `Annotated` версію, якщо це можливо. + + ```Python hl_lines="1 2 11-15" + {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + Бажано використовувати `Annotated` версію, якщо це можливо. + + ```Python hl_lines="1 2 12-16" + {!> ../../../docs_src/extra_data_types/tutorial001.py!} + ``` + +Зверніть увагу, що параметри всередині функції мають свій звичайний тип даних, і ви можете, наприклад, виконувати звичайні маніпуляції з датами, такі як: + +=== "Python 3.10+" + + ```Python hl_lines="18-19" + {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="18-19" + {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="19-20" + {!> ../../../docs_src/extra_data_types/tutorial001_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip + Бажано використовувати `Annotated` версію, якщо це можливо. + + ```Python hl_lines="17-18" + {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + Бажано використовувати `Annotated` версію, якщо це можливо. + + ```Python hl_lines="18-19" + {!> ../../../docs_src/extra_data_types/tutorial001.py!} + ``` diff --git a/docs/uk/docs/tutorial/index.md b/docs/uk/docs/tutorial/index.md new file mode 100644 index 0000000000000..e5bae74bc9833 --- /dev/null +++ b/docs/uk/docs/tutorial/index.md @@ -0,0 +1,80 @@ +# Туторіал - Посібник користувача + +У цьому посібнику показано, як користуватися **FastAPI** з більшістю його функцій, крок за кроком. + +Кожен розділ поступово надбудовується на попередні, але він структурований на окремі теми, щоб ви могли перейти безпосередньо до будь-якої конкретної, щоб вирішити ваші конкретні потреби API. + +Він також створений як довідник для роботи у майбутньому. + +Тож ви можете повернутися і побачити саме те, що вам потрібно. + +## Запустіть код + +Усі блоки коду можна скопіювати та використовувати безпосередньо (це фактично перевірені файли Python). + +Щоб запустити будь-який із прикладів, скопіюйте код у файл `main.py` і запустіть `uvicorn` за допомогою: + +
+ +```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. +``` + +
+ +**ДУЖЕ радимо** написати або скопіювати код, відредагувати його та запустити локально. + +Використання його у своєму редакторі – це те, що дійсно показує вам переваги FastAPI, бачите, як мало коду вам потрібно написати, всі перевірки типів, автозаповнення тощо. + +--- + +## Встановлення FastAPI + +Першим кроком є встановлення FastAPI. + +Для туторіалу ви можете встановити його з усіма необов’язковими залежностями та функціями: + +
+ +```console +$ pip install "fastapi[all]" + +---> 100% +``` + +
+ +...який також включає `uvicorn`, який ви можете використовувати як сервер, який запускає ваш код. + +!!! note + Ви також можете встановити його частина за частиною. + + Це те, що ви, ймовірно, зробили б, коли захочете розгорнути свою програму у виробничому середовищі: + + ``` + pip install fastapi + ``` + + Також встановіть `uvicorn`, щоб він працював як сервер: + + ``` + pip install "uvicorn[standard]" + ``` + + І те саме для кожної з опціональних залежностей, які ви хочете використовувати. + +## Розширений посібник користувача + +Існує також **Розширений посібник користувача**, який ви зможете прочитати пізніше після цього **Туторіал - Посібник користувача**. + +**Розширений посібник користувача** засновано на цьому, використовує ті самі концепції та навчає вас деяким додатковим функціям. + +Але вам слід спочатку прочитати **Туторіал - Посібник користувача** (те, що ви зараз читаєте). + +Він розроблений таким чином, що ви можете створити повну програму лише за допомогою **Туторіал - Посібник користувача**, а потім розширити її різними способами, залежно від ваших потреб, використовуючи деякі з додаткових ідей з **Розширеного посібника користувача** . diff --git a/docs/uk/mkdocs.yml b/docs/uk/mkdocs.yml new file mode 100644 index 0000000000000..de18856f445aa --- /dev/null +++ b/docs/uk/mkdocs.yml @@ -0,0 +1 @@ +INHERIT: ../en/mkdocs.yml diff --git a/docs/ur/docs/benchmarks.md b/docs/ur/docs/benchmarks.md new file mode 100644 index 0000000000000..9fc793e6fc60a --- /dev/null +++ b/docs/ur/docs/benchmarks.md @@ -0,0 +1,52 @@ +# بینچ مارکس + +انڈیپنڈنٹ ٹیک امپور بینچ مارک **FASTAPI** Uvicorn کے تحت چلنے والی ایپلی کیشنز کو ایک تیز رفتار Python فریم ورک میں سے ایک ، صرف Starlette اور Uvicorn کے نیچے ( FASTAPI کے ذریعہ اندرونی طور پر استعمال کیا جاتا ہے ) (*) + +لیکن جب بینچ مارک اور موازنہ کی جانچ پڑتال کرتے ہو تو آپ کو مندرجہ ذیل بات ذہن میں رکھنی چاہئے. + +## بینچ مارک اور رفتار + +جب آپ بینچ مارک کی جانچ کرتے ہیں تو ، مساوی کے مقابلے میں مختلف اقسام کے متعدد اوزار دیکھنا عام ہے. + +خاص طور پر ، Uvicorn, Starlette اور FastAPI کو دیکھنے کے لئے ( بہت سے دوسرے ٹولز ) کے ساتھ موازنہ کیا گیا. + +ٹول کے ذریعہ حل ہونے والا آسان مسئلہ ، اس کی بہتر کارکردگی ہوگی. اور زیادہ تر بینچ مارک ٹول کے ذریعہ فراہم کردہ اضافی خصوصیات کی جانچ نہیں کرتے ہیں. + +درجہ بندی کی طرح ہے: + +
    +
  • ASGI :Uvicorn سرور
  • +
      +
    • Starlette: (Uvicorn استعمال کرتا ہے) ایک ویب مائیکرو فریم ورک
    • +
        +
      • FastAPI: (Starlette کا استعمال کرتا ہے) ایک API مائکرو فریم ورک جس میں APIs بنانے کے لیے کئی اضافی خصوصیات ہیں، ڈیٹا کی توثیق وغیرہ کے ساتھ۔
      • +
      +
    +
+ +
    +
  • Uvicorn:
  • +
      +
    • بہترین کارکردگی ہوگی، کیونکہ اس میں سرور کے علاوہ زیادہ اضافی کوڈ نہیں ہے۔
    • +
    • آپ براہ راست Uvicorn میں درخواست نہیں لکھیں گے۔ اس کا مطلب یہ ہوگا کہ آپ کے کوڈ میں کم و بیش، کم از کم، Starlette (یا FastAPI) کی طرف سے فراہم کردہ تمام کوڈ شامل کرنا ہوں گے۔ اور اگر آپ نے ایسا کیا تو، آپ کی حتمی ایپلیکیشن کا وہی اوور ہیڈ ہوگا جیسا کہ ایک فریم ورک استعمال کرنے اور آپ کے ایپ کوڈ اور کیڑے کو کم سے کم کرنا۔
    • +
    • اگر آپ Uvicorn کا موازنہ کر رہے ہیں تو اس کا موازنہ Daphne، Hypercorn، uWSGI وغیرہ ایپلیکیشن سرورز سے کریں۔
    • +
    +
+
    +
  • Starlette:
  • +
      +
    • Uvicorn کے بعد اگلی بہترین کارکردگی ہوگی۔ درحقیقت، Starlette چلانے کے لیے Uvicorn کا استعمال کرتی ہے۔ لہذا، یہ شاید زیادہ کوڈ پر عمل درآمد کرکے Uvicorn سے "سست" ہوسکتا ہے۔
    • +
    • لیکن یہ آپ کو آسان ویب ایپلیکیشنز بنانے کے لیے ٹولز فراہم کرتا ہے، راستوں پر مبنی روٹنگ کے ساتھ، وغیرہ۔
    • +
    • اگر آپ سٹارلیٹ کا موازنہ کر رہے ہیں تو اس کا موازنہ Sanic، Flask، Django وغیرہ سے کریں۔ ویب فریم ورکس (یا مائیکرو فریم ورکس)
    • +
    +
+
    +
  • FastAPI:
  • +
      +
    • جس طرح سے Uvicorn Starlette کا استعمال کرتا ہے اور اس سے تیز نہیں ہو سکتا، Starlette FastAPI کا استعمال کرتا ہے، اس لیے یہ اس سے تیز نہیں ہو سکتا۔
    • +
    • Starlette FastAPI کے اوپری حصے میں مزید خصوصیات فراہم کرتا ہے۔ وہ خصوصیات جن کی آپ کو APIs بناتے وقت تقریباً ہمیشہ ضرورت ہوتی ہے، جیسے ڈیٹا کی توثیق اور سیریلائزیشن۔ اور اسے استعمال کرنے سے، آپ کو خودکار دستاویزات مفت میں مل جاتی ہیں (خودکار دستاویزات چلنے والی ایپلی کیشنز میں اوور ہیڈ کو بھی شامل نہیں کرتی ہیں، یہ اسٹارٹ اپ پر تیار ہوتی ہیں)۔
    • +
    • اگر آپ نے FastAPI کا استعمال نہیں کیا ہے اور Starlette کو براہ راست استعمال کیا ہے (یا کوئی دوسرا ٹول، جیسے Sanic، Flask، Responder، وغیرہ) آپ کو تمام ڈیٹا کی توثیق اور سیریلائزیشن کو خود نافذ کرنا ہوگا۔ لہذا، آپ کی حتمی ایپلیکیشن اب بھی وہی اوور ہیڈ ہوگی جیسا کہ اسے FastAPI کا استعمال کرتے ہوئے بنایا گیا تھا۔ اور بہت سے معاملات میں، یہ ڈیٹا کی توثیق اور سیریلائزیشن ایپلی کیشنز میں لکھے گئے کوڈ کی سب سے بڑی مقدار ہے۔
    • +
    • لہذا، FastAPI کا استعمال کرکے آپ ترقیاتی وقت، Bugs، کوڈ کی لائنوں کی بچت کر رہے ہیں، اور شاید آپ کو وہی کارکردگی (یا بہتر) ملے گی اگر آپ اسے استعمال نہیں کرتے (جیسا کہ آپ کو یہ سب اپنے کوڈ میں لاگو کرنا ہوگا۔ )
    • +
    • اگر آپ FastAPI کا موازنہ کر رہے ہیں، تو اس کا موازنہ ویب ایپلیکیشن فریم ورک (یا ٹولز کے سیٹ) سے کریں جو ڈیٹا کی توثیق، سیریلائزیشن اور دستاویزات فراہم کرتا ہے، جیسے Flask-apispec، NestJS، Molten، وغیرہ۔ مربوط خودکار ڈیٹا کی توثیق، سیریلائزیشن اور دستاویزات کے ساتھ فریم ورک۔
    • +
    +
diff --git a/docs/ur/mkdocs.yml b/docs/ur/mkdocs.yml new file mode 100644 index 0000000000000..de18856f445aa --- /dev/null +++ b/docs/ur/mkdocs.yml @@ -0,0 +1 @@ +INHERIT: ../en/mkdocs.yml diff --git a/docs/vi/docs/features.md b/docs/vi/docs/features.md new file mode 100644 index 0000000000000..9edb1c8fa2b91 --- /dev/null +++ b/docs/vi/docs/features.md @@ -0,0 +1,197 @@ +# Tính năng + +## Tính năng của FastAPI + +**FastAPI** cho bạn những tính năng sau: + +### Dựa trên những tiêu chuẩn mở + +* OpenAPI cho việc tạo API, bao gồm những khai báo về đường dẫn các toán tử, tham số, body requests, cơ chế bảo mật, etc. +* Tự động tài liệu hóa data model theo JSON Schema (OpenAPI bản thân nó được dựa trên JSON Schema). +* Được thiết kế xung quanh các tiêu chuẩn này sau khi nghiên cứu tỉ mỉ thay vì chỉ suy nghĩ đơn giản và sơ xài. +* Điều này cho phép tự động hóa **trình sinh code client** cho nhiều ngôn ngữ lập trình khác nhau. + +### Tự động hóa tài liệu + + +Tài liệu tương tác API và web giao diện người dùng. Là một framework được dựa trên OpenAPI do đó có nhiều tùy chọn giao diện cho tài liệu API, 2 giao diện bên dưới là mặc định. + +* Swagger UI, với giao diện khám phá, gọi và kiểm thử API trực tiếp từ trình duyệt. + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) + +* Thay thế với tài liệu API với ReDoc. + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) + +### Chỉ cần phiên bản Python hiện đại + +Tất cả được dựa trên khai báo kiểu dữ liệu chuẩn của **Python 3.8** (cảm ơn Pydantic). Bạn không cần học cú pháp mới, chỉ cần biết chuẩn Python hiện đại. + +Nếu bạn cần 2 phút để làm mới lại cách sử dụng các kiểu dữ liệu mới của Python (thậm chí nếu bạn không sử dụng FastAPI), xem hướng dẫn ngắn: [Kiểu dữ liệu Python](python-types.md){.internal-link target=_blank}. + +Bạn viết chuẩn Python với kiểu dữ liệu như sau: + +```Python +from datetime import date + +from pydantic import BaseModel + +# Declare a variable as a str +# and get editor support inside the function +def main(user_id: str): + return user_id + + +# A Pydantic model +class User(BaseModel): + id: int + name: str + joined: date +``` + +Sau đó có thể được sử dụng: + +```Python +my_user: User = User(id=3, name="John Doe", joined="2018-07-19") + +second_user_data = { + "id": 4, + "name": "Mary", + "joined": "2018-11-30", +} + +my_second_user: User = User(**second_user_data) +``` + +!!! info + `**second_user_data` nghĩa là: + + Truyền các khóa và giá trị của dict `second_user_data` trực tiếp như các tham số kiểu key-value, tương đương với: `User(id=4, name="Mary", joined="2018-11-30")` + +### Được hỗ trợ từ các trình soạn thảo + + +Toàn bộ framework được thiết kế để sử dụng dễ dàng và trực quan, toàn bộ quyết định đã được kiểm thử trên nhiều trình soạn thảo thậm chí trước khi bắt đầu quá trình phát triển, để chắc chắn trải nghiệm phát triển là tốt nhất. + +Trong lần khảo sát cuối cùng dành cho các lập trình viên Python, đã rõ ràng rằng đa số các lập trình viên sử dụng tính năng "autocompletion". + +Toàn bộ framework "FastAPI" phải đảm bảo rằng: autocompletion hoạt động ở mọi nơi. Bạn sẽ hiếm khi cần quay lại để đọc tài liệu. + +Đây là các trình soạn thảo có thể giúp bạn: + +* trong Visual Studio Code: + +![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) + +* trong PyCharm: + +![editor support](https://fastapi.tiangolo.com/img/pycharm-completion.png) + +Bạn sẽ có được auto-completion trong code, thậm chí trước đó là không thể. Như trong ví dụ, khóa `price` bên trong một JSON (đó có thể được lồng nhau) đến từ một request. + +Không còn nhập sai tên khóa, quay đi quay lại giữa các tài liệu hoặc cuộn lên cuộn xuống để tìm xem cuối cùng bạn đã sử dụng `username` hay `user_name`. + +### Ngắn gọn + +FastAPI có các giá trị mặc định hợp lý cho mọi thứ, với các cấu hình tùy chọn ở mọi nơi. Tất cả các tham số có thể được tinh chỉnh để thực hiện những gì bạn cần và để định nghĩa API bạn cần. + +Nhưng mặc định, tất cả **đều hoạt động**. + +### Validation + +* Validation cho đa số (hoặc tất cả?) **các kiểu dữ liệu** Python, bao gồm: + * JSON objects (`dict`). + * Mảng JSON (`list`) định nghĩa kiểu dữ liệu từng phần tử. + * Xâu (`str`), định nghĩa độ dài lớn nhất, nhỏ nhất. + * Số (`int`, `float`) với các giá trị lớn nhất, nhỏ nhất, etc. + +* Validation cho nhiều kiểu dữ liệu bên ngoài như: + * URL. + * Email. + * UUID. + * ...và nhiều cái khác. + +Tất cả validation được xử lí bằng những thiết lập tốt và mạnh mẽ của **Pydantic**. + +### Bảo mật và xác thực + +Bảo mật và xác thực đã tích hợp mà không làm tổn hại tới cơ sở dữ liệu hoặc data models. + +Tất cả cơ chế bảo mật định nghĩa trong OpenAPI, bao gồm: + +* HTTP Basic. +* **OAuth2** (với **JWT tokens**). Xem hướng dẫn [OAuth2 with JWT](tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. +* API keys in: + * Headers. + * Các tham số trong query string. + * Cookies, etc. + +Cộng với tất cả các tính năng bảo mật từ Starlette (bao gồm **session cookies**). + +Tất cả được xây dựng dưới dạng các công cụ và thành phần có thể tái sử dụng, dễ dàng tích hợp với hệ thống, kho lưu trữ dữ liệu, cơ sở dữ liệu quan hệ và NoSQL của bạn,... + +### Dependency Injection + +FastAPI bao gồm một hệ thống Dependency Injection vô cùng dễ sử dụng nhưng vô cùng mạnh mẽ. + +* Thậm chí, các dependency có thể có các dependency khác, tạo thành một phân cấp hoặc **"một đồ thị" của các dependency**. +* Tất cả **được xử lí tự động** bởi framework. +* Tất cả các dependency có thể yêu cầu dữ liệu từ request và **tăng cường các ràng buộc từ đường dẫn** và tự động tài liệu hóa. +* **Tự động hóa validation**, thậm chí với các tham số *đường dẫn* định nghĩa trong các dependency. +* Hỗ trợ hệ thống xác thực người dùng phức tạp, **các kết nối cơ sở dữ liệu**,... +* **Không làm tổn hại** cơ sở dữ liệu, frontends,... Nhưng dễ dàng tích hợp với tất cả chúng. + +### Không giới hạn "plug-ins" + +Hoặc theo một cách nào khác, không cần chúng, import và sử dụng code bạn cần. + +Bất kì tích hợp nào được thiết kế để sử dụng đơn giản (với các dependency), đến nỗi bạn có thể tạo một "plug-in" cho ứng dụng của mình trong 2 dòng code bằng cách sử dụng cùng một cấu trúc và cú pháp được sử dụng cho *path operations* của bạn. + +### Đã được kiểm thử + +* 100% test coverage. +* 100% type annotated code base. +* Được sử dụng cho các ứng dụng sản phẩm. + +## Tính năng của Starlette + +`FastAPI` is thực sự là một sub-class của `Starlette`. Do đó, nếu bạn đã biết hoặc đã sử dụng Starlette, đa số các chức năng sẽ làm việc giống như vậy. + +Với **FastAPI**, bạn có được tất cả những tính năng của **Starlette**: + +* Hiệu năng thực sự ấn tượng. Nó là một trong nhưng framework Python nhanh nhất, khi so sánh với **NodeJS** và **Go**. +* Hỗ trợ **WebSocket**. +* In-process background tasks. +* Startup and shutdown events. +* Client cho kiểm thử xây dựng trên HTTPX. +* **CORS**, GZip, Static Files, Streaming responses. +* Hỗ trợ **Session and Cookie**. +* 100% test coverage. +* 100% type annotated codebase. + +## Tính năng của Pydantic + +**FastAPI** tương thích đầy đủ với (và dựa trên) Pydantic. Do đó, bất kì code Pydantic nào bạn thêm vào cũng sẽ hoạt động. + +Bao gồm các thư viện bên ngoài cũng dựa trên Pydantic, như ORMs, ODMs cho cơ sở dữ liệu. + +Nó cũng có nghĩa là trong nhiều trường hợp, bạn có thể truyền cùng object bạn có từ một request **trực tiếp cho cơ sở dữ liệu**, vì mọi thứ được validate tự động. + +Điều tương tự áp dụng cho các cách khác nhau, trong nhiều trường hợp, bạn có thể chỉ truyền object từ cơ sở dữ liêu **trực tiếp tới client**. + +Với **FastAPI**, bạn có tất cả những tính năng của **Pydantic** (FastAPI dựa trên Pydantic cho tất cả những xử lí về dữ liệu): + +* **Không gây rối não**: + * Không cần học ngôn ngữ mô tả cấu trúc mới. + * Nếu bạn biết kiểu dữ liệu Python, bạn biết cách sử dụng Pydantic. +* Sử dụng tốt với **IDE/linter/não của bạn**: + + * Bởi vì các cấu trúc dữ liệu của Pydantic chỉ là các instances của class bạn định nghĩa; auto-completion, linting, mypy và trực giác của bạn nên làm việc riêng biệt với những dữ liệu mà bạn đã validate. +* Validate **các cấu trúc phức tạp**: + * Sử dụng các models Pydantic phân tầng, `List` và `Dict` của Python `typing`,... + * Và các validators cho phép các cấu trúc dữ liệu phức tạp trở nên rõ ràng và dễ dàng để định nghĩa, kiểm tra và tài liệu hóa thành JSON Schema. + * Bạn có thể có các object **JSON lồng nhau** và tất cả chúng đã validate và annotated. +* **Có khả năng mở rộng**: + * Pydantic cho phép bạn tùy chỉnh kiểu dữ liệu bằng việc định nghĩa hoặc bạn có thể mở rộng validation với các decorator trong model. +* 100% test coverage. diff --git a/docs/vi/docs/index.md b/docs/vi/docs/index.md new file mode 100644 index 0000000000000..3ade853e2838f --- /dev/null +++ b/docs/vi/docs/index.md @@ -0,0 +1,472 @@ +

+ FastAPI +

+

+ FastAPI framework, hiệu năng cao, dễ học, dễ code, sẵn sàng để tạo ra sản phẩm +

+

+ + Test + + + Coverage + + + Package version + + + Supported Python versions + +

+ +--- + +**Tài liệu**: https://fastapi.tiangolo.com + +**Mã nguồn**: https://github.com/tiangolo/fastapi + +--- + +FastAPI là một web framework hiện đại, hiệu năng cao để xây dựng web APIs với Python 3.8+ dựa trên tiêu chuẩn Python type hints. + +Những tính năng như: + +* **Nhanh**: Hiệu năng rất cao khi so sánh với **NodeJS** và **Go** (cảm ơn Starlette và Pydantic). [Một trong những Python framework nhanh nhất](#performance). +* **Code nhanh**: Tăng tốc độ phát triển tính năng từ 200% tới 300%. * +* **Ít lỗi hơn**: Giảm khoảng 40% những lỗi phát sinh bởi con người (nhà phát triển). * +* **Trực giác tốt hơn**: Được các trình soạn thảo hỗ tuyệt vời. Completion mọi nơi. Ít thời gian gỡ lỗi. +* **Dễ dàng**: Được thiết kế để dễ dàng học và sử dụng. Ít thời gian đọc tài liệu. +* **Ngắn**: Tối thiểu code bị trùng lặp. Nhiều tính năng được tích hợp khi định nghĩa tham số. Ít lỗi hơn. +* **Tăng tốc**: Có được sản phẩm cùng với tài liệu (được tự động tạo) có thể tương tác. +* **Được dựa trên các tiêu chuẩn**: Dựa trên (và hoàn toàn tương thích với) các tiêu chuẩn mở cho APIs : OpenAPI (trước đó được biết đến là Swagger) và JSON Schema. + +* ước tính được dựa trên những kiểm chứng trong nhóm phát triển nội bộ, xây dựng các ứng dụng sản phẩm. + +## Nhà tài trợ + + + +{% if sponsors %} +{% for sponsor in sponsors.gold -%} + +{% endfor -%} +{%- for sponsor in sponsors.silver -%} + +{% endfor %} +{% endif %} + + + +Những nhà tài trợ khác + +## Ý kiến đánh giá + +"_[...] Tôi đang sử dụng **FastAPI** vô cùng nhiều vào những ngày này. [...] Tôi thực sự đang lên kế hoạch sử dụng nó cho tất cả các nhóm **dịch vụ ML tại Microsoft**. Một vài trong số đó đang tích hợp vào sản phẩm lõi của **Window** và một vài sản phẩm cho **Office**._" + +
Kabir Khan - Microsoft (ref)
+ +--- + +"_Chúng tôi tích hợp thư viện **FastAPI** để sinh ra một **REST** server, nó có thể được truy vấn để thu được những **dự đoán**._ [bởi Ludwid] " + +
Piero Molino, Yaroslav Dudin, và Sai Sumanth Miryala - Uber (ref)
+ +--- + +"_**Netflix** vui mừng thông báo việc phát hành framework mã nguồn mở của chúng tôi cho *quản lí khủng hoảng* tập trung: **Dispatch**! [xây dựng với **FastAPI**]_" + +
Kevin Glisson, Marc Vilanova, Forest Monsen - Netflix (ref)
+ +--- + +"_Tôi vô cùng hào hứng về **FastAPI**. Nó rất thú vị_" + +
Brian Okken - Python Bytes podcast host (ref)
+ +--- + +"_Thành thật, những gì bạn đã xây dựng nhìn siêu chắc chắn và bóng bẩy. Theo nhiều cách, nó là những gì tôi đã muốn Hug trở thành - thật sự truyền cảm hứng để thấy ai đó xây dựng nó._" + +
Timothy Crosley - người tạo ra Hug (ref)
+ +--- + +"_Nếu bạn đang tìm kiếm một **framework hiện đại** để xây dựng một REST APIs, thử xem xét **FastAPI** [...] Nó nhanh, dễ dùng và dễ học [...]_" + +"_Chúng tôi đã chuyển qua **FastAPI cho **APIs** của chúng tôi [...] Tôi nghĩ bạn sẽ thích nó [...]_" + +
Ines Montani - Matthew Honnibal - Explosion AI founders - spaCy creators (ref) - (ref)
+
Ines Montani - Matthew Honnibal - nhà sáng lập Explosion AI - người tạo ra spaCy (ref) - (ref)
+ +--- + +"_Nếu ai đó đang tìm cách xây dựng sản phẩm API bằng Python, tôi sẽ đề xuất **FastAPI**. Nó **được thiết kế đẹp đẽ**, **sử dụng đơn giản** và **có khả năng mở rộng cao**, nó đã trở thành một **thành phần quan trọng** trong chiến lược phát triển API của chúng tôi và đang thúc đẩy nhiều dịch vụ và mảng tự động hóa như Kỹ sư TAC ảo của chúng tôi._" + +
Deon Pillsbury - Cisco (ref)
+ +--- + +## **Typer**, giao diện dòng lệnh của FastAPI + + + +Nếu bạn đang xây dựng một CLI - ứng dụng được sử dụng trong giao diện dòng lệnh, xem về **Typer**. + +**Typer** là một người anh em của FastAPI. Và nó được dự định trở thành **giao diện dòng lệnh cho FastAPI**. ⌨️ 🚀 + +## Yêu cầu + +Python 3.8+ + +FastAPI đứng trên vai những người khổng lồ: + +* Starlette cho phần web. +* Pydantic cho phần data. + +## Cài đặt + +
+ +```console +$ pip install fastapi + +---> 100% +``` + +
+ +Bạn cũng sẽ cần một ASGI server cho production như Uvicorn hoặc Hypercorn. + +
+ +```console +$ pip install "uvicorn[standard]" + +---> 100% +``` + +
+ +## Ví dụ + +### Khởi tạo + +* Tạo một tệp tin `main.py` như sau: + +```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} +``` + +
+Hoặc sử dụng async def... + +Nếu code của bạn sử dụng `async` / `await`, hãy sử dụng `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} +``` + +**Lưu ý**: + +Nếu bạn không biết, xem phần _"In a hurry?"_ về `async` và `await` trong tài liệu này. + +
+ +### Chạy ứng dụng + +Chạy server như sau: + +
+ +```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. +``` + +
+ +
+Về lệnh uvicorn main:app --reload... + +Lệnh `uvicorn main:app` tham chiếu tới những thành phần sau: + +* `main`: tệp tin `main.py` (một Python "module"). +* `app`: object được tạo trong tệp tin `main.py` tại dòng `app = FastAPI()`. +* `--reload`: chạy lại server sau khi code thay đổi. Chỉ sử dụng trong quá trình phát triển. + +
+ +### Kiểm tra + +Mở trình duyệt của bạn tại http://127.0.0.1:8000/items/5?q=somequery. + +Bạn sẽ thấy một JSON response: + +```JSON +{"item_id": 5, "q": "somequery"} +``` + +Bạn đã sẵn sàng để tạo một API như sau: + +* Nhận HTTP request với _đường dẫn_ `/` và `/items/{item_id}`. +* Cả hai _đường dẫn_ sử dụng toán tử `GET` (cũng đươc biết đến là _phương thức_ HTTP). +* _Đường dẫn_ `/items/{item_id}` có một _tham số đường dẫn_ `item_id`, nó là một tham số kiểu `int`. +* _Đường dẫn_ `/items/{item_id}` có một _tham số query string_ `q`, nó là một tham số tùy chọn kiểu `str`. + +### Tài liệu tương tác API + +Truy cập http://127.0.0.1:8000/docs. + +Bạn sẽ thấy tài liệu tương tác API được tạo tự động (cung cấp bởi Swagger UI): + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +### Tài liệu API thay thế + +Và bây giờ, hãy truy cập tới http://127.0.0.1:8000/redoc. + +Bạn sẽ thấy tài liệu được thay thế (cung cấp bởi ReDoc): + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +## Nâng cấp ví dụ + +Bây giờ sửa tệp tin `main.py` để nhận body từ một request `PUT`. + +Định nghĩa của body sử dụng kiểu dữ liệu chuẩn của Python, cảm ơn 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} +``` + +Server nên tự động chạy lại (bởi vì bạn đã thêm `--reload` trong lệnh `uvicorn` ở trên). + +### Nâng cấp tài liệu API + +Bây giờ truy cập tới http://127.0.0.1:8000/docs. + +* Tài liệu API sẽ được tự động cập nhật, bao gồm body mới: + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) + +* Click vào nút "Try it out", nó cho phép bạn điền những tham số và tương tác trực tiếp với API: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png) + +* Sau khi click vào nút "Execute", giao diện người dùng sẽ giao tiếp với API của bạn bao gồm: gửi các tham số, lấy kết quả và hiển thị chúng trên màn hình: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png) + +### Nâng cấp tài liệu API thay thế + +Và bây giờ truy cập tới http://127.0.0.1:8000/redoc. + +* Tài liệu thay thế cũng sẽ phản ánh tham số và body mới: + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) + +### Tóm lại + +Bạn khai báo **một lần** kiểu dữ liệu của các tham số, body, etc là các tham số của hàm số. + +Bạn định nghĩa bằng cách sử dụng các kiểu dữ liệu chuẩn của Python. + +Bạn không phải học một cú pháp mới, các phương thức và class của một thư viện cụ thể nào. + +Chỉ cần sử dụng các chuẩn của **Python 3.8+**. + +Ví dụ, với một tham số kiểu `int`: + +```Python +item_id: int +``` + +hoặc với một model `Item` phức tạp hơn: + +```Python +item: Item +``` + +...và với định nghĩa đơn giản đó, bạn có được: + +* Sự hỗ trợ từ các trình soạn thảo, bao gồm: + * Completion. + * Kiểm tra kiểu dữ liệu. +* Kiểm tra kiểu dữ liệu: + * Tự động sinh lỗi rõ ràng khi dữ liệu không hợp lệ . + * Kiểm tra JSON lồng nhau . +* Chuyển đổi dữ liệu đầu vào: tới từ network sang dữ liệu kiểu Python. Đọc từ: + * JSON. + * Các tham số trong đường dẫn. + * Các tham số trong query string. + * Cookies. + * Headers. + * Forms. + * Files. +* Chuyển đổi dữ liệu đầu ra: chuyển đổi từ kiểu dữ liệu Python sang dữ liệu network (như JSON): + * Chuyển đổi kiểu dữ liệu Python (`str`, `int`, `float`, `bool`, `list`,...). + * `datetime` objects. + * `UUID` objects. + * Database models. + * ...và nhiều hơn thế. +* Tự động tạo tài liệu tương tác API, bao gồm 2 giao diện người dùng: + * Swagger UI. + * ReDoc. + +--- + +Quay trở lại ví dụ trước, **FastAPI** sẽ thực hiện: + +* Kiểm tra xem có một `item_id` trong đường dẫn với các request `GET` và `PUT` không? +* Kiểm tra xem `item_id` có phải là kiểu `int` trong các request `GET` và `PUT` không? + * Nếu không, client sẽ thấy một lỗi rõ ràng và hữu ích. +* Kiểm tra xem nếu có một tham số `q` trong query string (ví dụ như `http://127.0.0.1:8000/items/foo?q=somequery`) cho request `GET`. + * Tham số `q` được định nghĩa `= None`, nó là tùy chọn. + * Nếu không phải `None`, nó là bắt buộc (như body trong trường hợp của `PUT`). +* Với request `PUT` tới `/items/{item_id}`, đọc body như JSON: + * Kiểm tra xem nó có một thuộc tính bắt buộc kiểu `str` là `name` không? + * Kiểm tra xem nó có một thuộc tính bắt buộc kiểu `float` là `price` không? + * Kiểm tra xem nó có một thuộc tính tùy chọn là `is_offer` không? Nếu có, nó phải có kiểu `bool`. + * Tất cả những kiểm tra này cũng được áp dụng với các JSON lồng nhau. +* Chuyển đổi tự động các JSON object đến và JSON object đi. +* Tài liệu hóa mọi thứ với OpenAPI, tài liệu đó có thể được sử dụng bởi: + + * Các hệ thống tài liệu có thể tương tác. + * Hệ thống sinh code tự động, cho nhiều ngôn ngữ lập trình. +* Cung cấp trực tiếp 2 giao diện web cho tài liệu tương tác + +--- + +Chúng tôi chỉ trình bày những thứ cơ bản bên ngoài, nhưng bạn đã hiểu cách thức hoạt động của nó. + +Thử thay đổi dòng này: + +```Python + return {"item_name": item.name, "item_id": item_id} +``` + +...từ: + +```Python + ... "item_name": item.name ... +``` + +...sang: + +```Python + ... "item_price": item.price ... +``` + +...và thấy trình soạn thảo của bạn nhận biết kiểu dữ liệu và gợi ý hoàn thiện các thuộc tính. + +![trình soạn thảo hỗ trợ](https://fastapi.tiangolo.com/img/vscode-completion.png) + +Ví dụ hoàn chỉnh bao gồm nhiều tính năng hơn, xem Tutorial - User Guide. + + +**Cảnh báo tiết lỗ**: Tutorial - User Guide: + +* Định nghĩa **tham số** từ các nguồn khác nhau như: **headers**, **cookies**, **form fields** và **files**. +* Cách thiết lập **các ràng buộc cho validation** như `maximum_length` hoặc `regex`. +* Một hệ thống **Dependency Injection vô cùng mạnh mẽ và dễ dàng sử dụng. +* Bảo mật và xác thực, hỗ trợ **OAuth2**(với **JWT tokens**) và **HTTP Basic**. +* Những kĩ thuật nâng cao hơn (nhưng tương đối dễ) để định nghĩa **JSON models lồng nhau** (cảm ơn Pydantic). +* Tích hợp **GraphQL** với Strawberry và các thư viện khác. +* Nhiều tính năng mở rộng (cảm ơn Starlette) như: + * **WebSockets** + * kiểm thử vô cùng dễ dàng dựa trên HTTPX và `pytest` + * **CORS** + * **Cookie Sessions** + * ...và nhiều hơn thế. + +## Hiệu năng + +Independent TechEmpower benchmarks cho thấy các ứng dụng **FastAPI** chạy dưới Uvicorn là một trong những Python framework nhanh nhất, chỉ đứng sau Starlette và Uvicorn (được sử dụng bên trong FastAPI). (*) + +Để hiểu rõ hơn, xem phần Benchmarks. + +## Các dependency tùy chọn + +Sử dụng bởi Pydantic: + +* ujson - "Parse" JSON nhanh hơn. +* email_validator - cho email validation. + +Sử dụng Starlette: + +* httpx - Bắt buộc nếu bạn muốn sử dụng `TestClient`. +* jinja2 - Bắt buộc nếu bạn muốn sử dụng cấu hình template engine mặc định. +* python-multipart - Bắt buộc nếu bạn muốn hỗ trợ "parsing", form với `request.form()`. +* itsdangerous - Bắt buộc để hỗ trợ `SessionMiddleware`. +* pyyaml - Bắt buộc để hỗ trợ `SchemaGenerator` cho Starlette (bạn có thể không cần nó trong FastAPI). +* ujson - Bắt buộc nếu bạn muốn sử dụng `UJSONResponse`. + +Sử dụng bởi FastAPI / Starlette: + +* uvicorn - Server để chạy ứng dụng của bạn. +* orjson - Bắt buộc nếu bạn muốn sử dụng `ORJSONResponse`. + +Bạn có thể cài đặt tất cả những dependency trên với `pip install "fastapi[all]"`. + +## Giấy phép + +Dự án này được cấp phép dưới những điều lệ của giấy phép MIT. diff --git a/docs/vi/docs/python-types.md b/docs/vi/docs/python-types.md new file mode 100644 index 0000000000000..b2a399aa5e5f0 --- /dev/null +++ b/docs/vi/docs/python-types.md @@ -0,0 +1,545 @@ +# Giới thiệu kiểu dữ liệu Python + +Python hỗ trợ tùy chọn "type hints" (còn được gọi là "type annotations"). + +Những **"type hints"** hay chú thích là một cú pháp đặc biệt cho phép khai báo kiểu dữ liệu của một biến. + +Bằng việc khai báo kiểu dữ liệu cho các biến của bạn, các trình soạn thảo và các công cụ có thể hỗ trợ bạn tốt hơn. + +Đây chỉ là một **hướng dẫn nhanh** về gợi ý kiểu dữ liệu trong Python. Nó chỉ bao gồm những điều cần thiết tối thiểu để sử dụng chúng với **FastAPI**... đó thực sự là rất ít. + +**FastAPI** hoàn toàn được dựa trên những gợi ý kiểu dữ liệu, chúng mang đến nhiều ưu điểm và lợi ích. + +Nhưng thậm chí nếu bạn không bao giờ sử dụng **FastAPI**, bạn sẽ được lợi từ việc học một ít về chúng. + +!!! note + Nếu bạn là một chuyên gia về Python, và bạn đã biết mọi thứ về gợi ý kiểu dữ liệu, bỏ qua và đi tới chương tiếp theo. + +## Động lực + +Hãy bắt đầu với một ví dụ đơn giản: + +```Python +{!../../../docs_src/python_types/tutorial001.py!} +``` + +Kết quả khi gọi chương trình này: + +``` +John Doe +``` + +Hàm thực hiện như sau: + +* Lấy một `first_name` và `last_name`. +* Chuyển đổi kí tự đầu tiên của mỗi biến sang kiểu chữ hoa với `title()`. +* Nối chúng lại với nhau bằng một kí tự trắng ở giữa. + +```Python hl_lines="2" +{!../../../docs_src/python_types/tutorial001.py!} +``` + +### Sửa đổi + +Nó là một chương trình rất đơn giản. + +Nhưng bây giờ hình dung rằng bạn đang viết nó từ đầu. + +Tại một vài thời điểm, bạn sẽ bắt đầu định nghĩa hàm, bạn có các tham số... + +Nhưng sau đó bạn phải gọi "phương thức chuyển đổi kí tự đầu tiên sang kiểu chữ hoa". + +Có phải là `upper`? Có phải là `uppercase`? `first_uppercase`? `capitalize`? + +Sau đó, bạn thử hỏi người bạn cũ của mình, autocompletion của trình soạn thảo. + +Bạn gõ tham số đầu tiên của hàm, `first_name`, sau đó một dấu chấm (`.`) và sau đó ấn `Ctrl+Space` để kích hoạt bộ hoàn thành. + +Nhưng đáng buồn, bạn không nhận được điều gì hữu ích cả: + + + +### Thêm kiểu dữ liệu + +Hãy sửa một dòng từ phiên bản trước. + +Chúng ta sẽ thay đổi chính xác đoạn này, tham số của hàm, từ: + +```Python + first_name, last_name +``` + +sang: + +```Python + first_name: str, last_name: str +``` + +Chính là nó. + +Những thứ đó là "type hints": + +```Python hl_lines="1" +{!../../../docs_src/python_types/tutorial002.py!} +``` + +Đó không giống như khai báo những giá trị mặc định giống như: + +```Python + first_name="john", last_name="doe" +``` + +Nó là một thứ khác. + +Chúng ta sử dụng dấu hai chấm (`:`), không phải dấu bằng (`=`). + +Và việc thêm gợi ý kiểu dữ liệu không làm thay đổi những gì xảy ra so với khi chưa thêm chúng. + +But now, imagine you are again in the middle of creating that function, but with type hints. + +Tại cùng một điểm, bạn thử kích hoạt autocomplete với `Ctrl+Space` và bạn thấy: + + + +Với cái đó, bạn có thể cuộn, nhìn thấy các lựa chọn, cho đến khi bạn tìm thấy một "tiếng chuông": + + + +## Động lực nhiều hơn + +Kiểm tra hàm này, nó đã có gợi ý kiểu dữ liệu: + +```Python hl_lines="1" +{!../../../docs_src/python_types/tutorial003.py!} +``` + +Bởi vì trình soạn thảo biết kiểu dữ liệu của các biến, bạn không chỉ có được completion, bạn cũng được kiểm tra lỗi: + + + +Bây giờ bạn biết rằng bạn phải sửa nó, chuyển `age` sang một xâu với `str(age)`: + +```Python hl_lines="2" +{!../../../docs_src/python_types/tutorial004.py!} +``` + +## Khai báo các kiểu dữ liệu + +Bạn mới chỉ nhìn thấy những nơi chủ yếu để đặt khai báo kiểu dữ liệu. Như là các tham số của hàm. + +Đây cũng là nơi chủ yếu để bạn sử dụng chúng với **FastAPI**. + +### Kiểu dữ liệu đơn giản + +Bạn có thể khai báo tất cả các kiểu dữ liệu chuẩn của Python, không chỉ là `str`. + +Bạn có thể sử dụng, ví dụ: + +* `int` +* `float` +* `bool` +* `bytes` + +```Python hl_lines="1" +{!../../../docs_src/python_types/tutorial005.py!} +``` + +### Các kiểu dữ liệu tổng quát với tham số kiểu dữ liệu + +Có một vài cấu trúc dữ liệu có thể chứa các giá trị khác nhau như `dict`, `list`, `set` và `tuple`. Và những giá trị nội tại cũng có thể có kiểu dữ liệu của chúng. + +Những kiểu dữ liệu nội bộ này được gọi là những kiểu dữ liệu "**tổng quát**". Và có khả năng khai báo chúng, thậm chí với các kiểu dữ liệu nội bộ của chúng. + +Để khai báo những kiểu dữ liệu và những kiểu dữ liệu nội bộ đó, bạn có thể sử dụng mô đun chuẩn của Python là `typing`. Nó có hỗ trợ những gợi ý kiểu dữ liệu này. + +#### Những phiên bản mới hơn của Python + +Cú pháp sử dụng `typing` **tương thích** với tất cả các phiên bản, từ Python 3.6 tới những phiên bản cuối cùng, bao gồm Python 3.9, Python 3.10,... + +As Python advances, **những phiên bản mới** mang tới sự hỗ trợ được cải tiến cho những chú thích kiểu dữ liệu và trong nhiều trường hợp bạn thậm chí sẽ không cần import và sử dụng mô đun `typing` để khai báo chú thích kiểu dữ liệu. + +Nếu bạn có thể chọn một phiên bản Python gần đây hơn cho dự án của bạn, ban sẽ có được những ưu điểm của những cải tiến đơn giản đó. + +Trong tất cả các tài liệu tồn tại những ví dụ tương thích với mỗi phiên bản Python (khi có một sự khác nhau). + +Cho ví dụ "**Python 3.6+**" có nghĩa là nó tương thích với Python 3.7 hoặc lớn hơn (bao gồm 3.7, 3.8, 3.9, 3.10,...). và "**Python 3.9+**" nghĩa là nó tương thích với Python 3.9 trở lên (bao gồm 3.10,...). + +Nếu bạn có thể sử dụng **phiên bản cuối cùng của Python**, sử dụng những ví dụ cho phiên bản cuối, những cái đó sẽ có **cú pháp đơn giản và tốt nhât**, ví dụ, "**Python 3.10+**". + +#### List + +Ví dụ, hãy định nghĩa một biến là `list` các `str`. + +=== "Python 3.9+" + + Khai báo biến với cùng dấu hai chấm (`:`). + + Tương tự kiểu dữ liệu `list`. + + Như danh sách là một kiểu dữ liệu chứa một vài kiểu dữ liệu có sẵn, bạn đặt chúng trong các dấu ngoặc vuông: + + ```Python hl_lines="1" + {!> ../../../docs_src/python_types/tutorial006_py39.py!} + ``` + +=== "Python 3.8+" + + Từ `typing`, import `List` (với chữ cái `L` viết hoa): + + ``` Python hl_lines="1" + {!> ../../../docs_src/python_types/tutorial006.py!} + ``` + + Khai báo biến với cùng dấu hai chấm (`:`). + + Tương tự như kiểu dữ liệu, `List` bạn import từ `typing`. + + Như danh sách là một kiểu dữ liệu chứa các kiểu dữ liệu có sẵn, bạn đặt chúng bên trong dấu ngoặc vuông: + + ```Python hl_lines="4" + {!> ../../../docs_src/python_types/tutorial006.py!} + ``` + +!!! info + Các kiểu dữ liệu có sẵn bên trong dấu ngoặc vuông được gọi là "tham số kiểu dữ liệu". + + Trong trường hợp này, `str` là tham số kiểu dữ liệu được truyền tới `List` (hoặc `list` trong Python 3.9 trở lên). + +Có nghĩa là: "biến `items` là một `list`, và mỗi phần tử trong danh sách này là một `str`". + +!!! tip + Nếu bạn sử dụng Python 3.9 hoặc lớn hơn, bạn không phải import `List` từ `typing`, bạn có thể sử dụng `list` để thay thế. + +Bằng cách này, trình soạn thảo của bạn có thể hỗ trợ trong khi xử lí các phần tử trong danh sách: + + + +Đa phần đều không thể đạt được nếu không có các kiểu dữ liệu. + +Chú ý rằng, biến `item` là một trong các phần tử trong danh sách `items`. + +Và do vậy, trình soạn thảo biết nó là một `str`, và cung cấp sự hỗ trợ cho nó. + +#### Tuple and Set + +Bạn sẽ làm điều tương tự để khai báo các `tuple` và các `set`: + +=== "Python 3.9+" + + ```Python hl_lines="1" + {!> ../../../docs_src/python_types/tutorial007_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="1 4" + {!> ../../../docs_src/python_types/tutorial007.py!} + ``` + +Điều này có nghĩa là: + +* Biến `items_t` là một `tuple` với 3 phần tử, một `int`, một `int` nữa, và một `str`. +* Biến `items_s` là một `set`, và mỗi phần tử của nó có kiểu `bytes`. + +#### Dict + +Để định nghĩa một `dict`, bạn truyền 2 tham số kiểu dữ liệu, phân cách bởi dấu phẩy. + +Tham số kiểu dữ liệu đầu tiên dành cho khóa của `dict`. + +Tham số kiểu dữ liệu thứ hai dành cho giá trị của `dict`. + +=== "Python 3.9+" + + ```Python hl_lines="1" + {!> ../../../docs_src/python_types/tutorial008_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="1 4" + {!> ../../../docs_src/python_types/tutorial008.py!} + ``` + +Điều này có nghĩa là: + +* Biến `prices` là một `dict`: + * Khóa của `dict` này là kiểu `str` (đó là tên của mỗi vật phẩm). + * Giá trị của `dict` này là kiểu `float` (đó là giá của mỗi vật phẩm). + +#### Union + +Bạn có thể khai báo rằng một biến có thể là **một vài kiểu dữ liệu" bất kì, ví dụ, một `int` hoặc một `str`. + +Trong Python 3.6 hoặc lớn hơn (bao gồm Python 3.10) bạn có thể sử dụng kiểu `Union` từ `typing` và đặt trong dấu ngoặc vuông những giá trị được chấp nhận. + +In Python 3.10 there's also a **new syntax** where you can put the possible types separated by a vertical bar (`|`). + +Trong Python 3.10 cũng có một **cú pháp mới** mà bạn có thể đặt những kiểu giá trị khả thi phân cách bởi một dấu sổ dọc (`|`). + + +=== "Python 3.10+" + + ```Python hl_lines="1" + {!> ../../../docs_src/python_types/tutorial008b_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="1 4" + {!> ../../../docs_src/python_types/tutorial008b.py!} + ``` + +Trong cả hai trường hợp có nghĩa là `item` có thể là một `int` hoặc `str`. + +#### Khả năng `None` + +Bạn có thể khai báo một giá trị có thể có một kiểu dữ liệu, giống như `str`, nhưng nó cũng có thể là `None`. + +Trong Python 3.6 hoặc lớn hơn (bao gồm Python 3.10) bạn có thể khai báo nó bằng các import và sử dụng `Optional` từ mô đun `typing`. + +```Python hl_lines="1 4" +{!../../../docs_src/python_types/tutorial009.py!} +``` + +Sử dụng `Optional[str]` thay cho `str` sẽ cho phép trình soạn thảo giúp bạn phát hiện các lỗi mà bạn có thể gặp như một giá trị luôn là một `str`, trong khi thực tế nó rất có thể là `None`. + +`Optional[Something]` là một cách viết ngắn gọn của `Union[Something, None]`, chúng là tương đương nhau. + +Điều này cũng có nghĩa là trong Python 3.10, bạn có thể sử dụng `Something | None`: + +=== "Python 3.10+" + + ```Python hl_lines="1" + {!> ../../../docs_src/python_types/tutorial009_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="1 4" + {!> ../../../docs_src/python_types/tutorial009.py!} + ``` + +=== "Python 3.8+ alternative" + + ```Python hl_lines="1 4" + {!> ../../../docs_src/python_types/tutorial009b.py!} + ``` + +#### Sử dụng `Union` hay `Optional` + +If you are using a Python version below 3.10, here's a tip from my very **subjective** point of view: + +Nếu bạn đang sử dụng phiên bản Python dưới 3.10, đây là một mẹo từ ý kiến rất "chủ quan" của tôi: + +* 🚨 Tránh sử dụng `Optional[SomeType]` +* Thay vào đó ✨ **sử dụng `Union[SomeType, None]`** ✨. + +Cả hai là tương đương và bên dưới chúng giống nhau, nhưng tôi sẽ đễ xuất `Union` thay cho `Optional` vì từ "**tùy chọn**" có vẻ ngầm định giá trị là tùy chọn, và nó thực sự có nghĩa rằng "nó có thể là `None`", do đó nó không phải là tùy chọn và nó vẫn được yêu cầu. + +Tôi nghĩ `Union[SomeType, None]` là rõ ràng hơn về ý nghĩa của nó. + +Nó chỉ là về các từ và tên. Nhưng những từ đó có thể ảnh hưởng cách bạn và những đồng đội của bạn suy nghĩ về code. + +Cho một ví dụ, hãy để ý hàm này: + +```Python hl_lines="1 4" +{!../../../docs_src/python_types/tutorial009c.py!} +``` + +Tham số `name` được định nghĩa là `Optional[str]`, nhưng nó **không phải là tùy chọn**, bạn không thể gọi hàm mà không có tham số: + +```Python +say_hi() # Oh, no, this throws an error! 😱 +``` + +Tham số `name` **vẫn được yêu cầu** (không phải là *tùy chọn*) vì nó không có giá trị mặc định. Trong khi đó, `name` chấp nhận `None` như là giá trị: + +```Python +say_hi(name=None) # This works, None is valid 🎉 +``` + +Tin tốt là, khi bạn sử dụng Python 3.10, bạn sẽ không phải lo lắng về điều đó, bạn sẽ có thể sử dụng `|` để định nghĩa hợp của các kiểu dữ liệu một cách đơn giản: + +```Python hl_lines="1 4" +{!../../../docs_src/python_types/tutorial009c_py310.py!} +``` + +Và sau đó, bạn sẽ không phải lo rằng những cái tên như `Optional` và `Union`. 😎 + + +#### Những kiểu dữ liệu tổng quát + +Những kiểu dữ liệu này lấy tham số kiểu dữ liệu trong dấu ngoặc vuông được gọi là **Kiểu dữ liệu tổng quát**, cho ví dụ: + +=== "Python 3.10+" + + Bạn có thể sử dụng các kiểu dữ liệu có sẵn như là kiểu dữ liệu tổng quát (với ngoặc vuông và kiểu dữ liệu bên trong): + + * `list` + * `tuple` + * `set` + * `dict` + + Và tương tự với Python 3.6, từ mô đun `typing`: + + * `Union` + * `Optional` (tương tự như Python 3.6) + * ...và các kiểu dữ liệu khác. + + Trong Python 3.10, thay vì sử dụng `Union` và `Optional`, bạn có thể sử dụng sổ dọc ('|') để khai báo hợp của các kiểu dữ liệu, điều đó tốt hơn và đơn giản hơn nhiều. + +=== "Python 3.9+" + + Bạn có thể sử dụng các kiểu dữ liệu có sẵn tương tự như (với ngoặc vuông và kiểu dữ liệu bên trong): + + * `list` + * `tuple` + * `set` + * `dict` + + Và tương tự với Python 3.6, từ mô đun `typing`: + + * `Union` + * `Optional` + * ...and others. + +=== "Python 3.8+" + + * `List` + * `Tuple` + * `Set` + * `Dict` + * `Union` + * `Optional` + * ...và các kiểu khác. + +### Lớp như kiểu dữ liệu + +Bạn cũng có thể khai báo một lớp như là kiểu dữ liệu của một biến. + +Hãy nói rằng bạn muốn có một lớp `Person` với một tên: + +```Python hl_lines="1-3" +{!../../../docs_src/python_types/tutorial010.py!} +``` + +Sau đó bạn có thể khai báo một biến có kiểu là `Person`: + +```Python hl_lines="6" +{!../../../docs_src/python_types/tutorial010.py!} +``` + +Và lại một lần nữa, bạn có được tất cả sự hỗ trợ từ trình soạn thảo: + + + +Lưu ý rằng, điều này có nghĩa rằng "`one_person`" là một **thực thể** của lớp `Person`. + +Nó không có nghĩa "`one_person`" là một **lớp** gọi là `Person`. + +## Pydantic models + +Pydantic là một thư viện Python để validate dữ liệu hiệu năng cao. + +Bạn có thể khai báo "hình dạng" của dữa liệu như là các lớp với các thuộc tính. + +Và mỗi thuộc tính có một kiểu dữ liệu. + +Sau đó bạn tạo một thực thể của lớp đó với một vài giá trị và nó sẽ validate các giá trị, chuyển đổi chúng sang kiểu dữ liệu phù hợp (nếu đó là trường hợp) và cho bạn một object với toàn bộ dữ liệu. + +Và bạn nhận được tất cả sự hỗ trợ của trình soạn thảo với object kết quả đó. + +Một ví dụ từ tài liệu chính thức của Pydantic: + +=== "Python 3.10+" + + ```Python + {!> ../../../docs_src/python_types/tutorial011_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python + {!> ../../../docs_src/python_types/tutorial011_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python + {!> ../../../docs_src/python_types/tutorial011.py!} + ``` + +!!! info + Để học nhiều hơn về Pydantic, tham khảo tài liệu của nó. + +**FastAPI** được dựa hoàn toàn trên Pydantic. + +Bạn sẽ thấy nhiều ví dụ thực tế hơn trong [Hướng dẫn sử dụng](tutorial/index.md){.internal-link target=_blank}. + +!!! tip + Pydantic có một hành vi đặc biệt khi bạn sử dụng `Optional` hoặc `Union[Something, None]` mà không có giá trị mặc dịnh, bạn có thể đọc nhiều hơn về nó trong tài liệu của Pydantic về Required Optional fields. + + +## Type Hints với Metadata Annotations + +Python cũng có một tính năng cho phép đặt **metadata bổ sung** trong những gợi ý kiểu dữ liệu này bằng cách sử dụng `Annotated`. + +=== "Python 3.9+" + + Trong Python 3.9, `Annotated` là một phần của thư viện chuẩn, do đó bạn có thể import nó từ `typing`. + + ```Python hl_lines="1 4" + {!> ../../../docs_src/python_types/tutorial013_py39.py!} + ``` + +=== "Python 3.8+" + + Ở phiên bản dưới Python 3.9, bạn import `Annotated` từ `typing_extensions`. + + Nó đã được cài đặt sẵng cùng với **FastAPI**. + + ```Python hl_lines="1 4" + {!> ../../../docs_src/python_types/tutorial013.py!} + ``` + +Python bản thân nó không làm bất kì điều gì với `Annotated`. Với các trình soạn thảo và các công cụ khác, kiểu dữ liệu vẫn là `str`. + +Nhưng bạn có thể sử dụng `Annotated` để cung cấp cho **FastAPI** metadata bổ sung về cách mà bạn muốn ứng dụng của bạn xử lí. + +Điều quan trọng cần nhớ là ***tham số kiểu dữ liệu* đầu tiên** bạn truyền tới `Annotated` là **kiểu giá trị thực sự**. Phần còn lại chỉ là metadata cho các công cụ khác. + +Bây giờ, bạn chỉ cần biết rằng `Annotated` tồn tại, và nó là tiêu chuẩn của Python. 😎 + + +Sau đó, bạn sẽ thấy sự **mạnh mẽ** mà nó có thể làm. + +!!! tip + Thực tế, cái này là **tiêu chuẩn của Python**, nghĩa là bạn vẫn sẽ có được **trải nghiệm phát triển tốt nhất có thể** với trình soạn thảo của bạn, với các công cụ bạn sử dụng để phân tích và tái cấu trúc code của bạn, etc. ✨ + + Và code của bạn sẽ tương thích với nhiều công cụ và thư viện khác của Python. 🚀 + +## Các gợi ý kiểu dữ liệu trong **FastAPI** + +**FastAPI** lấy các ưu điểm của các gợi ý kiểu dữ liệu để thực hiện một số thứ. + +Với **FastAPI**, bạn khai báo các tham số với gợi ý kiểu và bạn có được: + +* **Sự hỗ trợ từ các trình soạn thảo**. +* **Kiểm tra kiểu dữ liệu (type checking)**. + +...và **FastAPI** sử dụng các khia báo để: + +* **Định nghĩa các yêu cầu**: từ tham số đường dẫn của request, tham số query, headers, bodies, các phụ thuộc (dependencies),... +* **Chuyển dổi dữ liệu*: từ request sang kiểu dữ liệu được yêu cầu. +* **Kiểm tra tính đúng đắn của dữ liệu**: tới từ mỗi request: + * Sinh **lỗi tự động** để trả về máy khác khi dữ liệu không hợp lệ. +* **Tài liệu hóa** API sử dụng OpenAPI: + * cái mà sau được được sử dụng bởi tài liệu tương tác người dùng. + +Điều này có thể nghe trừu tượng. Đừng lo lắng. Bạn sẽ thấy tất cả chúng trong [Hướng dẫn sử dụng](tutorial/index.md){.internal-link target=_blank}. + +Điều quan trọng là bằng việc sử dụng các kiểu dữ liệu chuẩn của Python (thay vì thêm các lớp, decorators,...), **FastAPI** sẽ thực hiện nhiều công việc cho bạn. + +!!! info + Nếu bạn đã đi qua toàn bộ các hướng dẫn và quay trở lại để tìm hiểu nhiều hơn về các kiểu dữ liệu, một tài nguyên tốt như "cheat sheet" từ `mypy`. diff --git a/docs/vi/docs/tutorial/first-steps.md b/docs/vi/docs/tutorial/first-steps.md new file mode 100644 index 0000000000000..712f00852f594 --- /dev/null +++ b/docs/vi/docs/tutorial/first-steps.md @@ -0,0 +1,333 @@ +# Những bước đầu tiên + +Tệp tin FastAPI đơn giản nhất có thể trông như này: + +```Python +{!../../../docs_src/first_steps/tutorial001.py!} +``` + +Sao chép sang một tệp tin `main.py`. + +Chạy live server: + +
+ +```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 + Câu lệnh `uvicorn main:app` được giải thích như sau: + + * `main`: tệp tin `main.py` (một Python "mô đun"). + * `app`: một object được tạo ra bên trong `main.py` với dòng `app = FastAPI()`. + * `--reload`: làm server khởi động lại sau mỗi lần thay đổi. Chỉ sử dụng trong môi trường phát triển. + +Trong output, có một dòng giống như: + +```hl_lines="4" +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +Dòng đó cho thấy URL, nơi mà app của bạn đang được chạy, trong máy local của bạn. + +### Kiểm tra + +Mở trình duyệt của bạn tại http://127.0.0.1:8000. + +Bạn sẽ thấy một JSON response như: + +```JSON +{"message": "Hello World"} +``` + +### Tài liệu tương tác API + +Bây giờ tới http://127.0.0.1:8000/docs. + +Bạn sẽ thấy một tài liệu tương tác API (cung cấp bởi Swagger UI): + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +### Phiên bản thay thế của tài liệu API + +Và bây giờ tới http://127.0.0.1:8000/redoc. + +Bạn sẽ thấy một bản thay thế của tài liệu (cung cấp bởi ReDoc): + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +### OpenAPI + +**FastAPI** sinh một "schema" với tất cả API của bạn sử dụng tiêu chuẩn **OpenAPI** cho định nghĩa các API. + +#### "Schema" + +Một "schema" là một định nghĩa hoặc mô tả thứ gì đó. Không phải code triển khai của nó, nhưng chỉ là một bản mô tả trừu tượng. + +#### API "schema" + +Trong trường hợp này, OpenAPI là một bản mô tả bắt buộc cơ chế định nghĩa API của bạn. + +Định nghĩa cấu trúc này bao gồm những đường dẫn API của bạn, các tham số có thể có,... + +#### "Cấu trúc" dữ liệu + +Thuật ngữ "cấu trúc" (schema) cũng có thể được coi như là hình dạng của dữ liệu, tương tự như một JSON content. + +Trong trường hợp đó, nó có nghĩa là các thuộc tính JSON và các kiểu dữ liệu họ có,... + +#### OpenAPI và JSON Schema + +OpenAPI định nghĩa một cấu trúc API cho API của bạn. Và cấu trúc đó bao gồm các dịnh nghĩa (or "schema") về dữ liệu được gửi đi và nhận về bởi API của bạn, sử dụng **JSON Schema**, một tiêu chuẩn cho cấu trúc dữ liệu JSON. + +#### Kiểm tra `openapi.json` + +Nếu bạn tò mò về việc cấu trúc OpenAPI nhìn như thế nào thì FastAPI tự động sinh một JSON (schema) với các mô tả cho tất cả API của bạn. + +Bạn có thể thấy nó trực tiếp tại: http://127.0.0.1:8000/openapi.json. + +Nó sẽ cho thấy một JSON bắt đầu giống như: + +```JSON +{ + "openapi": "3.1.0", + "info": { + "title": "FastAPI", + "version": "0.1.0" + }, + "paths": { + "/items/": { + "get": { + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + + + +... +``` + +#### OpenAPI dùng để làm gì? + +Cấu trúc OpenAPI là sức mạnh của tài liệu tương tác. + +Và có hàng tá các bản thay thế, tất cả đều dựa trên OpenAPI. Bạn có thể dễ dàng thêm bất kì bản thay thế bào cho ứng dụng của bạn được xây dựng với **FastAPI**. + +Bạn cũng có thể sử dụng nó để sinh code tự động, với các client giao viết qua API của bạn. Ví dụ, frontend, mobile hoặc các ứng dụng IoT. + +## Tóm lại, từng bước một + +### Bước 1: import `FastAPI` + +```Python hl_lines="1" +{!../../../docs_src/first_steps/tutorial001.py!} +``` + +`FastAPI` là một Python class cung cấp tất cả chức năng cho API của bạn. + +!!! note "Chi tiết kĩ thuật" + `FastAPI` là một class kế thừa trực tiếp `Starlette`. + + Bạn cũng có thể sử dụng tất cả Starlette chức năng với `FastAPI`. + +### Bước 2: Tạo một `FastAPI` "instance" + +```Python hl_lines="3" +{!../../../docs_src/first_steps/tutorial001.py!} +``` + +Biến `app` này là một "instance" của class `FastAPI`. + +Đây sẽ là điểm cốt lõi để tạo ra tất cả API của bạn. + +`app` này chính là điều được nhắc tới bởi `uvicorn` trong câu lệnh: + +
+ +```console +$ uvicorn main:app --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Nếu bạn tạo ứng dụng của bạn giống như: + +```Python hl_lines="3" +{!../../../docs_src/first_steps/tutorial002.py!} +``` + +Và đặt nó trong một tệp tin `main.py`, sau đó bạn sẽ gọi `uvicorn` giống như: + +
+ +```console +$ uvicorn main:my_awesome_api --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +### Bước 3: tạo một *đường dẫn toán tử* + +#### Đường dẫn + +"Đường dẫn" ở đây được nhắc tới là phần cuối cùng của URL bắt đầu từ `/`. + +Do đó, trong một URL nhìn giống như: + +``` +https://example.com/items/foo +``` + +...đường dẫn sẽ là: + +``` +/items/foo +``` + +!!! info + Một đường dẫn cũng là một cách gọi chung cho một "endpoint" hoặc một "route". + +Trong khi xây dựng một API, "đường dẫn" là các chính để phân tách "mối quan hệ" và "tài nguyên". + +#### Toán tử (Operation) + +"Toán tử" ở đây được nhắc tới là một trong các "phương thức" HTTP. + +Một trong những: + +* `POST` +* `GET` +* `PUT` +* `DELETE` + +...và một trong những cái còn lại: + +* `OPTIONS` +* `HEAD` +* `PATCH` +* `TRACE` + +Trong giao thức HTTP, bạn có thể giao tiếp trong mỗi đường dẫn sử dụng một (hoặc nhiều) trong các "phương thức này". + +--- + +Khi xây dựng các API, bạn thường sử dụng cụ thể các phương thức HTTP này để thực hiện một hành động cụ thể. + +Thông thường, bạn sử dụng + +* `POST`: để tạo dữ liệu. +* `GET`: để đọc dữ liệu. +* `PUT`: để cập nhật dữ liệu. +* `DELETE`: để xóa dữ liệu. + +Do đó, trong OpenAPI, mỗi phương thức HTTP được gọi là một "toán tử (operation)". + +Chúng ta cũng sẽ gọi chúng là "**các toán tử**". + +#### Định nghĩa moojt *decorator cho đường dẫn toán tử* + +```Python hl_lines="6" +{!../../../docs_src/first_steps/tutorial001.py!} +``` + +`@app.get("/")` nói **FastAPI** rằng hàm bên dưới có trách nhiệm xử lí request tới: + +* đường dẫn `/` +* sử dụng một toán tửget + +!!! info Thông tin về "`@decorator`" + Cú pháp `@something` trong Python được gọi là một "decorator". + + Bạn đặt nó trên một hàm. Giống như một chiếc mũ xinh xắn (Tôi ddonas đó là lí do mà thuật ngữ này ra đời). + + Một "decorator" lấy một hàm bên dưới và thực hiện một vài thứ với nó. + + Trong trường hợp của chúng ta, decorator này nói **FastAPI** rằng hàm bên dưới ứng với **đường dẫn** `/` và một **toán tử** `get`. + + Nó là một "**decorator đường dẫn toán tử**". + +Bạn cũng có thể sử dụng với các toán tử khác: + +* `@app.post()` +* `@app.put()` +* `@app.delete()` + +Và nhiều hơn với các toán tử còn lại: + +* `@app.options()` +* `@app.head()` +* `@app.patch()` +* `@app.trace()` + +!!! tip + Bạn thoải mái sử dụng mỗi toán tử (phương thức HTTP) như bạn mơ ước. + + **FastAPI** không bắt buộc bất kì ý nghĩa cụ thể nào. + + Thông tin ở đây được biểu thị như là một chỉ dẫn, không phải là một yêu cầu bắt buộc. + + Ví dụ, khi sử dụng GraphQL bạn thông thường thực hiện tất cả các hành động chỉ bằng việc sử dụng các toán tử `POST`. + +### Step 4: Định nghĩa **hàm cho đường dẫn toán tử** + +Đây là "**hàm cho đường dẫn toán tử**": + +* **đường dẫn**: là `/`. +* **toán tử**: là `get`. +* **hàm**: là hàm bên dưới "decorator" (bên dưới `@app.get("/")`). + +```Python hl_lines="7" +{!../../../docs_src/first_steps/tutorial001.py!} +``` + +Đây là một hàm Python. + +Nó sẽ được gọi bởi **FastAPI** bất cứ khi nào nó nhận một request tới URL "`/`" sử dụng một toán tử `GET`. + +Trong trường hợp này, nó là một hàm `async`. + +--- + +Bạn cũng có thể định nghĩa nó như là một hàm thông thường thay cho `async def`: + +```Python hl_lines="7" +{!../../../docs_src/first_steps/tutorial003.py!} +``` + +!!! note + Nếu bạn không biết sự khác nhau, kiểm tra [Async: *"Trong khi vội vàng?"*](../async.md#in-a-hurry){.internal-link target=_blank}. + +### Bước 5: Nội dung trả về + +```Python hl_lines="8" +{!../../../docs_src/first_steps/tutorial001.py!} +``` + +Bạn có thể trả về một `dict`, `list`, một trong những giá trị đơn như `str`, `int`,... + +Bạn cũng có thể trả về Pydantic model (bạn sẽ thấy nhiều hơn về nó sau). + +Có nhiều object và model khác nhau sẽ được tự động chuyển đổi sang JSON (bao gồm cả ORM,...). Thử sử dụng loại ưa thích của bạn, nó có khả năng cao đã được hỗ trợ. + +## Tóm lại + +* Import `FastAPI`. +* Tạo một `app` instance. +* Viết một **decorator cho đường dẫn toán tử** (giống như `@app.get("/")`). +* Viết một **hàm cho đường dẫn toán tử** (giống như `def root(): ...` ở trên). +* Chạy server trong môi trường phát triển (giống như `uvicorn main:app --reload`). diff --git a/docs/vi/docs/tutorial/index.md b/docs/vi/docs/tutorial/index.md new file mode 100644 index 0000000000000..e8a93fe4084f4 --- /dev/null +++ b/docs/vi/docs/tutorial/index.md @@ -0,0 +1,80 @@ +# Hướng dẫn sử dụng + +Hướng dẫn này cho bạn thấy từng bước cách sử dụng **FastAPI** đa số các tính năng của nó. + +Mỗi phần được xây dựng từ những phần trước đó, nhưng nó được cấu trúc thành các chủ đề riêng biệt, do đó bạn có thể xem trực tiếp từng phần cụ thể bất kì để giải quyết những API cụ thể mà bạn cần. + +Nó cũng được xây dựng để làm việc như một tham chiếu trong tương lai. + +Do đó bạn có thể quay lại và tìm chính xác những gì bạn cần. + +## Chạy mã + +Tất cả các code block có thể được sao chép và sử dụng trực tiếp (chúng thực chất là các tệp tin Python đã được kiểm thử). + +Để chạy bất kì ví dụ nào, sao chép code tới tệp tin `main.py`, và bắt đầu `uvicorn` với: + +
+ +```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. +``` + +
+ +**Khuyến khích** bạn viết hoặc sao chép code, sửa và chạy nó ở local. + +Sử dụng nó trong trình soạn thảo của bạn thực sự cho bạn thấy những lợi ích của FastAPI, thấy được cách bạn viết code ít hơn, tất cả đều được type check, autocompletion,... + +--- + +## Cài đặt FastAPI + +Bước đầu tiên là cài đặt FastAPI. + +Với hướng dẫn này, bạn có thể muốn cài đặt nó với tất cả các phụ thuộc và tính năng tùy chọn: + +
+ +```console +$ pip install "fastapi[all]" + +---> 100% +``` + +
+ +...dó cũng bao gồm `uvicorn`, bạn có thể sử dụng như một server để chạy code của bạn. + +!!! note + Bạn cũng có thể cài đặt nó từng phần. + + Đây là những gì bạn có thể sẽ làm một lần duy nhất bạn muốn triển khai ứng dụng của bạn lên production: + + ``` + pip install fastapi + ``` + + Cũng cài đặt `uvicorn` để làm việc như một server: + + ``` + pip install "uvicorn[standard]" + ``` + + Và tương tự với từng phụ thuộc tùy chọn mà bạn muốn sử dụng. + +## Hướng dẫn nâng cao + +Cũng có một **Hướng dẫn nâng cao** mà bạn có thể đọc nó sau **Hướng dẫn sử dụng**. + +**Hướng dẫn sử dụng nâng cao**, xây dựng dựa trên cái này, sử dụng các khái niệm tương tự, và dạy bạn những tính năng mở rộng. + +Nhưng bạn nên đọc **Hướng dẫn sử dụng** đầu tiên (những gì bạn đang đọc). + +Nó được thiết kế do đó bạn có thể xây dựng một ứng dụng hoàn chỉnh chỉ với **Hướng dẫn sử dụng**, và sau đó mở rộng nó theo các cách khác nhau, phụ thuộc vào những gì bạn cần, sử dụng một vài ý tưởng bổ sung từ **Hướng dẫn sử dụng nâng cao**. diff --git a/docs/vi/mkdocs.yml b/docs/vi/mkdocs.yml new file mode 100644 index 0000000000000..de18856f445aa --- /dev/null +++ b/docs/vi/mkdocs.yml @@ -0,0 +1 @@ +INHERIT: ../en/mkdocs.yml diff --git a/docs/yo/docs/index.md b/docs/yo/docs/index.md new file mode 100644 index 0000000000000..5684f0a6a2b93 --- /dev/null +++ b/docs/yo/docs/index.md @@ -0,0 +1,470 @@ +

+ FastAPI +

+

+ Ìlànà wẹ́ẹ́bù FastAPI, iṣẹ́ gíga, ó rọrùn láti kọ̀, o yára láti kóòdù, ó sì ṣetán fún iṣelọpọ ní lílo +

+

+ + Test + + + Coverage + + + Package version + + + Supported Python versions + +

+ +--- + +**Àkọsílẹ̀**: https://fastapi.tiangolo.com + +**Orisun Kóòdù**: https://github.com/tiangolo/fastapi + +--- + +FastAPI jẹ́ ìgbàlódé, tí ó yára (iṣẹ-giga), ìlànà wẹ́ẹ́bù fún kikọ àwọn API pẹ̀lú Python 3.8+ èyí tí ó da lori àwọn ìtọ́kasí àmì irúfẹ́ Python. + +Àwọn ẹya pàtàkì ni: + +* **Ó yára**: Iṣẹ tí ó ga púpọ̀, tí ó wa ni ibamu pẹ̀lú **NodeJS** àti **Go** (ọpẹ si Starlette àti Pydantic). [Ọkan nínú àwọn ìlànà Python ti o yára jùlọ ti o wa](#performance). +* **Ó yára láti kóòdù**: O mu iyara pọ si láti kọ àwọn ẹya tuntun kóòdù nipasẹ "Igba ìdá ọgọ́rùn-ún" (i.e. 200%) si "ọ̀ọ́dúrún ìdá ọgọ́rùn-ún" (i.e. 300%). +* **Àìtọ́ kékeré**: O n din aṣiṣe ku bi ọgbon ìdá ọgọ́rùn-ún (i.e. 40%) ti eda eniyan (oṣiṣẹ kóòdù) fa. * +* **Ọgbọ́n àti ìmọ̀**: Atilẹyin olootu nla. Ìparí nibi gbogbo. Àkókò díẹ̀ nipa wíwá ibi tí ìṣòro kóòdù wà. +* **Irọrun**: A kọ kí ó le rọrun láti lo àti láti kọ ẹkọ nínú rè. Ó máa fún ọ ní àkókò díẹ̀ látı ka àkọsílẹ. +* **Ó kúkurú ní kikọ**: Ó dín àtúnkọ àti àtúntò kóòdù kù. Ìkéde àṣàyàn kọ̀ọ̀kan nínú rẹ̀ ní ọ̀pọ̀lọpọ̀ àwọn ìlò. O ṣe iranlọwọ láti má ṣe ní ọ̀pọ̀lọpọ̀ àṣìṣe. +* **Ó lágbára**: Ó ń ṣe àgbéjáde kóòdù tí ó ṣetán fún ìṣelọ́pọ̀. Pẹ̀lú àkọsílẹ̀ tí ó máa ṣàlàyé ara rẹ̀ fún ẹ ní ìbáṣepọ̀ aládàáṣiṣẹ́ pẹ̀lú rè. +* **Ajohunše/Ìtọ́kasí**: Ó da lori (àti ibamu ni kikun pẹ̀lú) àwọn ìmọ ajohunše/ìtọ́kasí fún àwọn API: OpenAPI (èyí tí a mọ tẹlẹ si Swagger) àti JSON Schema. + +* iṣiro yi da lori àwọn idanwo tí ẹgbẹ ìdàgbàsókè FastAPI ṣe, nígbàtí wọn kọ àwọn ohun elo iṣelọpọ kóòdù pẹ̀lú rẹ. + +## Àwọn onígbọ̀wọ́ + + + +{% if sponsors %} +{% for sponsor in sponsors.gold -%} + +{% endfor -%} +{%- for sponsor in sponsors.silver -%} + +{% endfor %} +{% endif %} + + + +Àwọn onígbọ̀wọ́ míràn + +## Àwọn ero àti èsì + +"_[...] Mò ń lo **FastAPI** púpọ̀ ní lẹ́nu àìpẹ́ yìí. [...] Mo n gbero láti lo o pẹ̀lú àwọn ẹgbẹ mi fún gbogbo iṣẹ **ML wa ni Microsoft**. Diẹ nínú wọn ni afikun ti ifilelẹ àwọn ẹya ara ti ọja **Windows** wa pẹ̀lú àwọn ti **Office**._" + +
Kabir Khan - Microsoft (ref)
+ +--- + +"_A gba àwọn ohun èlò ìwé afọwọkọ **FastAPI** tí kò yí padà láti ṣẹ̀dá olùpín **REST** tí a lè béèrè lọ́wọ́ rẹ̀ láti gba **àsọtẹ́lẹ̀**. [fún Ludwig]_" + +
Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala - Uber (ref)
+ +--- + +"_**Netflix** ni inudidun láti kede itusilẹ orisun kóòdù ti ìlànà iṣọkan **iṣakoso Ìṣòro** wa: **Ìfiránṣẹ́**! [a kọ pẹ̀lú **FastAPI**]_" + +
Kevin Glisson, Marc Vilanova, Forest Monsen - Netflix (ref)
+ +--- + +"_Inú mi dùn púpọ̀ nípa **FastAPI**. Ó mú inú ẹnì dùn púpọ̀!_" + +
Brian Okken - Python Bytes podcast host (ref)
+ +--- + +"_Ní tòótọ́, ohun tí o kọ dára ó sì tún dán. Ní ọ̀pọ̀lọpọ̀ ọ̀nà, ohun tí mo fẹ́ kí **Hug** jẹ́ nìyẹn - ó wúni lórí gan-an láti rí ẹnìkan tí ó kọ́ nǹkan bí èyí._" + +
Timothy Crosley - Hug creator (ref)
+ +--- + +"_Ti o ba n wa láti kọ ọkan **ìlànà igbalode** fún kikọ àwọn REST API, ṣayẹwo **FastAPI** [...] Ó yára, ó rọrùn láti lò, ó sì rọrùn láti kọ́[...]_" + +"_A ti yipada si **FastAPI** fún **APIs** wa [...] Mo lérò pé wà á fẹ́ràn rẹ̀ [...]_" + +
Ines Montani - Matthew Honnibal - Explosion AI founders - spaCy creators (ref) - (ref)
+ +--- + +"_Ti ẹnikẹni ba n wa láti kọ iṣelọpọ API pẹ̀lú Python, èmi yóò ṣe'dúró fún **FastAPI**. Ó jẹ́ ohun tí **àgbékalẹ̀ rẹ̀ lẹ́wà**, **ó rọrùn láti lò** àti wipe ó ni **ìwọ̀n gíga**, o tí dí **bọtini paati** nínú alakọkọ API ìdàgbàsókè kikọ fún wa, àti pe o ni ipa lori adaṣiṣẹ àti àwọn iṣẹ gẹ́gẹ́ bíi Onímọ̀-ẹ̀rọ TAC tí órí Íńtánẹ́ẹ̀tì_" + +
Deon Pillsbury - Cisco (ref)
+ +--- + +## **Typer**, FastAPI ti CLIs + + + +Ti o ba n kọ ohun èlò CLI láti ṣeé lọ nínú ohun èlò lori ebute kọmputa dipo API, ṣayẹwo **Typer**. + +**Typer** jẹ́ àbúrò ìyá FastAPI kékeré. Àti pé wọ́n kọ́ láti jẹ́ **FastAPI ti CLIs**. ⌨️ 🚀 + +## Èròjà + +Python 3.8+ + +FastAPI dúró lórí àwọn èjìká tí àwọn òmíràn: + +* Starlette fún àwọn ẹ̀yà ayélujára. +* Pydantic fún àwọn ẹ̀yà àkójọf'áyẹ̀wò. + +## Fifi sórí ẹrọ + +
+ +```console +$ pip install fastapi + +---> 100% +``` + +
+Iwọ yóò tún nílò olupin ASGI, fún iṣelọpọ bii Uvicorn tabi Hypercorn. + +
+ +```console +$ pip install "uvicorn[standard]" + +---> 100% +``` + +
+ +## Àpẹẹrẹ + +### Ṣẹ̀dá rẹ̀ + +* Ṣẹ̀dá fáìlì `main.py (èyí tíí ṣe, akọkọ.py)` pẹ̀lú: + +```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} +``` + +
+Tàbí lò async def... + +Tí kóòdù rẹ̀ bá ń lò `async` / `await`, lò `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} +``` + +**Akiyesi**: + +Tí o kò bá mọ̀, ṣàyẹ̀wò ibi tí a ti ní _"In a hurry?"_ (i.e. _"Ní kíákíá?"_) nípa `async` and `await` nínú àkọsílẹ̀. + +
+ +### Mu ṣiṣẹ + +Mú olupin ṣiṣẹ pẹ̀lú: + +
+ +```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. +``` + +
+ +
+Nipa aṣẹ kóòdù náà uvicorn main:app --reload... + +Àṣẹ `uvicorn main:app` ń tọ́ka sí: + +* `main`: fáìlì náà 'main.py' (Python "module"). +* `app` jẹ object( i.e. nǹkan) tí a ṣẹ̀dá nínú `main.py` pẹ̀lú ilà `app = FastAPI()`. +* `--reload`: èyí yóò jẹ́ ki olupin tún bẹ̀rẹ̀ lẹ́hìn àwọn àyípadà kóòdù. Jọ̀wọ́, ṣe èyí fún ìdàgbàsókè kóòdù nìkan, má ṣe é ṣe lori àgbéjáde kóòdù tabi fún iṣelọpọ kóòdù. + + +
+ +### Ṣayẹwo rẹ + +Ṣii aṣàwákiri kọ̀ǹpútà rẹ ni http://127.0.0.1:8000/items/5?q=somequery. + +Ìwọ yóò sì rí ìdáhùn JSON bíi: + +```JSON +{"item_id": 5, "q": "somequery"} +``` + +O tí ṣẹ̀dá API èyí tí yóò: + +* Gbà àwọn ìbéèrè HTTP ni àwọn _ipa ọ̀nà_ `/` àti `/items/{item_id}`. +* Èyí tí àwọn _ipa ọ̀nà_ (i.e. _paths_) méjèèjì gbà àwọn iṣẹ `GET` (a tun mọ si _àwọn ọna_ HTTP). +* Èyí tí _ipa ọ̀nà_ (i.e. _paths_) `/items/{item_id}` ní _àwọn ohun-ini ipa ọ̀nà_ tí ó yẹ kí ó jẹ́ `int` i.e. `ÒǸKÀ`. +* Èyí tí _ipa ọ̀nà_ (i.e. _paths_) `/items/{item_id}` ní àṣàyàn `str` _àwọn ohun-ini_ (i.e. _query parameter_) `q`. + +### Ìbáṣepọ̀ àkọsílẹ̀ API + +Ní báyìí, lọ sí http://127.0.0.1:8000/docs. + +Lẹ́yìn náà, iwọ yóò rí ìdáhùn àkọsílẹ̀ API tí ó jẹ́ ìbáṣepọ̀ alaifọwọyi/aládàáṣiṣẹ́ (tí a pèṣè nípaṣẹ̀ Swagger UI): + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +### Ìdàkejì àkọsílẹ̀ API + +Ní báyìí, lọ sí http://127.0.0.1:8000/redoc. + +Wà á rí àwọn àkọsílẹ̀ aládàáṣiṣẹ́ mìíràn (tí a pese nipasẹ ReDoc): + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +## Àpẹẹrẹ ìgbésókè mìíràn + +Ní báyìí ṣe àtúnṣe fáìlì `main.py` láti gba kókó èsì láti inú ìbéèrè `PUT`. + +Ní báyìí, ṣe ìkéde kókó èsì API nínú kóòdù rẹ nipa lílo àwọn ìtọ́kasí àmì irúfẹ́ Python, ọpẹ́ pàtàkìsi sí 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} +``` + +Olupin yóò tún ṣe àtúnṣe laifọwọyi/aládàáṣiṣẹ́ (nítorí wípé ó se àfikún `-reload` si àṣẹ kóòdù `uvicorn` lókè). + +### Ìbáṣepọ̀ ìgbésókè àkọsílẹ̀ API + +Ní báyìí, lọ sí http://127.0.0.1:8000/docs. + +* Ìbáṣepọ̀ àkọsílẹ̀ API yóò ṣe imudojuiwọn àkọsílẹ̀ API laifọwọyi, pẹ̀lú kókó èsì ìdáhùn API tuntun: + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) + +* Tẹ bọtini "Gbiyanju rẹ" i.e. "Try it out", yóò gbà ọ́ láàyè láti jẹ́ kí ó tẹ́ àlàyé tí ó nílò kí ó le sọ̀rọ̀ tààrà pẹ̀lú API: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png) + +* Lẹhinna tẹ bọtini "Ṣiṣe" i.e. "Execute", olùmúlò (i.e. user interface) yóò sọrọ pẹ̀lú API rẹ, yóò ṣe afiranṣẹ àwọn èròjà, pàápàá jùlọ yóò gba àwọn àbájáde yóò si ṣafihan wọn loju ìbòjú: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png) + +### Ìdàkejì ìgbésókè àkọsílẹ̀ API + +Ní báyìí, lọ sí http://127.0.0.1:8000/redoc. + +* Ìdàkejì àkọsílẹ̀ API yóò ṣ'afihan ìbéèrè èròjà/pàrámítà tuntun àti kókó èsì ti API: + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) + +### Àtúnyẹ̀wò + +Ni akopọ, ìwọ yóò kéde ni **kete** àwọn iru èròjà/pàrámítà, kókó èsì API, abbl (i.e. àti bẹbẹ lọ), bi àwọn èròjà iṣẹ. + +O ṣe ìyẹn pẹ̀lú irúfẹ́ àmì ìtọ́kasí ìgbàlódé Python. + +O ò nílò láti kọ́ síńtáàsì tuntun, ìlànà tàbí ọ̀wọ́ kíláàsì kan pàtó, abbl (i.e. àti bẹbẹ lọ). + +Ìtọ́kasí **Python 3.8+** + +Fún àpẹẹrẹ, fún `int`: + +```Python +item_id: int +``` + +tàbí fún àwòṣe `Item` tí ó nira díẹ̀ síi: + +```Python +item: Item +``` + +... àti pẹ̀lú ìkéde kan ṣoṣo yẹn ìwọ yóò gbà: + +* Atilẹyin olootu, pẹ̀lú: + * Pipari. + * Àyẹ̀wò irúfẹ́ àmì ìtọ́kasí. +* Ìfọwọ́sí àkójọf'áyẹ̀wò (i.e. data): + * Aṣiṣe alaifọwọyi/aládàáṣiṣẹ́ àti aṣiṣe ti ó hàn kedere nígbàtí àwọn àkójọf'áyẹ̀wò (i.e. data) kò wulo tabi tí kò fẹsẹ̀ múlẹ̀. + * Ìfọwọ́sí fún ohun elo JSON tí ó jìn gan-an. +* Ìyípadà tí input àkójọf'áyẹ̀wò: tí ó wà láti nẹtiwọọki si àkójọf'áyẹ̀wò àti irúfẹ́ àmì ìtọ́kasí Python. Ó ń ka láti: + * JSON. + * èròjà ọ̀nà tí ò gbé gbà. + * èròjà ìbéèrè. + * Àwọn Kúkì + * Àwọn Àkọlé + * Àwọn Fọọmu + * Àwọn Fáìlì +* Ìyípadà èsì àkójọf'áyẹ̀wò: yíyípadà láti àkójọf'áyẹ̀wò àti irúfẹ́ àmì ìtọ́kasí Python si nẹtiwọọki (gẹ́gẹ́ bí JSON): + * Yí irúfẹ́ àmì ìtọ́kasí padà (`str`, `int`, `float`, `bool`, `list`, abbl i.e. àti bèbè ló). + * Àwọn ohun èlò `datetime`. + * Àwọn ohun èlò `UUID`. + * Àwọn awoṣẹ́ ibi ìpamọ́ àkójọf'áyẹ̀wò. + * ...àti ọ̀pọ̀lọpọ̀ díẹ̀ síi. +* Ìbáṣepọ̀ àkọsílẹ̀ API aládàáṣiṣẹ́, pẹ̀lú ìdàkejì àgbékalẹ̀-àwọn-olùmúlò (i.e user interfaces) méjì: + * Àgbékalẹ̀-olùmúlò Swagger. + * ReDoc. + +--- + +Nisinsin yi, tí ó padà sí àpẹẹrẹ ti tẹ́lẹ̀, **FastAPI** yóò: + +* Fọwọ́ sí i pé `item_id` wà nínú ọ̀nà ìbéèrè HTTP fún `GET` àti `PUT`. +* Fọwọ́ sí i pé `item_id` jẹ́ irúfẹ́ àmì ìtọ́kasí `int` fún ìbéèrè HTTP `GET` àti `PUT`. + * Tí kìí bá ṣe bẹ, oníbàárà yóò ríi àṣìṣe tí ó wúlò, kedere. +* Ṣàyẹ̀wò bóyá ìbéèrè àṣàyàn pàrámítà kan wà tí orúkọ rẹ̀ ń jẹ́ `q` (gẹ́gẹ́ bíi `http://127.0.0.1:8000/items/foo?q=somequery`) fún ìbéèrè HTTP `GET`. + * Bí wọ́n ṣe kéde pàrámítà `q` pẹ̀lú `= None`, ó jẹ́ àṣàyàn (i.e optional). + * Láìsí `None` yóò nílò (gẹ́gẹ́ bí kókó èsì ìbéèrè HTTP ṣe wà pẹ̀lú `PUT`). +* Fún àwọn ìbéèrè HTTP `PUT` sí `/items/{item_id}`, kà kókó èsì ìbéèrè HTTP gẹ́gẹ́ bí JSON: + * Ṣàyẹ̀wò pé ó ní àbùdá tí ó nílò èyí tíí ṣe `name` i.e. `orúkọ` tí ó yẹ kí ó jẹ́ `str`. + * Ṣàyẹ̀wò pé ó ní àbùdá tí ó nílò èyí tíí ṣe `price` i.e. `iye` tí ó gbọ́dọ̀ jẹ́ `float`. + * Ṣàyẹ̀wò pé ó ní àbùdá àṣàyàn `is_offer`, tí ó yẹ kí ó jẹ́ `bool`, tí ó bá wà níbẹ̀. + * Gbogbo èyí yóò tún ṣiṣẹ́ fún àwọn ohun èlò JSON tí ó jìn gidi gan-an. +* Yìí padà láti àti sí JSON lai fi ọwọ́ yi. +* Ṣe àkọsílẹ̀ ohun gbogbo pẹ̀lú OpenAPI, èyí tí yóò wà ní lílo nípaṣẹ̀: + * Àwọn ètò àkọsílẹ̀ ìbáṣepọ̀. + * Aládàáṣiṣẹ́ oníbárà èlètò tíí ṣẹ̀dá kóòdù, fún ọ̀pọ̀lọpọ̀ àwọn èdè. +* Pese àkọsílẹ̀ òní ìbáṣepọ̀ ti àwọn àgbékalẹ̀ ayélujára méjì tààrà. + +--- + +A ń ṣẹ̀ṣẹ̀ ń mú ẹyẹ bọ́ làpò ní, ṣùgbọ́n ó ti ni òye bí gbogbo rẹ̀ ṣe ń ṣiṣẹ́. + +Gbiyanju láti yí ìlà padà pẹ̀lú: + +```Python + return {"item_name": item.name, "item_id": item_id} +``` + +...láti: + +```Python + ... "item_name": item.name ... +``` + +...ṣí: + +```Python + ... "item_price": item.price ... +``` + +.. kí o sì wo bí olóòtú rẹ yóò ṣe parí àwọn àbùdá náà fúnra rẹ̀, yóò sì mọ irúfẹ́ wọn: + +![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) + +Fún àpẹẹrẹ pípé síi pẹ̀lú àwọn àbùdá mìíràn, wo Ìdánilẹ́kọ̀ọ́ - Ìtọ́sọ́nà Olùmúlò. + +**Itaniji gẹ́gẹ́ bí isọ'ye**: ìdánilẹ́kọ̀ọ́ - itọsọna olùmúlò pẹ̀lú: + +* Ìkéde àṣàyàn **pàrámítà** láti àwọn oriṣiriṣi ibòmíràn gẹ́gẹ́ bíi: àwọn **àkọlé èsì API**, **kúkì**, **ààyè fọọmu**, àti **fáìlì**. +* Bíi ó ṣe lé ṣètò **àwọn ìdíwọ́ ìfọwọ́sí** bí `maximum_length` tàbí `regex`. +* Ó lágbára púpọ̀ ó sì rọrùn láti lo ètò **Àfikún Ìgbẹ́kẹ̀lé Kóòdù**. +* Ààbò àti ìfọwọ́sowọ́pọ̀, pẹ̀lú àtìlẹ́yìn fún **OAuth2** pẹ̀lú **àmì JWT** àti **HTTP Ipilẹ ìfọwọ́sowọ́pọ̀**. +* Àwọn ìlànà ìlọsíwájú (ṣùgbọ́n tí ó rọrùn bákan náà) fún ìkéde **àwọn àwòṣe JSON tó jinlẹ̀** (ọpẹ́ pàtàkìsi sí Pydantic). +* Iṣọpọ **GraphQL** pẹ̀lú Strawberry àti àwọn ohun èlò ìwé kóòdù afọwọkọ mìíràn tí kò yí padà. +* Ọpọlọpọ àwọn àfikún àwọn ẹ̀yà (ọpẹ́ pàtàkìsi sí Starlette) bí: + * **WebSockets** + * àwọn ìdánwò tí ó rọrùn púpọ̀ lórí HTTPX àti `pytest` + * **CORS** + * **Cookie Sessions** + * ...àti síwájú síi. + +## Ìṣesí + +Àwọn àlá TechEmpower fi hàn pé **FastAPI** ń ṣiṣẹ́ lábẹ́ Uvicorn gẹ́gẹ́ bí ọ̀kan lára àwọn ìlànà Python tí ó yára jùlọ tí ó wà, ní ìsàlẹ̀ Starlette àti Uvicorn fúnra wọn (tí FastAPI ń lò fúnra rẹ̀). (*) + +Láti ní òye síi nípa rẹ̀, wo abala àwọn Àlá. + +## Àṣàyàn Àwọn Àfikún Ìgbẹ́kẹ̀lé Kóòdù + +Èyí tí Pydantic ń lò: + +* email_validator - fún ifọwọsi ímeèlì. +* pydantic-settings - fún ètò ìsàkóso. +* pydantic-extra-types - fún àfikún oríṣi láti lọ pẹ̀lú Pydantic. + +Èyí tí Starlette ń lò: + +* httpx - Nílò tí ó bá fẹ́ láti lọ `TestClient`. +* jinja2 - Nílò tí ó bá fẹ́ láti lọ iṣeto awoṣe aiyipada. +* python-multipart - Nílò tí ó bá fẹ́ láti ṣe àtìlẹ́yìn fún "àyẹ̀wò" fọọmu, pẹ̀lú `request.form()`. +* itsdangerous - Nílò fún àtìlẹ́yìn `SessionMiddleware`. +* pyyaml - Nílò fún àtìlẹ́yìn Starlette's `SchemaGenerator` (ó ṣe ṣe kí ó má nílò rẹ̀ fún FastAPI). +* ujson - Nílò tí ó bá fẹ́ láti lọ `UJSONResponse`. + +Èyí tí FastAPI / Starlette ń lò: + +* uvicorn - Fún olupin tí yóò sẹ́ àmúyẹ àti tí yóò ṣe ìpèsè fún iṣẹ́ rẹ tàbí ohun èlò rẹ. +* orjson - Nílò tí ó bá fẹ́ láti lọ `ORJSONResponse`. + +Ó lè fi gbogbo àwọn wọ̀nyí sórí ẹrọ pẹ̀lú `pip install "fastapi[all]"`. + +## Iwe-aṣẹ + +Iṣẹ́ yìí ni iwe-aṣẹ lábẹ́ àwọn òfin tí iwe-aṣẹ MIT. diff --git a/docs/yo/mkdocs.yml b/docs/yo/mkdocs.yml new file mode 100644 index 0000000000000..de18856f445aa --- /dev/null +++ b/docs/yo/mkdocs.yml @@ -0,0 +1 @@ +INHERIT: ../en/mkdocs.yml diff --git a/docs/zh-hant/docs/index.md b/docs/zh-hant/docs/index.md new file mode 100644 index 0000000000000..9859d3c518670 --- /dev/null +++ b/docs/zh-hant/docs/index.md @@ -0,0 +1,470 @@ +

+ FastAPI +

+

+ FastAPI 框架,高效能,易於學習,快速開發,適用於生產環境 +

+

+ + Test + + + Coverage + + + Package version + + + Supported Python versions + +

+ +--- + +**文件**: https://fastapi.tiangolo.com + +**程式碼**: https://github.com/tiangolo/fastapi + +--- + +FastAPI 是一個現代、快速(高效能)的 web 框架,用於 Python 3.8+ 並採用標準 Python 型別提示。 + +主要特點包含: + +- **快速**: 非常高的效能,可與 **NodeJS** 和 **Go** 效能相當 (歸功於 Starlette and Pydantic)。 [FastAPI 是最快的 Python web 框架之一](#performance)。 +- **極速開發**: 提高開發功能的速度約 200% 至 300%。 \* +- **更少的 Bug**: 減少約 40% 的人為(開發者)導致的錯誤。 \* +- **直覺**: 具有出色的編輯器支援,處處都有自動補全以減少偵錯時間。 +- **簡單**: 設計上易於使用和學習,大幅減少閱讀文件的時間。 +- **簡潔**: 最小化程式碼重複性。可以通過不同的參數聲明來實現更豐富的功能,和更少的錯誤。 +- **穩健**: 立即獲得生產級可用的程式碼,還有自動生成互動式文件。 +- **標準化**: 基於 (且完全相容於) OpenAPIs 的相關標準:OpenAPI(之前被稱為 Swagger)和JSON Schema。 + +\* 基於內部開發團隊在建立生產應用程式時的測試預估。 + +## 贊助 + + + +{% if sponsors %} +{% for sponsor in sponsors.gold -%} + +{% endfor -%} +{%- for sponsor in sponsors.silver -%} + +{% endfor %} +{% endif %} + + + +其他贊助商 + +## 評價 + +"_[...] 近期大量的使用 **FastAPI**。 [...] 目前正在計畫在**微軟**團隊的**機器學習**服務中導入。其中一些正在整合到核心的 **Windows** 產品和一些 **Office** 產品。_" + +
Kabir Khan - Microsoft (ref)
+ +--- + +"_我們使用 **FastAPI** 來建立產生**預測**結果的 **REST** 伺服器。 [for Ludwig]_" + +
Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala - Uber (ref)
+ +--- + +"_**Netflix** 很榮幸地宣布開源**危機管理**協調框架: **Dispatch**! [是使用 **FastAPI** 建構]_" + +
Kevin Glisson, Marc Vilanova, Forest Monsen - Netflix (ref)
+ +--- + +"_我對 **FastAPI** 興奮得不得了。它太有趣了!_" + +
Brian Okken - Python Bytes podcast host (ref)
+ +--- + +"_老實說,你建造的東西看起來非常堅固和精緻。在很多方面,這就是我想要的,看到有人建造它真的很鼓舞人心。_" + +
Timothy Crosley - Hug creator (ref)
+ +--- + +"_如果您想學習一種用於構建 REST API 的**現代框架**,不能錯過 **FastAPI** [...] 它非常快速、且易於使用和學習 [...]_" + +"_我們的 **APIs** 已經改用 **FastAPI** [...] 我想你會喜歡它 [...]_" + +
Ines Montani - Matthew Honnibal - Explosion AI 創辦人 - spaCy creators (ref) - (ref)
+ +--- + +"_如果有人想要建立一個生產環境的 Python API,我強烈推薦 **FastAPI**,它**設計精美**,**使用簡單**且**高度可擴充**,它已成為我們 API 優先開發策略中的**關鍵組件**,並且驅動了許多自動化服務,例如我們的 Virtual TAC Engineer。_" + +
Deon Pillsbury - Cisco (ref)
+ +--- + +## **Typer**,命令列中的 FastAPI + + + +如果你不是在開發網頁 API,而是正在開發一個在終端機中運行的命令列應用程式,不妨嘗試 **Typer**。 + +**Typer** 是 FastAPI 的小兄弟。他立志成為命令列的 **FastAPI**。 ⌨️ 🚀 + +## 安裝需求 + +Python 3.8+ + +FastAPI 是站在以下巨人的肩膀上: + +- Starlette 負責網頁的部分 +- Pydantic 負責資料的部分 + +## 安裝 + +
+ +```console +$ pip install fastapi + +---> 100% +``` + +
+ +你同時也會需要 ASGI 伺服器用於生產環境,像是 UvicornHypercorn。 + +
+ +```console +$ pip install "uvicorn[standard]" + +---> 100% +``` + +
+ +## 範例 + +### 建立 + +- 建立一個 python 檔案 `main.py`,並寫入以下程式碼: + +```Python +from typing import Union + +from fastapi import FastAPI + +app = FastAPI() + + +@app.get("/") +def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} +``` + +
+或可以使用 async def... + +如果你的程式使用 `async` / `await`,請使用 `async def`: + +```Python hl_lines="9 14" +from typing import Union + +from fastapi import FastAPI + +app = FastAPI() + + +@app.get("/") +async def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +async def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} +``` + +**注意**: + +如果你不知道是否會用到,可以查看 _"In a hurry?"_ 章節中,關於 `async` 和 `await` 的部分。 + +
+ +### 運行 + +使用以下指令運行伺服器: + +
+ +```console +$ uvicorn main:app --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +INFO: Started reloader process [28720] +INFO: Started server process [28722] +INFO: Waiting for application startup. +INFO: Application startup complete. +``` + +
+ +
+關於指令 uvicorn main:app --reload... + +該指令 `uvicorn main:app` 指的是: + +- `main`:`main.py` 檔案(一個 python 的 "模組")。 +- `app`:在 `main.py` 檔案中,使用 `app = FastAPI()` 建立的物件。 +- `--reload`:程式碼更改後會自動重新啟動,請僅在開發時使用此參數。 + +
+ +### 檢查 + +使用瀏覽器開啟 http://127.0.0.1:8000/items/5?q=somequery。 + +你將會看到以下的 JSON 回應: + +```JSON +{"item_id": 5, "q": "somequery"} +``` + +你已經建立了一個具有以下功能的 API: + +- 透過路徑 `/` 和 `/items/{item_id}` 接受 HTTP 請求。 +- 以上路經都接受 `GET` 請求(也被稱為 HTTP _方法_)。 +- 路徑 `/items/{item_id}` 有一個 `int` 型別的 `item_id` 參數。 +- 路徑 `/items/{item_id}` 有一個 `str` 型別的查詢參數 `q`。 + +### 互動式 API 文件 + +使用瀏覽器開啟 http://127.0.0.1:8000/docs。 + +你會看到自動生成的互動式 API 文件(由 Swagger UI 生成): + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +### ReDoc API 文件 + +使用瀏覽器開啟 http://127.0.0.1:8000/redoc。 + +你將看到 ReDoc 文件 (由 ReDoc 生成): + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +## 範例升級 + +現在繼續修改 `main.py` 檔案,來接收一個帶有 body 的 `PUT` 請求。 + +我們使用 Pydantic 來使用標準的 Python 型別聲明請求。 + +```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} +``` + +伺服器將自動重新載入(因為在上一步中,你向 `uvicorn` 指令添加了 `--reload` 的選項)。 + +### 互動式 API 文件升級 + +使用瀏覽器開啟 http://127.0.0.1:8000/docs。 + +- 互動式 API 文件會自動更新,並加入新的 body 請求: + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) + +- 點擊 "Try it out" 按鈕, 你可以填寫參數並直接與 API 互動: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png) + +- 然後點擊 "Execute" 按鈕,使用者介面將會向 API 發送請求,並將結果顯示在螢幕上: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png) + +### ReDoc API 文件升級 + +使用瀏覽器開啟 http://127.0.0.1:8000/redoc。 + +- ReDoc API 文件會自動更新,並加入新的參數和 body 請求: + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) + +### 總結 + +總結來說, 你就像宣告函式的參數型別一樣,只宣告了一次請求參數和請求主體參數等型別。 + +你使用 Python 標準型別來完成聲明。 + +你不需要學習新的語法、類別、方法或函式庫等等。 + +只需要使用 **Python 3.8 以上的版本**。 + +舉個範例,比如宣告 int 的型別: + +```Python +item_id: int +``` + +或是一個更複雜的 `Item` 模型: + +```Python +item: Item +``` + +在進行一次宣告後,你將獲得: + +- 編輯器支援: + - 自動補全 + - 型別檢查 +- 資料驗證: + - 驗證失敗時自動生成清楚的錯誤訊息 + - 可驗證多層巢狀的 JSON 物件 +- 轉換輸入的資料: 轉換來自網路請求到 Python 資料型別。包含以下數據: + - JSON + - 路徑參數 + - 查詢參數 + - Cookies + - 請求標頭 + - 表單 + - 文件 +- 轉換輸出的資料: 轉換 Python 資料型別到網路傳輸的 JSON: + - 轉換 Python 型別 (`str`、 `int`、 `float`、 `bool`、 `list` 等) + - `datetime` 物件 + - `UUID` 物件 + - 數據模型 + - ...還有其他更多 +- 自動生成的 API 文件,包含 2 種不同的使用介面: + - Swagger UI + - ReDoc + +--- + +回到前面的的程式碼範例,**FastAPI** 還會: + +- 驗證 `GET` 和 `PUT` 請求路徑中是否包含 `item_id`。 +- 驗證 `GET` 和 `PUT` 請求中的 `item_id` 是否是 `int` 型別。 + - 如果驗證失敗,將會返回清楚有用的錯誤訊息。 +- 查看 `GET` 請求中是否有命名為 `q` 的查詢參數 (例如 `http://127.0.0.1:8000/items/foo?q=somequery`)。 + - 因為 `q` 參數被宣告為 `= None`,所以是選填的。 + - 如果沒有宣告 `None`,則此參數將會是必填 (例如 `PUT` 範例的請求 body)。 +- 對於 `PUT` 的請求 `/items/{item_id}`,將會讀取 body 為 JSON: + - 驗證是否有必填屬性 `name` 且型別是 `str`。 + - 驗證是否有必填屬性 `price` 且型別是 `float`。 + - 驗證是否有選填屬性 `is_offer` 且型別是 `bool`。 + - 以上驗證都適用於多層次巢狀 JSON 物件。 +- 自動轉換 JSON 格式。 +- 透過 OpenAPI 文件來記錄所有內容,可以被用於: + - 互動式文件系統。 + - 自動為多種程式語言生成用戶端的程式碼。 +- 提供兩種交互式文件介面。 + +--- + +雖然我們只敘述了表面的功能,但其實你已經理解了它是如何執行。 + +試著修改以下程式碼: + +```Python + return {"item_name": item.name, "item_id": item_id} +``` + +從: + +```Python + ... "item_name": item.name ... +``` + +修改為: + +```Python + ... "item_price": item.price ... +``` + +然後觀察你的編輯器,會自動補全並且還知道他們的型別: + +![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) + +有關更多功能的完整範例,可以參考 教學 - 使用者指南。 + +**劇透警告**: 教學 - 使用者指南內容有: + +- 對來自不同地方的**參數**進行宣告:像是 **headers**, **cookies**, **form 表單**以及**上傳檔案**。 +- 如何設定 **驗證限制** 像是 `maximum_length` or `regex`。 +- 簡單且非常容易使用的 **依賴注入** 系統。 +- 安全性和身份驗證,包含提供支援 **OAuth2**、**JWT tokens** 和 **HTTP Basic** 驗證。 +- 更進階 (但同樣簡單) 的宣告 **多層次的巢狀 JSON 格式** (感謝 Pydantic)。 +- **GraphQL** 與 Strawberry 以及其他的相關函式庫進行整合。 +- 更多其他的功能 (感謝 Starlette) 像是: + - **WebSockets** + - 於 HTTPX 和 `pytest` 的非常簡單測試 + - **CORS** + - **Cookie Sessions** + - ...以及更多 + +## 效能 + +來自獨立機構 TechEmpower 的測試結果,顯示在 Uvicorn 執行下的 **FastAPI** 是 最快的 Python 框架之一, 僅次於 Starlette 和 Uvicorn 本身 (兩者是 FastAPI 的底層)。 (\*) + +想了解更多訊息,可以參考 測試結果。 + +## 可選的依賴套件 + +用於 Pydantic: + +- email_validator - 用於電子郵件驗證。 +- pydantic-settings - 用於設定管理。 +- pydantic-extra-types - 用於與 Pydantic 一起使用的額外型別。 + +用於 Starlette: + +- httpx - 使用 `TestClient`時必須安裝。 +- jinja2 - 使用預設的模板配置時必須安裝。 +- python-multipart - 需要使用 `request.form()` 對表單進行 "解析" 時安裝。 +- itsdangerous - 需要使用 `SessionMiddleware` 支援時安裝。 +- pyyaml - 用於支援 Starlette 的 `SchemaGenerator` (如果你使用 FastAPI,可能不需要它)。 +- ujson - 使用 `UJSONResponse` 時必須安裝。 + +用於 FastAPI / Starlette: + +- uvicorn - 用於加載和運行應用程式的服務器。 +- orjson - 使用 `ORJSONResponse`時必須安裝。 + +你可以使用 `pip install "fastapi[all]"` 來安裝這些所有依賴套件。 + +## 授權 + +該項目遵循 MIT 許可協議。 diff --git a/docs/zh-hant/docs/learn/index.md b/docs/zh-hant/docs/learn/index.md new file mode 100644 index 0000000000000..eb7d7096a58d3 --- /dev/null +++ b/docs/zh-hant/docs/learn/index.md @@ -0,0 +1,5 @@ +# 學習 + +以下是學習 FastAPI 的入門介紹和教學。 + +你可以將其視為一本**書籍**或一門**課程**,這是**官方**認可並推薦的 FastAPI 學習方式。 😎 diff --git a/docs/zh-hant/mkdocs.yml b/docs/zh-hant/mkdocs.yml new file mode 100644 index 0000000000000..de18856f445aa --- /dev/null +++ b/docs/zh-hant/mkdocs.yml @@ -0,0 +1 @@ +INHERIT: ../en/mkdocs.yml diff --git a/docs/zh/docs/advanced/additional-responses.md b/docs/zh/docs/advanced/additional-responses.md new file mode 100644 index 0000000000000..2a1e1ed891a79 --- /dev/null +++ b/docs/zh/docs/advanced/additional-responses.md @@ -0,0 +1,219 @@ +# OPENAPI 中的其他响应 + +您可以声明附加响应,包括附加状态代码、媒体类型、描述等。 + +这些额外的响应将包含在OpenAPI模式中,因此它们也将出现在API文档中。 + +但是对于那些额外的响应,你必须确保你直接返回一个像 `JSONResponse` 一样的 `Response` ,并包含你的状态代码和内容。 + +## `model`附加响应 +您可以向路径操作装饰器传递参数 `responses` 。 + +它接收一个 `dict`,键是每个响应的状态代码(如`200`),值是包含每个响应信息的其他 `dict`。 + +每个响应字典都可以有一个关键模型,其中包含一个 `Pydantic` 模型,就像 `response_model` 一样。 + +**FastAPI**将采用该模型,生成其`JSON Schema`并将其包含在`OpenAPI`中的正确位置。 + +例如,要声明另一个具有状态码 `404` 和`Pydantic`模型 `Message` 的响应,可以写: +```Python hl_lines="18 22" +{!../../../docs_src/additional_responses/tutorial001.py!} +``` + + +!!! Note + 请记住,您必须直接返回 `JSONResponse` 。 + +!!! Info + `model` 密钥不是OpenAPI的一部分。 + **FastAPI**将从那里获取`Pydantic`模型,生成` JSON Schema` ,并将其放在正确的位置。 + - 正确的位置是: + - 在键 `content` 中,其具有另一个`JSON`对象( `dict` )作为值,该`JSON`对象包含: + - 媒体类型的密钥,例如 `application/json` ,它包含另一个`JSON`对象作为值,该对象包含: + - 一个键` schema` ,它的值是来自模型的`JSON Schema`,正确的位置在这里。 + - **FastAPI**在这里添加了对OpenAPI中另一个地方的全局JSON模式的引用,而不是直接包含它。这样,其他应用程序和客户端可以直接使用这些JSON模式,提供更好的代码生成工具等。 + + +**在OpenAPI中为该路径操作生成的响应将是:** + +```json hl_lines="3-12" +{ + "responses": { + "404": { + "description": "Additional Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Message" + } + } + } + }, + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Item" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } +} + +``` +**模式被引用到OpenAPI模式中的另一个位置:** +```json hl_lines="4-16" +{ + "components": { + "schemas": { + "Message": { + "title": "Message", + "required": [ + "message" + ], + "type": "object", + "properties": { + "message": { + "title": "Message", + "type": "string" + } + } + }, + "Item": { + "title": "Item", + "required": [ + "id", + "value" + ], + "type": "object", + "properties": { + "id": { + "title": "Id", + "type": "string" + }, + "value": { + "title": "Value", + "type": "string" + } + } + }, + "ValidationError": { + "title": "ValidationError", + "required": [ + "loc", + "msg", + "type" + ], + "type": "object", + "properties": { + "loc": { + "title": "Location", + "type": "array", + "items": { + "type": "string" + } + }, + "msg": { + "title": "Message", + "type": "string" + }, + "type": { + "title": "Error Type", + "type": "string" + } + } + }, + "HTTPValidationError": { + "title": "HTTPValidationError", + "type": "object", + "properties": { + "detail": { + "title": "Detail", + "type": "array", + "items": { + "$ref": "#/components/schemas/ValidationError" + } + } + } + } + } + } +} + +``` +## 主响应的其他媒体类型 + +您可以使用相同的 `responses` 参数为相同的主响应添加不同的媒体类型。 + +例如,您可以添加一个额外的媒体类型` image/png` ,声明您的路径操作可以返回JSON对象(媒体类型 `application/json` )或PNG图像: + +```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 `参数。 + +您可以使用默认的状态码 `200` (或者您需要的自定义状态码)声明一个 `response_model `,然后直接在OpenAPI模式中在 `responses` 中声明相同响应的其他信息。 + +**FastAPI**将保留来自 `responses` 的附加信息,并将其与模型中的JSON Schema结合起来。 + +例如,您可以使用状态码 `404` 声明响应,该响应使用`Pydantic`模型并具有自定义的` description` 。 + +以及一个状态码为 `200` 的响应,它使用您的 `response_model` ,但包含自定义的 `example` : + +```Python hl_lines="20-31" +{!../../../docs_src/additional_responses/tutorial003.py!} +``` + +所有这些都将被合并并包含在您的OpenAPI中,并在API文档中显示: + +## 联合预定义响应和自定义响应 + +您可能希望有一些应用于许多路径操作的预定义响应,但是你想将不同的路径和自定义的相应组合在一块。 +对于这些情况,你可以使用Python的技术,将 `dict` 与 `**dict_to_unpack` 解包: +```Python +old_dict = { + "old key": "old value", + "second old key": "second old value", +} +new_dict = {**old_dict, "new key": "new value"} +``` + +这里, new_dict 将包含来自 old_dict 的所有键值对加上新的键值对: +```python +{ + "old key": "old value", + "second old key": "second old value", + "new key": "new value", +} +``` +您可以使用该技术在路径操作中重用一些预定义的响应,并将它们与其他自定义响应相结合。 +**例如:** +```Python hl_lines="13-17 26" +{!../../../docs_src/additional_responses/tutorial004.py!} +``` +## 有关OpenAPI响应的更多信息 + +要了解您可以在响应中包含哪些内容,您可以查看OpenAPI规范中的以下部分: + + [OpenAPI响应对象](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#responsesObject),它包括 Response Object 。 + + [OpenAPI响应对象](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#responseObject),您可以直接在 `responses` 参数中的每个响应中包含任何内容。包括 `description` 、 `headers` 、 `content` (其中是声明不同的媒体类型和JSON Schemas)和 `links` 。 diff --git a/docs/zh/docs/advanced/advanced-dependencies.md b/docs/zh/docs/advanced/advanced-dependencies.md new file mode 100644 index 0000000000000..b2f6e3559e671 --- /dev/null +++ b/docs/zh/docs/advanced/advanced-dependencies.md @@ -0,0 +1,71 @@ +# 高级依赖项 + +## 参数化的依赖项 + +我们之前看到的所有依赖项都是写死的函数或类。 + +但也可以为依赖项设置参数,避免声明多个不同的函数或类。 + +假设要创建校验查询参数 `q` 是否包含固定内容的依赖项。 + +但此处要把待检验的固定内容定义为参数。 + +## **可调用**实例 + +Python 可以把类实例变为**可调用项**。 + +这里说的不是类本身(类本就是可调用项),而是类实例。 + +为此,需要声明 `__call__` 方法: + +```Python hl_lines="10" +{!../../../docs_src/dependencies/tutorial011.py!} +``` + +本例中,**FastAPI** 使用 `__call__` 检查附加参数及子依赖项,稍后,还要调用它向*路径操作函数*传递值。 + +## 参数化实例 + +接下来,使用 `__init__` 声明用于**参数化**依赖项的实例参数: + +```Python hl_lines="7" +{!../../../docs_src/dependencies/tutorial011.py!} +``` + +本例中,**FastAPI** 不使用 `__init__`,我们要直接在代码中使用。 + +## 创建实例 + +使用以下代码创建类实例: + +```Python hl_lines="16" +{!../../../docs_src/dependencies/tutorial011.py!} +``` + +这样就可以**参数化**依赖项,它包含 `checker.fixed_content` 的属性 - `"bar"`。 + +## 把实例作为依赖项 + +然后,不要再在 `Depends(checker)` 中使用 `Depends(FixedContentQueryChecker)`, 而是要使用 `checker`,因为依赖项是类实例 - `checker`,不是类。 + +处理依赖项时,**FastAPI** 以如下方式调用 `checker`: + +```Python +checker(q="somequery") +``` + +……并用*路径操作函数*的参数 `fixed_content_included` 返回依赖项的值: + +```Python hl_lines="20" +{!../../../docs_src/dependencies/tutorial011.py!} +``` + +!!! tip "提示" + + 本章示例有些刻意,也看不出有什么用处。 + + 这个简例只是为了说明高级依赖项的运作机制。 + + 在有关安全的章节中,工具函数将以这种方式实现。 + + 只要能理解本章内容,就能理解安全工具背后的运行机制。 diff --git a/docs/zh/docs/advanced/async-sql-databases.md b/docs/zh/docs/advanced/async-sql-databases.md new file mode 100644 index 0000000000000..c79877ada5cd1 --- /dev/null +++ b/docs/zh/docs/advanced/async-sql-databases.md @@ -0,0 +1,167 @@ +# 异步 SQL 关系型数据库 + +**FastAPI** 使用 `encode/databases` 为连接数据库提供异步支持(`async` 与 `await`)。 + +`databases` 兼容以下数据库: + +* PostgreSQL +* MySQL +* SQLite + +本章示例使用 **SQLite**,它使用的是单文件,且 Python 内置集成了 SQLite,因此,可以直接复制并运行本章示例。 + +生产环境下,则要使用 **PostgreSQL** 等数据库服务器。 + +!!! tip "提示" + + 您可以使用 SQLAlchemy ORM([SQL 关系型数据库一章](../tutorial/sql-databases.md){.internal-link target=_blank})中的思路,比如,使用工具函数在数据库中执行操作,独立于 **FastAPI** 代码。 + + 本章不应用这些思路,等效于 Starlette 的对应内容。 + +## 导入与设置 `SQLAlchemy` + +* 导入 `SQLAlchemy` +* 创建 `metadata` 对象 +* 使用 `metadata` 对象创建 `notes` 表 + +```Python hl_lines="4 14 16-22" +{!../../../docs_src/async_sql_databases/tutorial001.py!} +``` + +!!! tip "提示" + + 注意,上例是都是纯 SQLAlchemy Core 代码。 + + `databases` 还没有进行任何操作。 + +## 导入并设置 `databases` + +* 导入 `databases` +* 创建 `DATABASE_URL` +* 创建 `database` + +```Python hl_lines="3 9 12" +{!../../../docs_src/async_sql_databases/tutorial001.py!} +``` + +!!! tip "提示" + + 连接 PostgreSQL 等数据库时,需要修改 `DATABASE_URL`。 + +## 创建表 + +本例中,使用 Python 文件创建表,但在生产环境中,应使用集成迁移等功能的 Alembic 创建表。 + +本例在启动 **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 模型都可以辅助验证、序列化(转换)并注释(存档)输入的数据。 + +因此,API 文档会显示这些数据。 + +## 连接与断开 + +* 创建 `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`,因此*路径操作函数*要声明为异步函数(`asnyc`)。 + +### 注意 `response_model=List[Note]` + +`response_model=List[Note]` 使用的是 `typing.List`。 + +它以笔记(`Note`)列表的形式存档(及验证、序列化、筛选)输出的数据。 + +## 创建笔记 + +创建新建笔记的*路径操作函数*: + +```Python hl_lines="61-65" +{!../../../docs_src/async_sql_databases/tutorial001.py!} +``` + +!!! Note "笔记" + + 注意,本例与数据库通信时使用 `await`,因此要把*路径操作函数*声明为异步函数(`asnyc`)。 + +### 关于 `{**note.dict(), "id": last_record_id}` + +`note` 是 Pydantic `Note` 对象: + +`note.dict()` 返回包含如下数据的**字典**: + +```Python +{ + "text": "Some note", + "completed": False, +} +``` + +但它不包含 `id` 字段。 + +因此要新建一个包含 `note.dict()` 键值对的**字典**: + +```Python +{**note.dict()} +``` + +`**note.dict()` 直接**解包**键值对, 因此,`{**note.dict()}` 是 `note.dict()` 的副本。 + +然后,扩展`dict` 副本,添加键值对`"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。 + +API 文档显示如下内容: + + + +## 更多说明 + +更多内容详见 Github 上的`encode/databases` 的说明。 diff --git a/docs/zh/docs/advanced/behind-a-proxy.md b/docs/zh/docs/advanced/behind-a-proxy.md new file mode 100644 index 0000000000000..738bd7119b522 --- /dev/null +++ b/docs/zh/docs/advanced/behind-a-proxy.md @@ -0,0 +1,351 @@ +# 使用代理 + +有些情况下,您可能要使用 Traefik 或 Nginx 等**代理**服务器,并添加应用不能识别的附加路径前缀配置。 + +此时,要使用 `root_path` 配置应用。 + +`root_path` 是 ASGI 规范提供的机制,FastAPI 就是基于此规范开发的(通过 Starlette)。 + +`root_path` 用于处理这些特定情况。 + +在挂载子应用时,也可以在内部使用。 + +## 移除路径前缀的代理 + +本例中,移除路径前缀的代理是指在代码中声明路径 `/app`,然后在应用顶层添加代理,把 **FastAPI** 应用放在 `/api/v1` 路径下。 + +本例的原始路径 `/app` 实际上是在 `/api/v1/app` 提供服务。 + +哪怕所有代码都假设只有 `/app`。 + +代理只在把请求传送给 Uvicorn 之前才会**移除路径前缀**,让应用以为它是在 `/app` 提供服务,因此不必在代码中加入前缀 `/api/v1`。 + +但之后,在(前端)打开 API 文档时,代理会要求在 `/openapi.json`,而不是 `/api/v1/openapi.json` 中提取 OpenAPI 概图。 + +因此, (运行在浏览器中的)前端会尝试访问 `/openapi.json`,但没有办法获取 OpenAPI 概图。 + +这是因为应用使用了以 `/api/v1` 为路径前缀的代理,前端要从 `/api/v1/openapi.json` 中提取 OpenAPI 概图。 + +```mermaid +graph LR + +browser("Browser") +proxy["Proxy on http://0.0.0.0:9999/api/v1/app"] +server["Server on http://127.0.0.1:8000/app"] + +browser --> proxy +proxy --> server +``` + +!!! tip "提示" + + IP `0.0.0.0` 常用于指程序监听本机或服务器上的所有有效 IP。 + +API 文档还需要 OpenAPI 概图声明 API `server` 位于 `/api/v1`(使用代理时的 URL)。例如: + +```JSON hl_lines="4-8" +{ + "openapi": "3.0.2", + // More stuff here + "servers": [ + { + "url": "/api/v1" + } + ], + "paths": { + // More stuff here + } +} +``` + +本例中的 `Proxy` 是 **Traefik**,`server` 是运行 FastAPI 应用的 **Uvicorn**。 + +### 提供 `root_path` + +为此,要以如下方式使用命令行选项 `--root-path`: + +
+ +```console +$ uvicorn main:app --root-path /api/v1 + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Hypercorn 也支持 `--root-path `选项。 + +!!! note "技术细节" + + ASGI 规范定义的 `root_path` 就是为了这种用例。 + + 并且 `--root-path` 命令行选项支持 `root_path`。 + +### 查看当前的 `root_path` + +获取应用为每个请求使用的当前 `root_path`,这是 `scope` 字典的内容(也是 ASGI 规范的内容)。 + +我们在这里的信息里包含 `roo_path` 只是为了演示。 + +```Python hl_lines="8" +{!../../../docs_src/behind_a_proxy/tutorial001.py!} +``` + +然后,用以下命令启动 Uvicorn: + +
+ +```console +$ uvicorn main:app --root-path /api/v1 + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +返回的响应如下: + +```JSON +{ + "message": "Hello World", + "root_path": "/api/v1" +} +``` + +### 在 FastAPI 应用里设置 `root_path` + +还有一种方案,如果不能提供 `--root-path` 或等效的命令行选项,则在创建 FastAPI 应用时要设置 `root_path` 参数。 + +```Python hl_lines="3" +{!../../../docs_src/behind_a_proxy/tutorial002.py!} +``` + +传递 `root_path` 给 `FastAPI` 与传递 `--root-path` 命令行选项给 Uvicorn 或 Hypercorn 一样。 + +### 关于 `root_path` + +注意,服务器(Uvicorn)只是把 `root_path` 传递给应用。 + +在浏览器中输入 http://127.0.0.1:8000/app 时能看到标准响应: + +```JSON +{ + "message": "Hello World", + "root_path": "/api/v1" +} +``` + +它不要求访问 `http://127.0.0.1:800/api/v1/app`。 + +Uvicorn 预期代理在 `http://127.0.0.1:8000/app` 访问 Uvicorn,而在顶部添加 `/api/v1` 前缀是代理要做的事情。 + +## 关于移除路径前缀的代理 + +注意,移除路径前缀的代理只是配置代理的方式之一。 + +大部分情况下,代理默认都不会移除路径前缀。 + +(未移除路径前缀时)代理监听 `https://myawesomeapp.com` 等对象,如果浏览器跳转到 `https://myawesomeapp.com/api/v1/app`,且服务器(例如 Uvicorn)监听 `http://127.0.0.1:8000` 代理(未移除路径前缀) 会在同样的路径:`http://127.0.0.1:8000/api/v1/app` 访问 Uvicorn。 + +## 本地测试 Traefik + +您可以轻易地在本地使用 Traefik 运行移除路径前缀的试验。 + +下载 Traefik,这是一个二进制文件,需要解压文件,并在 Terminal 中直接运行。 + +然后创建包含如下内容的 `traefik.toml` 文件: + +```TOML hl_lines="3" +[entryPoints] + [entryPoints.http] + address = ":9999" + +[providers] + [providers.file] + filename = "routes.toml" +``` + +这个文件把 Traefik 监听端口设置为 `9999`,并设置要使用另一个文件 `routes.toml`。 + +!!! tip "提示" + + 使用端口 9999 代替标准的 HTTP 端口 80,这样就不必使用管理员权限运行(`sudo`)。 + +接下来,创建 `routes.toml`: + +```TOML hl_lines="5 12 20" +[http] + [http.middlewares] + + [http.middlewares.api-stripprefix.stripPrefix] + prefixes = ["/api/v1"] + + [http.routers] + + [http.routers.app-http] + entryPoints = ["http"] + service = "app" + rule = "PathPrefix(`/api/v1`)" + middlewares = ["api-stripprefix"] + + [http.services] + + [http.services.app] + [http.services.app.loadBalancer] + [[http.services.app.loadBalancer.servers]] + url = "http://127.0.0.1:8000" +``` + +这个文件配置 Traefik 使用路径前缀 `/api/v1`。 + +然后,它把请求重定位到运行在 `http://127.0.0.1:8000` 上的 Uvicorn。 + +现在,启动 Traefik: + +
+ +```console +$ ./traefik --configFile=traefik.toml + +INFO[0000] Configuration loaded from file: /home/user/awesomeapi/traefik.toml +``` + +
+ +接下来,使用 Uvicorn 启动应用,并使用 `--root-path` 选项: + +
+ +```console +$ uvicorn main:app --root-path /api/v1 + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +### 查看响应 + +访问含 Uvicorn 端口的 URL:http://127.0.0.1:8000/app,就能看到标准响应: + +```JSON +{ + "message": "Hello World", + "root_path": "/api/v1" +} +``` + +!!! tip "提示" + + 注意,就算访问 `http://127.0.0.1:8000/app`,也显示从选项 `--root-path` 中提取的 `/api/v1`,这是 `root_path` 的值。 + +打开含 Traefik 端口的 URL,包含路径前缀:http://127.0.0.1:9999/api/v1/app。 + +得到同样的响应: + +```JSON +{ + "message": "Hello World", + "root_path": "/api/v1" +} +``` + +但这一次 URL 包含了代理提供的路径前缀:`/api/v1`。 + +当然,这是通过代理访问应用的方式,因此,路径前缀 `/app/v1` 版本才是**正确**的。 + +而不带路径前缀的版本(`http://127.0.0.1:8000/app`),则由 Uvicorn 直接提供,专供*代理*(Traefik)访问。 + +这演示了代理(Traefik)如何使用路径前缀,以及服务器(Uvicorn)如何使用选项 `--root-path` 中的 `root_path`。 + +### 查看文档 + +但这才是有趣的地方 ✨ + +访问应用的**官方**方式是通过含路径前缀的代理。因此,不出所料,如果没有在 URL 中添加路径前缀,直接访问通过 Uvicorn 运行的 API 文档,不能正常访问,因为需要通过代理才能访问。 + +输入 http://127.0.0.1:8000/docs 查看 API 文档: + + + +但输入**官方**链接 `/api/v1/docs`,并使用端口 `9999` 访问 API 文档,就能正常运行了!🎉 + +输入 http://127.0.0.1:9999/api/v1/docs 查看文档: + + + +一切正常。 ✔️ + +这是因为 FastAPI 在 OpenAPI 里使用 `root_path` 提供的 URL 创建默认 `server`。 + +## 附加的服务器 + +!!! warning "警告" + + 此用例较难,可以跳过。 + +默认情况下,**FastAPI** 使用 `root_path` 的链接在 OpenAPI 概图中创建 `server`。 + +但也可以使用其它备选 `servers`,例如,需要同一个 API 文档与 staging 和生产环境交互。 + +如果传递自定义 `servers` 列表,并有 `root_path`( 因为 API 使用了代理),**FastAPI** 会在列表开头使用这个 `root_path` 插入**服务器**。 + +例如: + +```Python hl_lines="4-7" +{!../../../docs_src/behind_a_proxy/tutorial003.py!} +``` + +这段代码生产如下 OpenAPI 概图: + +```JSON hl_lines="5-7" +{ + "openapi": "3.0.2", + // More stuff here + "servers": [ + { + "url": "/api/v1" + }, + { + "url": "https://stag.example.com", + "description": "Staging environment" + }, + { + "url": "https://prod.example.com", + "description": "Production environment" + } + ], + "paths": { + // More stuff here + } +} +``` + +!!! tip "提示" + + 注意,自动生成服务器时,`url` 的值 `/api/v1` 提取自 `roog_path`。 + +http://127.0.0.1:9999/api/v1/docs 的 API 文档所示如下: + + + +!!! tip "提示" + + API 文档与所选的服务器进行交互。 + +### 从 `root_path` 禁用自动服务器 + +如果不想让 **FastAPI** 包含使用 `root_path` 的自动服务器,则要使用参数 `root_path_in_servers=False`: + +```Python hl_lines="9" +{!../../../docs_src/behind_a_proxy/tutorial004.py!} +``` + +这样,就不会在 OpenAPI 概图中包含服务器了。 + +## 挂载子应用 + +如需挂载子应用(详见 [子应用 - 挂载](./sub-applications.md){.internal-link target=_blank}),也要通过 `root_path` 使用代理,这与正常应用一样,别无二致。 + +FastAPI 在内部使用 `root_path`,因此子应用也可以正常运行。✨ diff --git a/docs/zh/docs/advanced/custom-request-and-route.md b/docs/zh/docs/advanced/custom-request-and-route.md new file mode 100644 index 0000000000000..0a0257d080bbc --- /dev/null +++ b/docs/zh/docs/advanced/custom-request-and-route.md @@ -0,0 +1,113 @@ +# 自定义请求与 APIRoute 类 + +有时,我们要覆盖 `Request` 与 `APIRoute` 类使用的逻辑。 + +尤其是中间件里的逻辑。 + +例如,在应用处理请求体前,预先读取或操控请求体。 + +!!! danger "危险" + + 本章内容**较难**。 + + **FastAPI** 新手可跳过本章。 + +## 用例 + +常见用例如下: + +* 把 `msgpack` 等非 JSON 请求体转换为 JSON +* 解压 gzip 压缩的请求体 +* 自动记录所有请求体的日志 + +## 处理自定义请求体编码 + +下面学习如何使用自定义 `Request` 子类压缩 gizp 请求。 + +并在自定义请求的类中使用 `APIRoute` 子类。 + +### 创建自定义 `GzipRequest` 类 + +!!! tip "提示" + + 本例只是为了说明 `GzipRequest` 类如何运作。如需 Gzip 支持,请使用 [`GzipMiddleware`](./middleware.md#gzipmiddleware){.internal-link target=_blank}。 + +首先,创建 `GzipRequest` 类,覆盖解压请求头中请求体的 `Request.body()` 方法。 + +请求头中没有 `gzip` 时,`GzipRequest` 不会解压请求体。 + +这样就可以让同一个路由类处理 gzip 压缩的请求或未压缩的请求。 + +```Python hl_lines="8-15" +{!../../../docs_src/custom_request_and_route/tutorial001.py!} +``` + +### 创建自定义 `GzipRoute` 类 + +接下来,创建使用 `GzipRequest` 的 `fastapi.routing.APIRoute ` 的自定义子类。 + +此时,这个自定义子类会覆盖 `APIRoute.get_route_handler()`。 + +`APIRoute.get_route_handler()` 方法返回的是函数,并且返回的函数接收请求并返回响应。 + +本例用它根据原始请求创建 `GzipRequest`。 + +```Python hl_lines="18-26" +{!../../../docs_src/custom_request_and_route/tutorial001.py!} +``` + +!!! note "技术细节" + + `Request` 的 `request.scope` 属性是包含关联请求元数据的字典。 + + `Request` 的 `request.receive` 方法是**接收**请求体的函数。 + + `scope` 字典与 `receive` 函数都是 ASGI 规范的内容。 + + `scope` 与 `receive` 也是创建新的 `Request` 实例所需的。 + + `Request` 的更多内容详见 Starlette 官档 - 请求。 + +`GzipRequest.get_route_handler` 返回函数的唯一区别是把 `Request` 转换成了 `GzipRequest`。 + +如此一来,`GzipRequest` 把数据传递给*路径操作*前,就会解压数据(如需)。 + +之后,所有处理逻辑都一样。 + +但因为改变了 `GzipRequest.body`,**FastAPI** 加载请求体时会自动解压。 + +## 在异常处理器中访问请求体 + +!!! tip "提示" + + 为了解决同样的问题,在 `RequestValidationError` 的自定义处理器使用 `body` ([处理错误](../tutorial/handling-errors.md#use-the-requestvalidationerror-body){.internal-link target=_blank})可能会更容易。 + + 但本例仍然可行,而且本例展示了如何与内部组件进行交互。 + +同样也可以在异常处理器中访问请求体。 + +此时要做的只是处理 `try`/`except` 中的请求: + +```Python hl_lines="13 15" +{!../../../docs_src/custom_request_and_route/tutorial002.py!} +``` + +发生异常时,`Request` 实例仍在作用域内,因此处理错误时可以读取和使用请求体: + +```Python hl_lines="16-18" +{!../../../docs_src/custom_request_and_route/tutorial002.py!} +``` + +## 在路由中自定义 `APIRoute` 类 + +您还可以设置 `APIRoute` 的 `route_class` 参数: + +```Python hl_lines="26" +{!../../../docs_src/custom_request_and_route/tutorial003.py!} +``` + +本例中,*路径操作*下的 `router` 使用自定义的 `TimedRoute` 类,并在响应中包含输出生成响应时间的 `X-Response-Time` 响应头: + +```Python hl_lines="13-20" +{!../../../docs_src/custom_request_and_route/tutorial003.py!} +``` diff --git a/docs/zh/docs/advanced/dataclasses.md b/docs/zh/docs/advanced/dataclasses.md new file mode 100644 index 0000000000000..5a93877cc4317 --- /dev/null +++ b/docs/zh/docs/advanced/dataclasses.md @@ -0,0 +1,99 @@ +# 使用数据类 + +FastAPI 基于 **Pydantic** 构建,前文已经介绍过如何使用 Pydantic 模型声明请求与响应。 + +但 FastAPI 还可以使用数据类(`dataclasses`): + +```Python hl_lines="1 7-12 19-20" +{!../../../docs_src/dataclasses/tutorial001.py!} +``` + +这还是借助于 **Pydantic** 及其内置的 `dataclasses`。 + +因此,即便上述代码没有显式使用 Pydantic,FastAPI 仍会使用 Pydantic 把标准数据类转换为 Pydantic 数据类(`dataclasses`)。 + +并且,它仍然支持以下功能: + +* 数据验证 +* 数据序列化 +* 数据存档等 + +数据类的和运作方式与 Pydantic 模型相同。实际上,它的底层使用的也是 Pydantic。 + +!!! info "说明" + + 注意,数据类不支持 Pydantic 模型的所有功能。 + + 因此,开发时仍需要使用 Pydantic 模型。 + + 但如果数据类很多,这一技巧能给 FastAPI 开发 Web API 增添不少助力。🤓 + +## `response_model` 使用数据类 + +在 `response_model` 参数中使用 `dataclasses`: + +```Python hl_lines="1 7-13 19" +{!../../../docs_src/dataclasses/tutorial002.py!} +``` + +本例把数据类自动转换为 Pydantic 数据类。 + +API 文档中也会显示相关概图: + + + +## 在嵌套数据结构中使用数据类 + +您还可以把 `dataclasses` 与其它类型注解组合在一起,创建嵌套数据结构。 + +还有一些情况也可以使用 Pydantic 的 `dataclasses`。例如,在 API 文档中显示错误。 + +本例把标准的 `dataclasses` 直接替换为 `pydantic.dataclasses`: + +```{ .python .annotate hl_lines="1 5 8-11 14-17 23-25 28" } +{!../../../docs_src/dataclasses/tutorial003.py!} +``` + +1. 本例依然要从标准的 `dataclasses` 中导入 `field`; + +2. 使用 `pydantic.dataclasses` 直接替换 `dataclasses`; + +3. `Author` 数据类包含 `Item` 数据类列表; + +4. `Author` 数据类用于 `response_model` 参数; + +5. 其它带有数据类的标准类型注解也可以作为请求体; + + 本例使用的是 `Item` 数据类列表; + +6. 这行代码返回的是包含 `items` 的字典,`items` 是数据类列表; + + FastAPI 仍能把数据序列化为 JSON; + +7. 这行代码中,`response_model` 的类型注解是 `Author` 数据类列表; + + 再一次,可以把 `dataclasses` 与标准类型注解一起使用; + +8. 注意,*路径操作函数*使用的是普通函数,不是异步函数; + + 与往常一样,在 FastAPI 中,可以按需组合普通函数与异步函数; + + 如果不清楚何时使用异步函数或普通函数,请参阅**急不可待?**一节中对 `async` 与 `await` 的说明; + +9. *路径操作函数*返回的不是数据类(虽然它可以返回数据类),而是返回内含数据的字典列表; + + FastAPI 使用(包含数据类的) `response_model` 参数转换响应。 + +把 `dataclasses` 与其它类型注解组合在一起,可以组成不同形式的复杂数据结构。 + +更多内容详见上述代码内的注释。 + +## 深入学习 + +您还可以把 `dataclasses` 与其它 Pydantic 模型组合在一起,继承合并的模型,把它们包含在您自己的模型里。 + +详见 Pydantic 官档 - 数据类。 + +## 版本 + +本章内容自 FastAPI `0.67.0` 版起生效。🔖 diff --git a/docs/zh/docs/advanced/events.md b/docs/zh/docs/advanced/events.md new file mode 100644 index 0000000000000..6017b8ef02f20 --- /dev/null +++ b/docs/zh/docs/advanced/events.md @@ -0,0 +1,51 @@ +# 事件:启动 - 关闭 + +**FastAPI** 支持定义在应用启动前,或应用关闭后执行的事件处理器(函数)。 + +事件函数既可以声明为异步函数(`async def`),也可以声明为普通函数(`def`)。 + +!!! warning "警告" + + **FastAPI** 只执行主应用中的事件处理器,不执行[子应用 - 挂载](./sub-applications.md){.internal-link target=_blank}中的事件处理器。 + +## `startup` 事件 + +使用 `startup` 事件声明 `app` 启动前运行的函数: + +```Python hl_lines="8" +{!../../../docs_src/events/tutorial001.py!} +``` + +本例中,`startup` 事件处理器函数为项目数据库(只是**字典**)提供了一些初始值。 + +**FastAPI** 支持多个事件处理器函数。 + +只有所有 `startup` 事件处理器运行完毕,**FastAPI** 应用才开始接收请求。 + +## `shutdown` 事件 + +使用 `shutdown` 事件声明 `app` 关闭时运行的函数: + +```Python hl_lines="6" +{!../../../docs_src/events/tutorial002.py!} +``` + +此处,`shutdown` 事件处理器函数在 `log.txt` 中写入一行文本 `Application shutdown`。 + +!!! info "说明" + + `open()` 函数中,`mode="a"` 指的是**追加**。因此这行文本会添加在文件已有内容之后,不会覆盖之前的内容。 + +!!! tip "提示" + + 注意,本例使用 Python `open()` 标准函数与文件交互。 + + 这个函数执行 I/O(输入/输出)操作,需要等待内容写进磁盘。 + + 但 `open()` 函数不支持使用 `async` 与 `await`。 + + 因此,声明事件处理函数要使用 `def`,不能使用 `asnyc def`。 + +!!! info "说明" + + 有关事件处理器的详情,请参阅 Starlette 官档 - 事件。 diff --git a/docs/zh/docs/advanced/extending-openapi.md b/docs/zh/docs/advanced/extending-openapi.md new file mode 100644 index 0000000000000..4669614621b3f --- /dev/null +++ b/docs/zh/docs/advanced/extending-openapi.md @@ -0,0 +1,252 @@ +# 扩展 OpenAPI + +!!! warning "警告" + + 本章介绍的功能较难,您可以跳过阅读。 + + 如果您刚开始学习**用户指南**,最好跳过本章。 + + 如果您确定要修改 OpenAPI 概图,请继续阅读。 + +某些情况下,我们需要修改 OpenAPI 概图。 + +本章介绍如何修改 OpenAPI 概图。 + +## 常规流程 + +常规(默认)流程如下。 + +`FastAPI` 应用(实例)提供了返回 OpenAPI 概图的 `.openapi()` 方法。 + +作为应用对象创建的组成部分,要注册 `/openapi.json` (或其它为 `openapi_url` 设置的任意内容)*路径操作*。 + +它只返回包含应用的 `.openapi()` 方法操作结果的 JSON 响应。 + +但默认情况下,`.openapi()` 只是检查 `.openapi_schema` 属性是否包含内容,并返回其中的内容。 + +如果 `.openapi_schema` 属性没有内容,该方法就使用 `fastapi.openapi.utils.get_openapi` 工具函数生成内容。 + +`get_openapi()` 函数接收如下参数: + +* `title`:文档中显示的 OpenAPI 标题 +* `version`:API 的版本号,例如 `2.5.0` +* `openapi_version`: OpenAPI 规范的版本号,默认为最新版: `3.0.2` +* `description`:API 的描述说明 +* `routes`:路由列表,每个路由都是注册的*路径操作*。这些路由是从 `app.routes` 中提取的。 + +## 覆盖默认值 + +`get_openapi()` 工具函数还可以用于生成 OpenAPI 概图,并利用上述信息参数覆盖指定的内容。 + +例如,使用 ReDoc 的 OpenAPI 扩展添加自定义 Logo。 + +### 常规 **FastAPI** + +首先,编写常规 **FastAPI** 应用: + +```Python hl_lines="1 4 7-9" +{!../../../docs_src/extending_openapi/tutorial001.py!} +``` + +### 生成 OpenAPI 概图 + +然后,在 `custom_openapi()` 函数里使用 `get_openapi()` 工具函数生成 OpenAPI 概图: + +```Python hl_lines="2 15-20" +{!../../../docs_src/extending_openapi/tutorial001.py!} +``` + +### 修改 OpenAPI 概图 + +添加 ReDoc 扩展信息,为 OpenAPI 概图里的 `info` **对象**添加自定义 `x-logo`: + +```Python hl_lines="21-23" +{!../../../docs_src/extending_openapi/tutorial001.py!} +``` + +### 缓存 OpenAPI 概图 + +把 `.openapi_schema` 属性当作**缓存**,存储生成的概图。 + +通过这种方式,**FastAPI** 应用不必在用户每次打开 API 文档时反复生成概图。 + +只需生成一次,下次请求时就可以使用缓存的概图。 + +```Python hl_lines="13-14 24-25" +{!../../../docs_src/extending_openapi/tutorial001.py!} +``` + +### 覆盖方法 + +用新函数替换 `.openapi()` 方法。 + +```Python hl_lines="28" +{!../../../docs_src/extending_openapi/tutorial001.py!} +``` + +### 查看文档 + +打开 http://127.0.0.1:8000/redoc,查看自定义 Logo(本例中是 **FastAPI** 的 Logo): + + + +## 文档 JavaScript 与 CSS 自托管 + +FastAPI 支持 **Swagger UI** 和 **ReDoc** 两种 API 文档,这两种文档都需要调用 JavaScript 与 CSS 文件。 + +这些文件默认由 CDN 提供支持服务。 + +但也可以自定义设置指定的 CDN 或自行提供文件服务。 + +这种做法很常用,例如,在没有联网或本地局域网时也能让应用在离线状态下正常运行。 + +本文介绍如何为 FastAPI 应用提供文件自托管服务,并设置文档使用这些文件。 + +### 项目文件架构 + +假设项目文件架构如下: + +``` +. +├── app +│ ├── __init__.py +│ ├── main.py +``` + +接下来,创建存储静态文件的文件夹。 + +新的文件架构如下: + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +└── static/ +``` + +### 下载文件 + +下载文档所需的静态文件,把文件放到 `static/` 文件夹里。 + +右键点击链接,选择**另存为...**。 + +**Swagger UI** 使用如下文件: + +* `swagger-ui-bundle.js` +* `swagger-ui.css` + +**ReDoc** 使用如下文件: + +* `redoc.standalone.js` + +保存好后,文件架构所示如下: + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +└── static + ├── redoc.standalone.js + ├── swagger-ui-bundle.js + └── swagger-ui.css +``` + +### 安装 `aiofiles` + +现在,安装 `aiofiles`: + + +
+ +```console +$ pip install aiofiles + +---> 100% +``` + +
+ +### 静态文件服务 + +* 导入 `StaticFiles` +* 在指定路径下**挂载** `StaticFiles()` 实例 + +```Python hl_lines="7 11" +{!../../../docs_src/extending_openapi/tutorial002.py!} +``` + +### 测试静态文件 + +启动应用,打开 http://127.0.0.1:8000/static/redoc.standalone.js。 + +就能看到 **ReDoc** 的 JavaScript 文件。 + +该文件开头如下: + +```JavaScript +/*! + * ReDoc - OpenAPI/Swagger-generated API Reference Documentation + * ------------------------------------------------------------- + * Version: "2.0.0-rc.18" + * Repo: https://github.com/Redocly/redoc + */ +!function(e,t){"object"==typeof exports&&"object"==typeof m + +... +``` + +能打开这个文件就表示 FastAPI 应用能提供静态文件服务,并且文档要调用的静态文件放到了正确的位置。 + +接下来,使用静态文件配置文档。 + +### 禁用 API 文档 + +第一步是禁用 API 文档,就是使用 CDN 的默认文档。 + +创建 `FastAPI` 应用时把文档的 URL 设置为 `None` 即可禁用默认文档: + +```Python hl_lines="9" +{!../../../docs_src/extending_openapi/tutorial002.py!} +``` + +### 添加自定义文档 + +现在,创建自定义文档的*路径操作*。 + +导入 FastAPI 内部函数为文档创建 HTML 页面,并把所需参数传递给这些函数: + +* `openapi_url`: API 文档获取 OpenAPI 概图的 HTML 页面,此处可使用 `app.openapi_url` +* `title`:API 的标题 +* `oauth2_redirect_url`:此处使用 `app.swagger_ui_oauth2_redirect_url` 作为默认值 +* `swagger_js_url`:Swagger UI 文档所需 **JavaScript** 文件的 URL,即为应用提供服务的文件 +* `swagger_css_url`:Swagger UI 文档所需 **CSS** 文件的 URL,即为应用提供服务的文件 + +添加 ReDoc 文档的方式与此类似…… + +```Python hl_lines="2-6 14-22 25-27 30-36" +{!../../../docs_src/extending_openapi/tutorial002.py!} +``` + +!!! tip "提示" + + `swagger_ui_redirect` 的*路径操作*是 OAuth2 的辅助函数。 + + 集成 API 与 OAuth2 第三方应用时,您能进行身份验证,使用请求凭证返回 API 文档,并使用真正的 OAuth2 身份验证与 API 文档进行交互操作。 + + Swagger UI 在后台进行处理,但它需要这个**重定向**辅助函数。 + +### 创建测试*路径操作* + +现在,测试各项功能是否能顺利运行。创建*路径操作*: + +```Python hl_lines="39-41" +{!../../../docs_src/extending_openapi/tutorial002.py!} +``` + +### 测试文档 + +断开 WiFi 连接,打开 http://127.0.0.1:8000/docs,刷新页面。 + +现在,就算没有联网也能查看并操作 API 文档。 diff --git a/docs/zh/docs/advanced/generate-clients.md b/docs/zh/docs/advanced/generate-clients.md new file mode 100644 index 0000000000000..e222e479c805e --- /dev/null +++ b/docs/zh/docs/advanced/generate-clients.md @@ -0,0 +1,266 @@ +# 生成客户端 + +因为 **FastAPI** 是基于OpenAPI规范的,自然您可以使用许多相匹配的工具,包括自动生成API文档 (由 Swagger UI 提供)。 + +一个不太明显而又特别的优势是,你可以为你的API针对不同的**编程语言**来**生成客户端**(有时候被叫做 **SDKs** )。 + +## OpenAPI 客户端生成 + +有许多工具可以从**OpenAPI**生成客户端。 + +一个常见的工具是 OpenAPI Generator。 + +如果您正在开发**前端**,一个非常有趣的替代方案是 openapi-typescript-codegen。 + +## 生成一个 TypeScript 前端客户端 + +让我们从一个简单的 FastAPI 应用开始: + +=== "Python 3.9+" + + ```Python hl_lines="7-9 12-13 16-17 21" + {!> ../../../docs_src/generate_clients/tutorial001_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9-11 14-15 18 19 23" + {!> ../../../docs_src/generate_clients/tutorial001.py!} + ``` + +请注意,*路径操作* 定义了他们所用于请求数据和回应数据的模型,所使用的模型是`Item` 和 `ResponseMessage`。 + +### API 文档 + +如果您访问API文档,您将看到它具有在请求中发送和在响应中接收数据的**模式(schemas)**: + + + +您可以看到这些模式,因为它们是用程序中的模型声明的。 + +那些信息可以在应用的 **OpenAPI模式** 被找到,然后显示在API文档中(通过Swagger UI)。 + +OpenAPI中所包含的模型里有相同的信息可以用于 **生成客户端代码**。 + +### 生成一个TypeScript 客户端 + +现在我们有了带有模型的应用,我们可以为前端生成客户端代码。 + +#### 安装 `openapi-typescript-codegen` + +您可以使用以下工具在前端代码中安装 `openapi-typescript-codegen`: + +
+ +```console +$ npm install openapi-typescript-codegen --save-dev + +---> 100% +``` + +
+ +#### 生成客户端代码 + +要生成客户端代码,您可以使用现在将要安装的命令行应用程序 `openapi`。 + +因为它安装在本地项目中,所以您可能无法直接使用此命令,但您可以将其放在 `package.json` 文件中。 + +它可能看起来是这样的: + +```JSON hl_lines="7" +{ + "name": "frontend-app", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "generate-client": "openapi --input http://localhost:8000/openapi.json --output ./src/client --client axios" + }, + "author": "", + "license": "", + "devDependencies": { + "openapi-typescript-codegen": "^0.20.1", + "typescript": "^4.6.2" + } +} +``` + +在这里添加 NPM `generate-client` 脚本后,您可以使用以下命令运行它: + +
+ +```console +$ npm run generate-client + +frontend-app@1.0.0 generate-client /home/user/code/frontend-app +> openapi --input http://localhost:8000/openapi.json --output ./src/client --client axios +``` + +
+ +此命令将在 `./src/client` 中生成代码,并将在其内部使用 `axios`(前端HTTP库)。 + +### 尝试客户端代码 + +现在您可以导入并使用客户端代码,它可能看起来像这样,请注意,您可以为这些方法使用自动补全: + + + +您还将自动补全要发送的数据: + + + +!!! tip + 请注意, `name` 和 `price` 的自动补全,是通过其在`Item`模型(FastAPI)中的定义实现的。 + +如果发送的数据字段不符,你也会看到编辑器的错误提示: + + + +响应(response)对象也拥有自动补全: + + + +## 带有标签的 FastAPI 应用 + +在许多情况下,你的FastAPI应用程序会更复杂,你可能会使用标签来分隔不同组的*路径操作(path operations)*。 + +例如,您可以有一个用 `items` 的部分和另一个用于 `users` 的部分,它们可以用标签来分隔: + +=== "Python 3.9+" + + ```Python hl_lines="21 26 34" + {!> ../../../docs_src/generate_clients/tutorial002_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="23 28 36" + {!> ../../../docs_src/generate_clients/tutorial002.py!} + ``` + +### 生成带有标签的 TypeScript 客户端 + +如果您使用标签为FastAPI应用生成客户端,它通常也会根据标签分割客户端代码。 + +通过这种方式,您将能够为客户端代码进行正确地排序和分组: + + + +在这个案例中,您有: + +* `ItemsService` +* `UsersService` + +### 客户端方法名称 + +现在生成的方法名像 `createItemItemsPost` 看起来不太简洁: + +```TypeScript +ItemsService.createItemItemsPost({name: "Plumbus", price: 5}) +``` + +...这是因为客户端生成器为每个 *路径操作* 使用OpenAPI的内部 **操作 ID(operation ID)**。 + +OpenAPI要求每个操作 ID 在所有 *路径操作* 中都是唯一的,因此 FastAPI 使用**函数名**、**路径**和**HTTP方法/操作**来生成此操作ID,因为这样可以确保这些操作 ID 是唯一的。 + +但接下来我会告诉你如何改进。 🤓 + +## 自定义操作ID和更好的方法名 + +您可以**修改**这些操作ID的**生成**方式,以使其更简洁,并在客户端中具有**更简洁的方法名称**。 + +在这种情况下,您必须确保每个操作ID在其他方面是**唯一**的。 + +例如,您可以确保每个*路径操作*都有一个标签,然后根据**标签**和*路径操作***名称**(函数名)来生成操作ID。 + +### 自定义生成唯一ID函数 + +FastAPI为每个*路径操作*使用一个**唯一ID**,它用于**操作ID**,也用于任何所需自定义模型的名称,用于请求或响应。 + +你可以自定义该函数。它接受一个 `APIRoute` 对象作为输入,并输出一个字符串。 + +例如,以下是一个示例,它使用第一个标签(你可能只有一个标签)和*路径操作*名称(函数名)。 + +然后,你可以将这个自定义函数作为 `generate_unique_id_function` 参数传递给 **FastAPI**: + +=== "Python 3.9+" + + ```Python hl_lines="6-7 10" + {!> ../../../docs_src/generate_clients/tutorial003_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="8-9 12" + {!> ../../../docs_src/generate_clients/tutorial003.py!} + ``` + +### 使用自定义操作ID生成TypeScript客户端 + +现在,如果你再次生成客户端,你会发现它具有改善的方法名称: + + + +正如你所见,现在方法名称中只包含标签和函数名,不再包含URL路径和HTTP操作的信息。 + +### 预处理用于客户端生成器的OpenAPI规范 + +生成的代码仍然存在一些**重复的信息**。 + +我们已经知道该方法与 **items** 相关,因为它在 `ItemsService` 中(从标签中获取),但方法名中仍然有标签名作为前缀。😕 + +一般情况下对于OpenAPI,我们可能仍然希望保留它,因为这将确保操作ID是**唯一的**。 + +但对于生成的客户端,我们可以在生成客户端之前**修改** OpenAPI 操作ID,以使方法名称更加美观和**简洁**。 + +我们可以将 OpenAPI JSON 下载到一个名为`openapi.json`的文件中,然后使用以下脚本**删除此前缀的标签**: + +```Python +{!../../../docs_src/generate_clients/tutorial004.py!} +``` + +通过这样做,操作ID将从类似于 `items-get_items` 的名称重命名为 `get_items` ,这样客户端生成器就可以生成更简洁的方法名称。 + +### 使用预处理的OpenAPI生成TypeScript客户端 + +现在,由于最终结果保存在文件openapi.json中,你可以修改 package.json 文件以使用此本地文件,例如: + +```JSON hl_lines="7" +{ + "name": "frontend-app", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "generate-client": "openapi --input ./openapi.json --output ./src/client --client axios" + }, + "author": "", + "license": "", + "devDependencies": { + "openapi-typescript-codegen": "^0.20.1", + "typescript": "^4.6.2" + } +} +``` + +生成新的客户端之后,你现在将拥有**清晰的方法名称**,具备**自动补全**、**错误提示**等功能: + + + +## 优点 + +当使用自动生成的客户端时,你将获得以下的自动补全功能: + +* 方法。 +* 请求体中的数据、查询参数等。 +* 响应数据。 + +你还将获得针对所有内容的错误提示。 + +每当你更新后端代码并**重新生成**前端代码时,新的*路径操作*将作为方法可用,旧的方法将被删除,并且其他任何更改将反映在生成的代码中。 🤓 + +这也意味着如果有任何更改,它将自动**反映**在客户端代码中。如果你**构建**客户端,在使用的数据上存在**不匹配**时,它将报错。 + +因此,你将在开发周期的早期**检测到许多错误**,而不必等待错误在生产环境中向最终用户展示,然后尝试调试问题所在。 ✨ diff --git a/docs/zh/docs/advanced/middleware.md b/docs/zh/docs/advanced/middleware.md new file mode 100644 index 0000000000000..06232fe17b490 --- /dev/null +++ b/docs/zh/docs/advanced/middleware.md @@ -0,0 +1,100 @@ +# 高级中间件 + +用户指南介绍了如何为应用添加[自定义中间件](../tutorial/middleware.md){.internal-link target=_blank} 。 + +以及如何[使用 `CORSMiddleware` 处理 CORS](../tutorial/cors.md){.internal-link target=_blank}。 + +本章学习如何使用其它中间件。 + +## 添加 ASGI 中间件 + +因为 **FastAPI** 基于 Starlette,且执行 ASGI 规范,所以可以使用任意 ASGI 中间件。 + +中间件不必是专为 FastAPI 或 Starlette 定制的,只要遵循 ASGI 规范即可。 + +总之,ASGI 中间件是类,并把 ASGI 应用作为第一个参数。 + +因此,有些第三方 ASGI 中间件的文档推荐以如下方式使用中间件: + +```Python +from unicorn import UnicornMiddleware + +app = SomeASGIApp() + +new_app = UnicornMiddleware(app, some_config="rainbow") +``` + +但 FastAPI(实际上是 Starlette)提供了一种更简单的方式,能让内部中间件在处理服务器错误的同时,还能让自定义异常处理器正常运作。 + +为此,要使用 `app.add_middleware()` (与 CORS 中的示例一样)。 + +```Python +from fastapi import FastAPI +from unicorn import UnicornMiddleware + +app = FastAPI() + +app.add_middleware(UnicornMiddleware, some_config="rainbow") +``` + +`app.add_middleware()` 的第一个参数是中间件的类,其它参数则是要传递给中间件的参数。 + +## 集成中间件 + +**FastAPI** 为常见用例提供了一些中间件,下面介绍怎么使用这些中间件。 + +!!! note "技术细节" + + 以下几个示例中也可以使用 `from starlette.middleware.something import SomethingMiddleware`。 + + **FastAPI** 在 `fastapi.middleware` 中提供的中间件只是为了方便开发者使用,但绝大多数可用的中间件都直接继承自 Starlette。 + +## `HTTPSRedirectMiddleware` + +强制所有传入请求必须是 `https` 或 `wss`。 + +任何传向 `http` 或 `ws` 的请求都会被重定向至安全方案。 + +```Python hl_lines="2 6" +{!../../../docs_src/advanced_middleware/tutorial001.py!} +``` + +## `TrustedHostMiddleware` + +强制所有传入请求都必须正确设置 `Host` 请求头,以防 HTTP 主机头攻击。 + +```Python hl_lines="2 6-8" +{!../../../docs_src/advanced_middleware/tutorial002.py!} +``` + +支持以下参数: + +* `allowed_hosts` - 允许的域名(主机名)列表。`*.example.com` 等通配符域名可以匹配子域名,或使用 `allowed_hosts=["*"]` 允许任意主机名,或省略中间件。 + +如果传入的请求没有通过验证,则发送 `400` 响应。 + +## `GZipMiddleware` + +处理 `Accept-Encoding` 请求头中包含 `gzip` 请求的 GZip 响应。 + +中间件会处理标准响应与流响应。 + +```Python hl_lines="2 6" +{!../../../docs_src/advanced_middleware/tutorial003.py!} +``` + +支持以下参数: + +* `minimum_size` - 小于最小字节的响应不使用 GZip。 默认值是 `500`。 + +## 其它中间件 + +除了上述中间件外,FastAPI 还支持其它ASGI 中间件。 + +例如: + +* Sentry +* Uvicorn 的 `ProxyHeadersMiddleware` +* MessagePack + +其它可用中间件详见 Starlette 官档 -  中间件ASGI Awesome 列表。 diff --git a/docs/zh/docs/advanced/openapi-callbacks.md b/docs/zh/docs/advanced/openapi-callbacks.md new file mode 100644 index 0000000000000..e2dadbfb0d3bd --- /dev/null +++ b/docs/zh/docs/advanced/openapi-callbacks.md @@ -0,0 +1,184 @@ +# OpenAPI 回调 + +您可以创建触发外部 API 请求的*路径操作* API,这个外部 API 可以是别人创建的,也可以是由您自己创建的。 + +API 应用调用外部 API 时的流程叫做**回调**。因为外部开发者编写的软件发送请求至您的 API,然后您的 API 要进行回调,并把请求发送至外部 API。 + +此时,我们需要存档外部 API 的*信息*,比如应该有哪些*路径操作*,返回什么样的请求体,应该返回哪种响应等。 + +## 使用回调的应用 + +示例如下。 + +假设要开发一个创建发票的应用。 + +发票包括 `id`、`title`(可选)、`customer`、`total` 等属性。 + +API 的用户 (外部开发者)要在您的 API 内使用 POST 请求创建一条发票记录。 + +(假设)您的 API 将: + +* 把发票发送至外部开发者的消费者 +* 归集现金 +* 把通知发送至 API 的用户(外部开发者) + * 通过(从您的 API)发送 POST 请求至外部 API (即**回调**)来完成 + +## 常规 **FastAPI** 应用 + +添加回调前,首先看下常规 API 应用是什么样子。 + +常规 API 应用包含接收 `Invoice` 请求体的*路径操作*,还有包含回调 URL 的查询参数 `callback_url`。 + +这部分代码很常规,您对绝大多数代码应该都比较熟悉了: + +```Python hl_lines="10-14 37-54" +{!../../../docs_src/openapi_callbacks/tutorial001.py!} +``` + +!!! tip "提示" + + `callback_url` 查询参数使用 Pydantic 的 URL 类型。 + +此处唯一比较新的内容是*路径操作装饰器*中的 `callbacks=invoices_callback_router.routes` 参数,下文介绍。 + +## 存档回调 + +实际的回调代码高度依赖于您自己的 API 应用。 + +并且可能每个应用都各不相同。 + +回调代码可能只有一两行,比如: + +```Python +callback_url = "https://example.com/api/v1/invoices/events/" +requests.post(callback_url, json={"description": "Invoice paid", "paid": True}) +``` + +但回调最重要的部分可能是,根据 API 要发送给回调请求体的数据等内容,确保您的 API 用户(外部开发者)正确地实现*外部 API*。 + +因此,我们下一步要做的就是添加代码,为从 API 接收回调的*外部 API*存档。 + +这部分文档在 `/docs` 下的 Swagger API 文档中显示,并且会告诉外部开发者如何构建*外部 API*。 + +本例没有实现回调本身(只是一行代码),只有文档部分。 + +!!! tip "提示" + + 实际的回调只是 HTTP 请求。 + + 实现回调时,要使用 HTTPXRequests。 + +## 编写回调文档代码 + +应用不执行这部分代码,只是用它来*记录 外部 API* 。 + +但,您已经知道用 **FastAPI** 创建自动 API 文档有多简单了。 + +我们要使用与存档*外部 API* 相同的知识……通过创建外部 API 要实现的*路径操作*(您的 API 要调用的)。 + +!!! tip "提示" + + 编写存档回调的代码时,假设您是*外部开发者*可能会用的上。并且您当前正在实现的是*外部 API*,不是*您自己的 API*。 + + 临时改变(为外部开发者的)视角能让您更清楚该如何放置*外部 API* 响应和请求体的参数与 Pydantic 模型等。 + +### 创建回调的 `APIRouter` + +首先,新建包含一些用于回调的 `APIRouter`。 + +```Python hl_lines="5 26" +{!../../../docs_src/openapi_callbacks/tutorial001.py!} +``` + +### 创建回调*路径操作* + +创建回调*路径操作*也使用之前创建的 `APIRouter`。 + +它看起来和常规 FastAPI *路径操作*差不多: + +* 声明要接收的请求体,例如,`body: InvoiceEvent` +* 还要声明要返回的响应,例如,`response_model=InvoiceEventReceived` + +```Python hl_lines="17-19 22-23 29-33" +{!../../../docs_src/openapi_callbacks/tutorial001.py!} +``` + +回调*路径操作*与常规*路径操作*有两点主要区别: + +* 它不需要任何实际的代码,因为应用不会调用这段代码。它只是用于存档*外部 API*。因此,函数的内容只需要 `pass` 就可以了 +* *路径*可以包含 OpenAPI 3 表达式(详见下文),可以使用带参数的变量,以及发送至您的 API 的原始请求的部分 + +### 回调路径表达式 + +回调*路径*支持包含发送给您的 API 的原始请求的部分的 OpenAPI 3 表达式。 + +本例中是**字符串**: + +```Python +"{$callback_url}/invoices/{$request.body.id}" +``` + +因此,如果您的 API 用户(外部开发者)发送请求到您的 API: + +``` +https://yourapi.com/invoices/?callback_url=https://www.external.org/events +``` + +使用如下 JSON 请求体: + +```JSON +{ + "id": "2expen51ve", + "customer": "Mr. Richie Rich", + "total": "9999" +} +``` + +然后,您的 API 就会处理发票,并在某个点之后,发送回调请求至 `callback_url`(外部 API): + +``` +https://www.external.org/events/invoices/2expen51ve +``` + +JSON 请求体包含如下内容: + +```JSON +{ + "description": "Payment celebration", + "paid": true +} +``` + +它会预期*外部 API* 的响应包含如下 JSON 请求体: + +```JSON +{ + "ok": true +} +``` + +!!! tip "提示" + + 注意,回调 URL包含 `callback_url` (`https://www.external.org/events`)中的查询参数,还有 JSON 请求体内部的发票 ID(`2expen51ve`)。 + +### 添加回调路由 + +至此,在上文创建的回调路由里就包含了*回调路径操作*(外部开发者要在外部 API 中实现)。 + +现在使用 API *路径操作装饰器*的参数 `callbacks`,从回调路由传递属性 `.routes`(实际上只是路由/路径操作的**列表**): + +```Python hl_lines="36" +{!../../../docs_src/openapi_callbacks/tutorial001.py!} +``` + +!!! tip "提示" + + 注意,不能把路由本身(`invoices_callback_router`)传递给 `callback=`,要传递 `invoices_callback_router.routes` 中的 `.routes` 属性。 + +### 查看文档 + +现在,使用 Uvicorn 启动应用,打开 http://127.0.0.1:8000/docs。 + +就能看到文档的*路径操作*已经包含了**回调**的内容以及*外部 API*: + + diff --git a/docs/zh/docs/advanced/security/http-basic-auth.md b/docs/zh/docs/advanced/security/http-basic-auth.md new file mode 100644 index 0000000000000..1f251ca452667 --- /dev/null +++ b/docs/zh/docs/advanced/security/http-basic-auth.md @@ -0,0 +1,107 @@ +# HTTP 基础授权 + +最简单的用例是使用 HTTP 基础授权(HTTP Basic Auth)。 + +在 HTTP 基础授权中,应用需要请求头包含用户名与密码。 + +如果没有接收到 HTTP 基础授权,就返回 HTTP 401 `"Unauthorized"` 错误。 + +并返回含 `Basic` 值的请求头 `WWW-Authenticate`以及可选的 `realm` 参数。 + +HTTP 基础授权让浏览器显示内置的用户名与密码提示。 + +输入用户名与密码后,浏览器会把它们自动发送至请求头。 + +## 简单的 HTTP 基础授权 + +* 导入 `HTTPBsic` 与 `HTTPBasicCredentials` +* 使用 `HTTPBsic` 创建**安全概图** +* 在*路径操作*的依赖项中使用 `security` +* 返回类型为 `HTTPBasicCredentials` 的对象: + * 包含发送的 `username` 与 `password` + +```Python hl_lines="2 6 10" +{!../../../docs_src/security/tutorial006.py!} +``` + +第一次打开 URL(或在 API 文档中点击 **Execute** 按钮)时,浏览器要求输入用户名与密码: + + + +## 检查用户名 + +以下是更完整的示例。 + +使用依赖项检查用户名与密码是否正确。 + +为此要使用 Python 标准模块 `secrets` 检查用户名与密码: + +```Python hl_lines="1 11-13" +{!../../../docs_src/security/tutorial007.py!} +``` + +这段代码确保 `credentials.username` 是 `"stanleyjobson"`,且 `credentials.password` 是`"swordfish"`。与以下代码类似: + +```Python +if not (credentials.username == "stanleyjobson") or not (credentials.password == "swordfish"): + # Return some error + ... +``` + +但使用 `secrets.compare_digest()`,可以防御**时差攻击**,更加安全。 + +### 时差攻击 + +什么是**时差攻击**? + +假设攻击者试图猜出用户名与密码。 + +他们发送用户名为 `johndoe`,密码为 `love123` 的请求。 + +然后,Python 代码执行如下操作: + +```Python +if "johndoe" == "stanleyjobson" and "love123" == "swordfish": + ... +``` + +但就在 Python 比较完 `johndoe` 的第一个字母 `j` 与 `stanleyjobson` 的 `s` 时,Python 就已经知道这两个字符串不相同了,它会这么想,**没必要浪费更多时间执行剩余字母的对比计算了**。应用立刻就会返回**错误的用户或密码**。 + +但接下来,攻击者继续尝试 `stanleyjobsox` 和 密码 `love123`。 + +应用代码会执行类似下面的操作: + +```Python +if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish": + ... +``` + +此时,Python 要对比 `stanleyjobsox` 与 `stanleyjobson` 中的 `stanleyjobso`,才能知道这两个字符串不一样。因此会多花费几微秒来返回**错误的用户或密码**。 + +#### 反应时间对攻击者的帮助 + +通过服务器花费了更多微秒才发送**错误的用户或密码**响应,攻击者会知道猜对了一些内容,起码开头字母是正确的。 + +然后,他们就可以放弃 `johndoe`,再用类似 `stanleyjobsox` 的内容进行尝试。 + +#### **专业**攻击 + +当然,攻击者不用手动操作,而是编写每秒能执行成千上万次测试的攻击程序,每次都会找到更多正确字符。 + +但是,在您的应用的**帮助**下,攻击者利用时间差,就能在几分钟或几小时内,以这种方式猜出正确的用户名和密码。 + +#### 使用 `secrets.compare_digest()` 修补 + +在此,代码中使用了 `secrets.compare_digest()`。 + +简单的说,它使用相同的时间对比 `stanleyjobsox` 和 `stanleyjobson`,还有 `johndoe` 和 `stanleyjobson`。对比密码时也一样。 + +在代码中使用 `secrets.compare_digest()` ,就可以安全地防御全面攻击了。 + +### 返回错误 + +检测到凭证不正确后,返回 `HTTPException` 及状态码 401(与无凭证时返回的内容一样),并添加请求头 `WWW-Authenticate`,让浏览器再次显示登录提示: + +```Python hl_lines="15-19" +{!../../../docs_src/security/tutorial007.py!} +``` diff --git a/docs/zh/docs/advanced/security/oauth2-scopes.md b/docs/zh/docs/advanced/security/oauth2-scopes.md new file mode 100644 index 0000000000000..e5eeffb0a4f8b --- /dev/null +++ b/docs/zh/docs/advanced/security/oauth2-scopes.md @@ -0,0 +1,276 @@ +# OAuth2 作用域 + +**FastAPI** 无缝集成 OAuth2 作用域(`Scopes`),可以直接使用。 + +作用域是更精密的权限系统,遵循 OAuth2 标准,与 OpenAPI 应用(和 API 自动文档)集成。 + +OAuth2 也是脸书、谷歌、GitHub、微软、推特等第三方身份验证应用使用的机制。这些身份验证应用在用户登录应用时使用 OAuth2 提供指定权限。 + +脸书、谷歌、GitHub、微软、推特就是 OAuth2 作用域登录。 + +本章介绍如何在 **FastAPI** 应用中使用 OAuth2 作用域管理验证与授权。 + +!!! warning "警告" + + 本章内容较难,刚接触 FastAPI 的新手可以跳过。 + + OAuth2 作用域不是必需的,没有它,您也可以处理身份验证与授权。 + + 但 OAuth2 作用域与 API(通过 OpenAPI)及 API 文档集成地更好。 + + 不管怎么说,**FastAPI** 支持在代码中使用作用域或其它安全/授权需求项。 + + 很多情况下,OAuth2 作用域就像一把牛刀。 + + 但如果您确定要使用作用域,或对它有兴趣,请继续阅读。 + +## OAuth2 作用域与 OpenAPI + +OAuth2 规范的**作用域**是由空格分割的字符串组成的列表。 + +这些字符串支持任何格式,但不能包含空格。 + +作用域表示的是**权限**。 + +OpenAPI 中(例如 API 文档)可以定义**安全方案**。 + +这些安全方案在使用 OAuth2 时,还可以声明和使用作用域。 + +**作用域**只是(不带空格的)字符串。 + +常用于声明特定安全权限,例如: + +* 常见用例为,`users:read` 或 `users:write` +* 脸书和 Instagram 使用 `instagram_basic` +* 谷歌使用 `https://www.googleapis.com/auth/drive` + +!!! info "说明" + + OAuth2 中,**作用域**只是声明特定权限的字符串。 + + 是否使用冒号 `:` 等符号,或是不是 URL 并不重要。 + + 这些细节只是特定的实现方式。 + + 对 OAuth2 来说,它们都只是字符串而已。 + +## 全局纵览 + +首先,快速浏览一下以下代码与**用户指南**中 [OAuth2 实现密码哈希与 Bearer JWT 令牌验证](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank}一章中代码的区别。以下代码使用 OAuth2 作用域: + +```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 153" +{!../../../docs_src/security/tutorial005.py!} +``` + +下面,我们逐步说明修改的代码内容。 + +## OAuth2 安全方案 + +第一个修改的地方是,使用两个作用域 `me` 和 `items ` 声明 OAuth2 安全方案。 + +`scopes` 参数接收**字典**,键是作用域、值是作用域的描述: + +```Python hl_lines="62-65" +{!../../../docs_src/security/tutorial005.py!} +``` + +因为声明了作用域,所以登录或授权时会在 API 文档中显示。 + +此处,选择给予访问权限的作用域: `me` 和 `items`。 + +这也是使用脸书、谷歌、GitHub 登录时的授权机制。 + + + +## JWT 令牌作用域 + +现在,修改令牌*路径操作*,返回请求的作用域。 + +此处仍然使用 `OAuth2PasswordRequestForm`。它包含类型为**字符串列表**的 `scopes` 属性,且`scopes` 属性中包含要在请求里接收的每个作用域。 + +这样,返回的 JWT 令牌中就包含了作用域。 + +!!! danger "危险" + + 为了简明起见,本例把接收的作用域直接添加到了令牌里。 + + 但在您的应用中,为了安全,应该只把作用域添加到确实需要作用域的用户,或预定义的用户。 + +```Python hl_lines="153" +{!../../../docs_src/security/tutorial005.py!} +``` + +## 在*路径操作*与依赖项中声明作用域 + +接下来,为*路径操作* `/users/me/items/` 声明作用域 `items`。 + +为此,要从 `fastapi` 中导入并使用 `Security` 。 + +`Security` 声明依赖项的方式和 `Depends` 一样,但 `Security` 还能接收作用域(字符串)列表类型的参数 `scopes`。 + +此处使用与 `Depends` 相同的方式,把依赖项函数 `get_current_active_user` 传递给 `Security`。 + +同时,还传递了作用域**列表**,本例中只传递了一个作用域:`items`(此处支持传递更多作用域)。 + +依赖项函数 `get_current_active_user` 还能声明子依赖项,不仅可以使用 `Depends`,也可以使用 `Security`。声明子依赖项函数(`get_current_user`)及更多作用域。 + +本例要求使用作用域 `me`(还可以使用更多作用域)。 + +!!! note "笔记" + + 不必在不同位置添加不同的作用域。 + + 本例使用的这种方式只是为了展示 **FastAPI** 如何处理在不同层级声明的作用域。 + +```Python hl_lines="4 139 166" +{!../../../docs_src/security/tutorial005.py!} +``` + +!!! info "技术细节" + + `Security` 实际上是 `Depends` 的子类,而且只比 `Depends` 多一个参数。 + + 但使用 `Security` 代替 `Depends`,**FastAPI** 可以声明安全作用域,并在内部使用这些作用域,同时,使用 OpenAPI 存档 API。 + + 但实际上,从 `fastapi` 导入的 `Query`、`Path`、`Depends`、`Security` 等对象,只是返回特殊类的函数。 + +## 使用 `SecurityScopes` + +修改依赖项 `get_current_user`。 + +这是上面的依赖项使用的依赖项。 + +这里使用的也是之前创建的 OAuth2 方案,并把它声明为依赖项:`oauth2_scheme`。 + +该依赖项函数本身不需要作用域,因此,可以使用 `Depends` 和 `oauth2_scheme`。不需要指定安全作用域时,不必使用 `Security`。 + +此处还声明了从 `fastapin.security` 导入的 `SecurityScopes` 类型的特殊参数。 + +`SecuriScopes` 类与 `Request` 类似(`Request` 用于直接提取请求对象)。 + +```Python hl_lines="8 105" +{!../../../docs_src/security/tutorial005.py!} +``` + +## 使用 `scopes` + +参数 `security_scopes` 的类型是 `SecurityScopes`。 + +它的属性 `scopes` 是作用域列表,所有依赖项都把它作为子依赖项。也就是说所有**依赖**……这听起来有些绕,后文会有解释。 + +(类 `SecurityScopes` 的)`security_scopes` 对象还提供了单字符串类型的属性 `scope_str`,该属性是(要在本例中使用的)用空格分割的作用域。 + +此处还创建了后续代码中要复用(`raise`)的 `HTTPException` 。 + +该异常包含了作用域所需的(如有),以空格分割的字符串(使用 `scope_str`)。该字符串要放到包含作用域的 `WWW-Authenticate` 请求头中(这也是规范的要求)。 + +```Python hl_lines="105 107-115" +{!../../../docs_src/security/tutorial005.py!} +``` + +## 校验 `username` 与数据形状 + +我们可以校验是否获取了 `username`,并抽取作用域。 + +然后,使用 Pydantic 模型校验数据(捕获 `ValidationError` 异常),如果读取 JWT 令牌或使用 Pydantic 模型验证数据时出错,就会触发之前创建的 `HTTPException` 异常。 + +对此,要使用新的属性 `scopes` 更新 Pydantic 模型 `TokenData`。 + +使用 Pydantic 验证数据可以确保数据中含有由作用域组成的**字符串列表**,以及 `username` 字符串等内容。 + +反之,如果使用**字典**或其它数据结构,就有可能在后面某些位置破坏应用,形成安全隐患。 + +还可以使用用户名验证用户,如果没有用户,也会触发之前创建的异常。 + +```Python hl_lines="46 116-127" +{!../../../docs_src/security/tutorial005.py!} +``` + +## 校验 `scopes` + +接下来,校验所有依赖项和依赖要素(包括*路径操作*)所需的作用域。这些作用域包含在令牌的 `scopes` 里,如果不在其中就会触发 `HTTPException` 异常。 + +为此,要使用包含所有作用域**字符串列表**的 `security_scopes.scopes`, 。 + +```Python hl_lines="128-134" +{!../../../docs_src/security/tutorial005.py!} +``` + +## 依赖项树与作用域 + +再次查看这个依赖项树与作用域。 + +`get_current_active_user` 依赖项包含子依赖项 `get_current_user`,并在 `get_current_active_user`中声明了作用域 `"me"` 包含所需作用域列表 ,在 `security_scopes.scopes` 中传递给 `get_current_user`。 + +*路径操作*自身也声明了作用域,`"items"`,这也是 `security_scopes.scopes` 列表传递给 `get_current_user` 的。 + +依赖项与作用域的层级架构如下: + +* *路径操作* `read_own_items` 包含: + * 依赖项所需的作用域 `["items"]`: + * `get_current_active_user`: + * 依赖项函数 `get_current_active_user` 包含: + * 所需的作用域 `"me"` 包含依赖项: + * `get_current_user`: + * 依赖项函数 `get_current_user` 包含: + * 没有作用域需求其自身 + * 依赖项使用 `oauth2_scheme` + * `security_scopes` 参数的类型是 `SecurityScopes`: + * `security_scopes` 参数的属性 `scopes` 是包含上述声明的所有作用域的**列表**,因此: + * `security_scopes.scopes` 包含用于*路径操作*的 `["me", "items"]` + * `security_scopes.scopes` 包含*路径操作* `read_users_me` 的 `["me"]`,因为它在依赖项里被声明 + * `security_scopes.scopes` 包含用于*路径操作* `read_system_status` 的 `[]`(空列表),并且它的依赖项 `get_current_user` 也没有声明任何 `scope` + +!!! tip "提示" + + 此处重要且**神奇**的事情是,`get_current_user` 检查每个*路径操作*时可以使用不同的 `scopes` 列表。 + + 所有这些都依赖于在每个*路径操作*和指定*路径操作*的依赖树中的每个依赖项。 + +## `SecurityScopes` 的更多细节 + +您可以任何位置或多个位置使用 `SecurityScopes`,不一定非得在**根**依赖项中使用。 + +它总是在当前 `Security` 依赖项中和所有依赖因子对于**特定** *路径操作*和**特定**依赖树中安全作用域 + +因为 `SecurityScopes` 包含所有由依赖项声明的作用域,可以在核心依赖函数中用它验证所需作用域的令牌,然后再在不同的*路径操作*中声明不同作用域需求。 + +它们会为每个*路径操作*进行单独检查。 + +## 查看文档 + +打开 API 文档,进行身份验证,并指定要授权的作用域。 + + + +没有选择任何作用域,也可以进行**身份验证**,但访问 `/uses/me` 或 `/users/me/items` 时,会显示没有足够的权限。但仍可以访问 `/status/`。 + +如果选择了作用域 `me`,但没有选择作用域 `items`,则可以访问 `/users/me/`,但不能访问 `/users/me/items`。 + +这就是通过用户提供的令牌使用第三方应用访问这些*路径操作*时会发生的情况,具体怎样取决于用户授予第三方应用的权限。 + +## 关于第三方集成 + +本例使用 OAuth2 **密码**流。 + +这种方式适用于登录我们自己的应用,最好使用我们自己的前端。 + +因为我们能控制自己的前端应用,可以信任它接收 `username` 与 `password`。 + +但如果构建的是连接其它应用的 OAuth2 应用,比如具有与脸书、谷歌、GitHub 相同功能的第三方身份验证应用。那您就应该使用其它安全流。 + +最常用的是隐式流。 + +最安全的是代码流,但实现起来更复杂,而且需要更多步骤。因为它更复杂,很多第三方身份验证应用最终建议使用隐式流。 + +!!! note "笔记" + + 每个身份验证应用都会采用不同方式会命名流,以便融合入自己的品牌。 + + 但归根结底,它们使用的都是 OAuth2 标准。 + +**FastAPI** 的 `fastapi.security.oauth2` 里包含了所有 OAuth2 身份验证流工具。 + +## 装饰器 `dependencies` 中的 `Security` + +同样,您可以在装饰器的 `dependencies` 参数中定义 `Depends` 列表,(详见[路径操作装饰器依赖项](../../tutorial/dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank})),也可以把 `scopes` 与 `Security` 一起使用。 diff --git a/docs/zh/docs/advanced/settings.md b/docs/zh/docs/advanced/settings.md index 597e99a7793c3..d793b9c7fd1cf 100644 --- a/docs/zh/docs/advanced/settings.md +++ b/docs/zh/docs/advanced/settings.md @@ -127,7 +127,7 @@ Hello World from Python ## Pydantic 的 `Settings` -幸运的是,Pydantic 提供了一个很好的工具来处理来自环境变量的设置,即Pydantic: Settings management。 +幸运的是,Pydantic 提供了一个很好的工具来处理来自环境变量的设置,即Pydantic: Settings management。 ### 创建 `Settings` 对象 @@ -223,13 +223,13 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app {!> ../../../docs_src/settings/app02_an_py39/main.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="6 12-13" {!> ../../../docs_src/settings/app02_an/main.py!} ``` -=== "Python 3.6+ 非注解版本" +=== "Python 3.8+ 非注解版本" !!! tip 如果可能,请尽量使用 `Annotated` 版本。 @@ -239,7 +239,7 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app ``` !!! tip - 我们稍后会讨论 `@lru_cache()`。 + 我们稍后会讨论 `@lru_cache`。 目前,您可以将 `get_settings()` 视为普通函数。 @@ -251,13 +251,13 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app {!> ../../../docs_src/settings/app02_an_py39/main.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="17 19-21" {!> ../../../docs_src/settings/app02_an/main.py!} ``` -=== "Python 3.6+ 非注解版本" +=== "Python 3.8+ 非注解版本" !!! tip 如果可能,请尽量使用 `Annotated` 版本。 @@ -289,7 +289,7 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app 但是,dotenv 文件实际上不一定要具有确切的文件名。 -Pydantic 支持使用外部库从这些类型的文件中读取。您可以在Pydantic 设置: Dotenv (.env) 支持中阅读更多相关信息。 +Pydantic 支持使用外部库从这些类型的文件中读取。您可以在Pydantic 设置: Dotenv (.env) 支持中阅读更多相关信息。 !!! tip 要使其工作,您需要执行 `pip install python-dotenv`。 @@ -314,7 +314,7 @@ APP_NAME="ChimichangApp" 在这里,我们在 Pydantic 的 `Settings` 类中创建了一个名为 `Config` 的类,并将 `env_file` 设置为我们想要使用的 dotenv 文件的文件名。 !!! tip - `Config` 类仅用于 Pydantic 配置。您可以在Pydantic Model Config中阅读更多相关信息。 + `Config` 类仅用于 Pydantic 配置。您可以在Pydantic Model Config中阅读更多相关信息。 ### 使用 `lru_cache` 仅创建一次 `Settings` @@ -337,7 +337,7 @@ def get_settings(): 我们将为每个请求创建该对象,并且将在每个请求中读取 `.env` 文件。 ⚠️ -但是,由于我们在顶部使用了 `@lru_cache()` 装饰器,因此只有在第一次调用它时,才会创建 `Settings` 对象一次。 ✔️ +但是,由于我们在顶部使用了 `@lru_cache` 装饰器,因此只有在第一次调用它时,才会创建 `Settings` 对象一次。 ✔️ === "Python 3.9+" @@ -345,13 +345,13 @@ def get_settings(): {!> ../../../docs_src/settings/app03_an_py39/main.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="1 11" {!> ../../../docs_src/settings/app03_an/main.py!} ``` -=== "Python 3.6+ 非注解版本" +=== "Python 3.8+ 非注解版本" !!! tip 如果可能,请尽量使用 `Annotated` 版本。 @@ -364,13 +364,13 @@ def get_settings(): #### `lru_cache` 技术细节 -`@lru_cache()` 修改了它所装饰的函数,以返回第一次返回的相同值,而不是再次计算它,每次都执行函数的代码。 +`@lru_cache` 修改了它所装饰的函数,以返回第一次返回的相同值,而不是再次计算它,每次都执行函数的代码。 因此,下面的函数将对每个参数组合执行一次。然后,每个参数组合返回的值将在使用完全相同的参数组合调用函数时再次使用。 例如,如果您有一个函数: ```Python -@lru_cache() +@lru_cache def say_hi(name: str, salutation: str = "Ms."): return f"Hello {salutation} {name}" ``` @@ -422,7 +422,7 @@ participant execute as Execute function 这样,它的行为几乎就像是一个全局变量。但是由于它使用了依赖项函数,因此我们可以轻松地进行测试时的覆盖。 -`@lru_cache()` 是 `functools` 的一部分,它是 Python 标准库的一部分,您可以在Python 文档中了解有关 `@lru_cache()` 的更多信息。 +`@lru_cache` 是 `functools` 的一部分,它是 Python 标准库的一部分,您可以在Python 文档中了解有关 `@lru_cache` 的更多信息。 ## 小结 @@ -430,4 +430,4 @@ participant execute as Execute function * 通过使用依赖项,您可以简化测试。 * 您可以使用 `.env` 文件。 -* 使用 `@lru_cache()` 可以避免为每个请求重复读取 dotenv 文件,同时允许您在测试时进行覆盖。 +* 使用 `@lru_cache` 可以避免为每个请求重复读取 dotenv 文件,同时允许您在测试时进行覆盖。 diff --git a/docs/zh/docs/advanced/sub-applications.md b/docs/zh/docs/advanced/sub-applications.md new file mode 100644 index 0000000000000..55651def53fc1 --- /dev/null +++ b/docs/zh/docs/advanced/sub-applications.md @@ -0,0 +1,73 @@ +# 子应用 - 挂载 + +如果需要两个独立的 FastAPI 应用,拥有各自独立的 OpenAPI 与文档,则需设置一个主应用,并**挂载**一个(或多个)子应用。 + +## 挂载 **FastAPI** 应用 + +**挂载**是指在特定路径中添加完全**独立**的应用,然后在该路径下使用*路径操作*声明的子应用处理所有事务。 + +### 顶层应用 + +首先,创建主(顶层)**FastAPI** 应用及其*路径操作*: + +```Python hl_lines="3 6-8" +{!../../../docs_src/sub_applications/tutorial001.py!} +``` + +### 子应用 + +接下来,创建子应用及其*路径操作*。 + +子应用只是另一个标准 FastAPI 应用,但这个应用是被**挂载**的应用: + +```Python hl_lines="11 14-16" +{!../../../docs_src/sub_applications/tutorial001.py!} +``` + +### 挂载子应用 + +在顶层应用 `app` 中,挂载子应用 `subapi`。 + +本例的子应用挂载在 `/subapi` 路径下: + +```Python hl_lines="11 19" +{!../../../docs_src/sub_applications/tutorial001.py!} +``` + +### 查看文档 + +如果主文件是 `main.py`,则用以下 `uvicorn` 命令运行主应用: + +
+ +```console +$ uvicorn main:app --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +查看文档 http://127.0.0.1:8000/docs。 + +下图显示的是主应用 API 文档,只包括其自有的*路径操作*。 + + + +然后查看子应用文档 http://127.0.0.1:8000/subapi/docs。 + +下图显示的是子应用的 API 文档,也是只包括其自有的*路径操作*,所有这些路径操作都在 `/subapi` 子路径前缀下。 + + + +两个用户界面都可以正常运行,因为浏览器能够与每个指定的应用或子应用会话。 + +### 技术细节:`root_path` + +以上述方式挂载子应用时,FastAPI 使用 ASGI 规范中的 `root_path` 机制处理挂载子应用路径之间的通信。 + +这样,子应用就可以为自动文档使用路径前缀。 + +并且子应用还可以再挂载子应用,一切都会正常运行,FastAPI 可以自动处理所有 `root_path`。 + +关于 `root_path` 及如何显式使用 `root_path` 的内容,详见[使用代理](./behind-a-proxy.md){.internal-link target=_blank}一章。 diff --git a/docs/zh/docs/advanced/templates.md b/docs/zh/docs/advanced/templates.md new file mode 100644 index 0000000000000..d735f16976f5d --- /dev/null +++ b/docs/zh/docs/advanced/templates.md @@ -0,0 +1,94 @@ +# 模板 + +**FastAPI** 支持多种模板引擎。 + +Flask 等工具使用的 Jinja2 是最用的模板引擎。 + +在 Starlette 的支持下,**FastAPI** 应用可以直接使用工具轻易地配置 Jinja2。 + +## 安装依赖项 + +安装 `jinja2`: + +
+ +```console +$ pip install jinja2 + +---> 100% +``` + +
+ +如需使用静态文件,还要安装 `aiofiles`: + +
+ +```console +$ pip install aiofiles + +---> 100% +``` + +
+ +## 使用 `Jinja2Templates` + +* 导入 `Jinja2Templates` +* 创建可复用的 `templates` 对象 +* 在返回模板的*路径操作*中声明 `Request` 参数 +* 使用 `templates` 渲染并返回 `TemplateResponse`, 以键值对方式在 Jinja2 的 **context** 中传递 `request` + +```Python hl_lines="4 11 15-16" +{!../../../docs_src/templates/tutorial001.py!} +``` + +!!! note "笔记" + + 注意,必须为 Jinja2 以键值对方式在上下文中传递 `request`。因此,还要在*路径操作*中声明。 + +!!! tip "提示" + + 通过声明 `response_class=HTMLResponse`,API 文档就能识别响应的对象是 HTML。 + +!!! note "技术细节" + + 您还可以使用 `from starlette.templating import Jinja2Templates`。 + + **FastAPI** 的 `fastapi.templating` 只是为开发者提供的快捷方式。实际上,绝大多数可用响应都直接继承自 Starlette。 `Request` 与 `StaticFiles` 也一样。 + +## 编写模板 + +编写模板 `templates/item.html`,代码如下: + +```jinja hl_lines="7" +{!../../../docs_src/templates/templates/item.html!} +``` + +它会显示从 **context** 字典中提取的 `id`: + +```Python +{"request": request, "id": id} +``` + +## 模板与静态文件 + +在模板内部使用 `url_for()`,例如,与挂载的 `StaticFiles` 一起使用。 + +```jinja hl_lines="4" +{!../../../docs_src/templates/templates/item.html!} +``` + +本例中,使用 `url_for()` 为模板添加 CSS 文件 `static/styles.css` 链接: + +```CSS hl_lines="4" +{!../../../docs_src/templates/static/styles.css!} +``` + +因为使用了 `StaticFiles`, **FastAPI** 应用自动提供位于 URL `/static/styles.css` + +的 CSS 文件。 + +## 更多说明 + +包括测试模板等更多详情,请参阅 Starlette 官档 - 模板。 diff --git a/docs/zh/docs/advanced/testing-database.md b/docs/zh/docs/advanced/testing-database.md new file mode 100644 index 0000000000000..8dc95c25f48c2 --- /dev/null +++ b/docs/zh/docs/advanced/testing-database.md @@ -0,0 +1,97 @@ +# 测试数据库 + +您还可以使用[测试依赖项](testing-dependencies.md){.internal-link target=_blank}中的覆盖依赖项方法变更测试的数据库。 + +实现设置其它测试数据库、在测试后回滚数据、或预填测试数据等操作。 + +本章的主要思路与上一章完全相同。 + +## 为 SQL 应用添加测试 + +为了使用测试数据库,我们要升级 [SQL 关系型数据库](../tutorial/sql-databases.md){.internal-link target=_blank} 一章中的示例。 + +应用的所有代码都一样,直接查看那一章的示例代码即可。 + +本章只是新添加了测试文件。 + +正常的依赖项 `get_db()` 返回数据库会话。 + +测试时使用覆盖依赖项返回自定义数据库会话代替正常的依赖项。 + +本例中,要创建仅用于测试的临时数据库。 + +## 文件架构 + +创建新文件 `sql_app/tests/test_sql_app.py`。 + +因此,新的文件架构如下: + +``` hl_lines="9-11" +. +└── sql_app + ├── __init__.py + ├── crud.py + ├── database.py + ├── main.py + ├── models.py + ├── schemas.py + └── tests + ├── __init__.py + └── test_sql_app.py +``` + +## 创建新的数据库会话 + +首先,为新建数据库创建新的数据库会话。 + +测试时,使用 `test.db` 替代 `sql_app.db`。 + +但其余的会话代码基本上都是一样的,只要复制就可以了。 + +```Python hl_lines="8-13" +{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} +``` + +!!! tip "提示" + + 为减少代码重复,最好把这段代码写成函数,在 `database.py` 与 `tests/test_sql_app.py`中使用。 + + 为了把注意力集中在测试代码上,本例只是复制了这段代码。 + +## 创建数据库 + +因为现在是想在新文件中使用新数据库,所以要使用以下代码创建数据库: + +```Python +Base.metadata.create_all(bind=engine) +``` + +一般是在 `main.py` 中调用这行代码,但在 `main.py` 里,这行代码用于创建 `sql_app.db`,但是现在要为测试创建 `test.db`。 + +因此,要在测试代码中添加这行代码创建新的数据库文件。 + +```Python hl_lines="16" +{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} +``` + +## 覆盖依赖项 + +接下来,创建覆盖依赖项,并为应用添加覆盖内容。 + +```Python hl_lines="19-24 27" +{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} +``` + +!!! tip "提示" + + `overrider_get_db()` 与 `get_db` 的代码几乎完全一样,只是 `overrider_get_db` 中使用测试数据库的 `TestingSessionLocal`。 + +## 测试应用 + +然后,就可以正常测试了。 + +```Python hl_lines="32-47" +{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} +``` + +测试期间,所有在数据库中所做的修改都在 `test.db` 里,不会影响主应用的 `sql_app.db`。 diff --git a/docs/zh/docs/advanced/testing-dependencies.md b/docs/zh/docs/advanced/testing-dependencies.md new file mode 100644 index 0000000000000..dc0f88b33141d --- /dev/null +++ b/docs/zh/docs/advanced/testing-dependencies.md @@ -0,0 +1,51 @@ +# 测试依赖项 + +## 测试时覆盖依赖项 + +有些场景下,您可能需要在测试时覆盖依赖项。 + +即不希望运行原有依赖项(及其子依赖项)。 + +反之,要在测试期间(或只是为某些特定测试)提供只用于测试的依赖项,并使用此依赖项的值替换原有依赖项的值。 + +### 用例:外部服务 + +常见实例是调用外部第三方身份验证应用。 + +向第三方应用发送令牌,然后返回经验证的用户。 + +但第三方服务商处理每次请求都可能会收费,并且耗时通常也比调用写死的模拟测试用户更长。 + +一般只要测试一次外部验证应用就够了,不必每次测试都去调用。 + +此时,最好覆盖调用外部验证应用的依赖项,使用返回模拟测试用户的自定义依赖项就可以了。 + +### 使用 `app.dependency_overrides` 属性 + +对于这些用例,**FastAPI** 应用支持 `app.dependcy_overrides` 属性,该属性就是**字典**。 + +要在测试时覆盖原有依赖项,这个字典的键应当是原依赖项(函数),值是覆盖依赖项(另一个函数)。 + +这样一来,**FastAPI** 就会调用覆盖依赖项,不再调用原依赖项。 + +```Python hl_lines="26-27 30" +{!../../../docs_src/dependency_testing/tutorial001.py!} +``` + +!!! tip "提示" + + **FastAPI** 应用中的任何位置都可以实现覆盖依赖项。 + + 原依赖项可用于*路径操作函数*、*路径操作装饰器*(不需要返回值时)、`.include_router()` 调用等。 + + FastAPI 可以覆盖这些位置的依赖项。 + +然后,使用 `app.dependency_overrides` 把覆盖依赖项重置为空**字典**: + +```Python +app.dependency_overrides = {} +``` + +!!! tip "提示" + + 如果只在某些测试时覆盖依赖项,您可以在测试开始时(在测试函数内)设置覆盖依赖项,并在结束时(在测试函数结尾)重置覆盖依赖项。 diff --git a/docs/zh/docs/advanced/testing-events.md b/docs/zh/docs/advanced/testing-events.md new file mode 100644 index 0000000000000..222a67c8cffe5 --- /dev/null +++ b/docs/zh/docs/advanced/testing-events.md @@ -0,0 +1,7 @@ +# 测试事件:启动 - 关闭 + +使用 `TestClient` 和 `with` 语句,在测试中运行事件处理器(`startup` 与 `shutdown`)。 + +```Python hl_lines="9-12 20-24" +{!../../../docs_src/app_testing/tutorial003.py!} +``` diff --git a/docs/zh/docs/advanced/testing-websockets.md b/docs/zh/docs/advanced/testing-websockets.md new file mode 100644 index 0000000000000..f303e1d67c96d --- /dev/null +++ b/docs/zh/docs/advanced/testing-websockets.md @@ -0,0 +1,13 @@ +# 测试 WebSockets + +测试 WebSockets 也使用 `TestClient`。 + +为此,要在 `with` 语句中使用 `TestClient` 连接 WebSocket。 + +```Python hl_lines="27-31" +{!../../../docs_src/app_testing/tutorial002.py!} +``` + +!!! note "笔记" + + 更多细节详见 Starlette 官档 - 测试 WebSockets。 diff --git a/docs/zh/docs/advanced/using-request-directly.md b/docs/zh/docs/advanced/using-request-directly.md new file mode 100644 index 0000000000000..1842c2e270f17 --- /dev/null +++ b/docs/zh/docs/advanced/using-request-directly.md @@ -0,0 +1,54 @@ +# 直接使用请求 + +至此,我们已经使用多种类型声明了请求的各种组件。 + +并从以下对象中提取数据: + +* 路径参数 +* 请求头 +* Cookies +* 等 + +**FastAPI** 使用这种方式验证数据、转换数据,并自动生成 API 文档。 + +但有时,我们也需要直接访问 `Request` 对象。 + +## `Request` 对象的细节 + +实际上,**FastAPI** 的底层是 **Starlette**,**FastAPI** 只不过是在 **Starlette** 顶层提供了一些工具,所以能直接使用 Starlette 的 `Request` 对象。 + +但直接从 `Request` 对象提取数据时(例如,读取请求体),**FastAPI** 不会验证、转换和存档数据(为 API 文档使用 OpenAPI)。 + +不过,仍可以验证、转换与注释(使用 Pydantic 模型的请求体等)其它正常声明的参数。 + +但在某些特定情况下,还是需要提取 `Request` 对象。 + +## 直接使用 `Request` 对象 + +假设要在*路径操作函数*中获取客户端 IP 地址和主机。 + +此时,需要直接访问请求。 + +```Python hl_lines="1 7-8" +{!../../../docs_src/using_request_directly/tutorial001.py!} +``` + +把*路径操作函数*的参数类型声明为 `Request`,**FastAPI** 就能把 `Request` 传递到参数里。 + +!!! tip "提示" + + 注意,本例除了声明请求参数之外,还声明了路径参数。 + + 因此,能够提取、验证路径参数、并转换为指定类型,还可以用 OpenAPI 注释。 + + 同样,您也可以正常声明其它参数,而且还可以提取 `Request`。 + +## `Request` 文档 + +更多细节详见 Starlette 官档 - `Request` 对象。 + +!!! note "技术细节" + + 您也可以使用 `from starlette.requests import Request`。 + + **FastAPI** 的 `from fastapi import Request` 只是为开发者提供的快捷方式,但其实它直接继承自 Starlette。 diff --git a/docs/zh/docs/advanced/websockets.md b/docs/zh/docs/advanced/websockets.md index a723487fdfcb4..a5cbdd96516c4 100644 --- a/docs/zh/docs/advanced/websockets.md +++ b/docs/zh/docs/advanced/websockets.md @@ -118,7 +118,7 @@ $ uvicorn main:app --reload {!> ../../../docs_src/websockets/tutorial002_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="69-70 83" {!> ../../../docs_src/websockets/tutorial002_an.py!} @@ -133,7 +133,7 @@ $ uvicorn main:app --reload {!> ../../../docs_src/websockets/tutorial002_py310.py!} ``` -=== "Python 3.6+ 非带注解版本" +=== "Python 3.8+ 非带注解版本" !!! tip 如果可能,请尽量使用 `Annotated` 版本。 @@ -181,7 +181,7 @@ $ uvicorn main:app --reload {!> ../../../docs_src/websockets/tutorial003_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="81-83" {!> ../../../docs_src/websockets/tutorial003.py!} diff --git a/docs/zh/docs/async.md b/docs/zh/docs/async.md new file mode 100644 index 0000000000000..59eebd04914c6 --- /dev/null +++ b/docs/zh/docs/async.md @@ -0,0 +1,430 @@ +# 并发 async / await + +有关路径操作函数的 `async def` 语法以及异步代码、并发和并行的一些背景知识。 + +## 赶时间吗? + +TL;DR: + +如果你正在使用第三方库,它们会告诉你使用 `await` 关键字来调用它们,就像这样: + +```Python +results = await some_library() +``` + +然后,通过 `async def` 声明你的 *路径操作函数*: + +```Python hl_lines="2" +@app.get('/') +async def read_results(): + results = await some_library() + return results +``` + +!!! note + 你只能在被 `async def` 创建的函数内使用 `await` + +--- + +如果你正在使用一个第三方库和某些组件(比如:数据库、API、文件系统...)进行通信,第三方库又不支持使用 `await` (目前大多数数据库三方库都是这样),这种情况你可以像平常那样使用 `def` 声明一个路径操作函数,就像这样: + +```Python hl_lines="2" +@app.get('/') +def results(): + results = some_library() + return results +``` + +--- + +如果你的应用程序不需要与其他任何东西通信而等待其响应,请使用 `async def`。 + +--- + +如果你不清楚,使用 `def` 就好. + +--- + +**注意**:你可以根据需要在路径操作函数中混合使用 `def` 和 `async def`,并使用最适合你的方式去定义每个函数。FastAPI 将为他们做正确的事情。 + +无论如何,在上述任何情况下,FastAPI 仍将异步工作,速度也非常快。 + +但是,通过遵循上述步骤,它将能够进行一些性能优化。 + +## 技术细节 + +Python 的现代版本支持通过一种叫**"协程"**——使用 `async` 和 `await` 语法的东西来写**”异步代码“**。 + +让我们在下面的部分中逐一介绍: + +* **异步代码** +* **`async` 和 `await`** +* **协程** + +## 异步代码 + +异步代码仅仅意味着编程语言 💬 有办法告诉计算机/程序 🤖 在代码中的某个点,它 🤖 将不得不等待在某些地方完成一些事情。让我们假设一些事情被称为 "慢文件"📝. + +所以,在等待"慢文件"📝完成的这段时间,计算机可以做一些其他工作。 + +然后计算机/程序 🤖 每次有机会都会回来,因为它又在等待,或者它 🤖 完成了当前所有的工作。而且它 🤖 将查看它等待的所有任务中是否有已经完成的,做它必须做的任何事情。 + +接下来,它 🤖 完成第一个任务(比如是我们的"慢文件"📝) 并继续与之相关的一切。 + +这个"等待其他事情"通常指的是一些相对较慢(与处理器和 RAM 存储器的速度相比)的 I/O 操作,比如说: + +* 通过网络发送来自客户端的数据 +* 客户端接收来自网络中的数据 +* 磁盘中要由系统读取并提供给程序的文件的内容 +* 程序提供给系统的要写入磁盘的内容 +* 一个 API 的远程调用 +* 一个数据库操作,直到完成 +* 一个数据库查询,直到返回结果 +* 等等. + +这个执行的时间大多是在等待 I/O 操作,因此它们被叫做 "I/O 密集型" 操作。 + +它被称为"异步"的原因是因为计算机/程序不必与慢任务"同步",去等待任务完成的确切时刻,而在此期间不做任何事情直到能够获取任务结果才继续工作。 + +相反,作为一个"异步"系统,一旦完成,任务就可以排队等待一段时间(几微秒),等待计算机程序完成它要做的任何事情,然后回来获取结果并继续处理它们。 + +对于"同步"(与"异步"相反),他们通常也使用"顺序"一词,因为计算机程序在切换到另一个任务之前是按顺序执行所有步骤,即使这些步骤涉及到等待。 + +### 并发与汉堡 + +上述异步代码的思想有时也被称为“并发”,它不同于“并行”。 + +并发和并行都与“不同的事情或多或少同时发生”有关。 + +但是并发和并行之间的细节是完全不同的。 + +要了解差异,请想象以下关于汉堡的故事: + +### 并发汉堡 + +你和你的恋人一起去快餐店,你排队在后面,收银员从你前面的人接单。😍 + + + +然后轮到你了,你为你的恋人和你选了两个非常豪华的汉堡。🍔🍔 + + + +收银员对厨房里的厨师说了一些话,让他们知道他们必须为你准备汉堡(尽管他们目前正在为之前的顾客准备汉堡)。 + + + +你付钱了。 💸 + +收银员给你轮到的号码。 + + + +当你在等待的时候,你和你的恋人一起去挑选一张桌子,然后你们坐下来聊了很长时间(因为汉堡很豪华,需要一些时间来准备)。 + +当你和你的恋人坐在桌子旁,等待汉堡的时候,你可以用这段时间来欣赏你的恋人是多么的棒、可爱和聪明✨😍✨。 + + + +在等待中和你的恋人交谈时,你会不时地查看柜台上显示的号码,看看是否已经轮到你了。 + +然后在某个时刻,终于轮到你了。你去柜台拿汉堡然后回到桌子上。 + + + +你们享用了汉堡,整个过程都很开心。✨ + + + +!!! info + 漂亮的插画来自 Ketrina Thompson. 🎨 + +--- + +在那个故事里,假设你是计算机程序 🤖 。 + +当你在排队时,你只是闲着😴, 轮到你前不做任何事情(仅排队)。但排队很快,因为收银员只接订单(不准备订单),所以这一切都还好。 + +然后,当轮到你时,需要你做一些实际性的工作,比如查看菜单,决定你想要什么,让你的恋人选择,支付,检查你是否提供了正确的账单或卡,检查你的收费是否正确,检查订单是否有正确的项目,等等。 + +此时,即使你仍然没有汉堡,你和收银员的工作也"暂停"了⏸, 因为你必须等待一段时间 🕙 让你的汉堡做好。 + +但是,当你离开柜台并坐在桌子旁,在轮到你的号码前的这段时间,你可以将焦点切换到 🔀 你的恋人上,并做一些"工作"⏯ 🤓。你可以做一些非常"有成效"的事情,比如和你的恋人调情😍. + +之后,收银员 💁 把号码显示在显示屏上,并说到 "汉堡做好了",而当显示的号码是你的号码时,你不会立刻疯狂地跳起来。因为你知道没有人会偷你的汉堡,因为你有你的号码,而其他人又有他们自己的号码。 + +所以你要等待你的恋人完成故事(完成当前的工作⏯ /正在做的事🤓), 轻轻微笑,说你要吃汉堡⏸. + +然后你去柜台🔀, 到现在初始任务已经完成⏯, 拿起汉堡,说声谢谢,然后把它们送到桌上。这就完成了与计数器交互的步骤/任务⏹. 这反过来又产生了一项新任务,即"吃汉堡"🔀 ⏯, 上一个"拿汉堡"的任务已经结束了⏹. + +### 并行汉堡 + +现在让我们假设不是"并发汉堡",而是"并行汉堡"。 + +你和你的恋人一起去吃并行快餐。 + +你站在队伍中,同时是厨师的几个收银员(比方说8个)从前面的人那里接单。 + +你之前的每个人都在等待他们的汉堡准备好后才离开柜台,因为8名收银员都会在下一份订单前马上准备好汉堡。 + + + +然后,终于轮到你了,你为你的恋人和你订购了两个非常精美的汉堡。 + +你付钱了 💸。 + + + +收银员去厨房。 + +你站在柜台前 🕙等待着,这样就不会有人在你之前抢走你的汉堡,因为没有轮流的号码。 + + + +当你和你的恋人忙于不让任何人出现在你面前,并且在他们到来的时候拿走你的汉堡时,你无法关注到你的恋人。😞 + +这是"同步"的工作,你被迫与服务员/厨师 👨‍🍳"同步"。你在此必须等待 🕙 ,在收银员/厨师 👨‍🍳 完成汉堡并将它们交给你的确切时间到达之前一直等待,否则其他人可能会拿走它们。 + + + +你经过长时间的等待 🕙 ,收银员/厨师 👨‍🍳终于带着汉堡回到了柜台。 + + + +你拿着汉堡,和你的情人一起上桌。 + +你们仅仅是吃了它们,就结束了。⏹ + + + +没有太多的交谈或调情,因为大部分时间 🕙 都在柜台前等待😞。 + +!!! info + 漂亮的插画来自 Ketrina Thompson. 🎨 + +--- + +在这个并行汉堡的场景中,你是一个计算机程序 🤖 且有两个处理器(你和你的恋人),都在等待 🕙 ,并投入他们的注意力 ⏯ 在柜台上等待了很长一段时间。 + +这家快餐店有 8 个处理器(收银员/厨师)。而并发汉堡店可能只有 2 个(一个收银员和一个厨师)。 + +但最终的体验仍然不是最好的。😞 + +--- + +这将是与汉堡的类似故事。🍔 + +一种更"贴近生活"的例子,想象一家银行。 + +直到最近,大多数银行都有多个出纳员 👨‍💼👨‍💼👨‍💼👨‍💼 还有一条长长排队队伍🕙🕙🕙🕙🕙🕙🕙🕙。 + +所有收银员都是一个接一个的在客户面前做完所有的工作👨‍💼⏯. + +你必须经过 🕙 较长时间排队,否则你就没机会了。 + +你可不会想带你的恋人 😍 和你一起去银行办事🏦. + +### 汉堡结论 + +在"你与恋人一起吃汉堡"的这个场景中,因为有很多人在等待🕙, 使用并发系统更有意义⏸🔀⏯. + +大多数 Web 应用都是这样的。 + +你的服务器正在等待很多很多用户通过他们不太好的网络发送来的请求。 + +然后再次等待 🕙 响应回来。 + +这个"等待" 🕙 是以微秒为单位测量的,但总的来说,最后还是等待很久。 + +这就是为什么使用异步对于 Web API 很有意义的原因 ⏸🔀⏯。 + +这种异步机制正是 NodeJS 受到欢迎的原因(尽管 NodeJS 不是并行的),以及 Go 作为编程语言的优势所在。 + +这与 **FastAPI** 的性能水平相同。 + +您可以同时拥有并行性和异步性,您可以获得比大多数经过测试的 NodeJS 框架更高的性能,并且与 Go 不相上下, Go 是一种更接近于 C 的编译语言(全部归功于 Starlette)。 + +### 并发比并行好吗? + +不!这不是故事的本意。 + +并发不同于并行。而是在需要大量等待的特定场景下效果更好。因此,在 Web 应用程序开发中,它通常比并行要好得多,但这并不意味着全部。 + +因此,为了平衡这一点,想象一下下面的短篇故事: + +> 你必须打扫一个又大又脏的房子。 + +*是的,这就是完整的故事。* + +--- + +在任何地方, 都不需要等待 🕙 ,只需要在房子的多个地方做着很多工作。 + +你可以像汉堡的例子那样轮流执行,先是客厅,然后是厨房,但因为你不需要等待 🕙 ,对于任何事情都是清洁,清洁,还是清洁,轮流不会影响任何事情。 + +无论是否轮流执行(并发),都需要相同的时间来完成,而你也会完成相同的工作量。 + +但在这种情况下,如果你能带上 8 名前收银员/厨师,现在是清洁工一起清扫,他们中的每一个人(加上你)都能占据房子的一个区域来清扫,你就可以在额外的帮助下并行的更快地完成所有工作。 + +在这个场景中,每个清洁工(包括您)都将是一个处理器,完成这个工作的一部分。 + +由于大多数执行时间是由实际工作(而不是等待)占用的,并且计算机中的工作是由 CPU 完成的,所以他们称这些问题为"CPU 密集型"。 + +--- + +CPU 密集型操作的常见示例是需要复杂的数学处理。 + +例如: + +* **音频**或**图像**处理; +* **计算机视觉**: 一幅图像由数百万像素组成,每个像素有3种颜色值,处理通常需要同时对这些像素进行计算; +* **机器学习**: 它通常需要大量的"矩阵"和"向量"乘法。想象一个包含数字的巨大电子表格,并同时将所有数字相乘; +* **深度学习**: 这是机器学习的一个子领域,同样适用。只是没有一个数字的电子表格可以相乘,而是一个庞大的数字集合,在很多情况下,你需要使用一个特殊的处理器来构建和使用这些模型。 + +### 并发 + 并行: Web + 机器学习 + +使用 **FastAPI**,您可以利用 Web 开发中常见的并发机制的优势(NodeJS 的主要吸引力)。 + +并且,您也可以利用并行和多进程(让多个进程并行运行)的优点来处理与机器学习系统中类似的 **CPU 密集型** 工作。 + +这一点,再加上 Python 是**数据科学**、机器学习(尤其是深度学习)的主要语言这一简单事实,使得 **FastAPI** 与数据科学/机器学习 Web API 和应用程序(以及其他许多应用程序)非常匹配。 + +了解如何在生产环境中实现这种并行性,可查看此文 [Deployment](deployment/index.md){.internal-link target=_blank}。 + +## `async` 和 `await` + +现代版本的 Python 有一种非常直观的方式来定义异步代码。这使它看起来就像正常的"顺序"代码,并在适当的时候"等待"。 + +当有一个操作需要等待才能给出结果,且支持这个新的 Python 特性时,您可以编写如下代码: + +```Python +burgers = await get_burgers(2) +``` + +这里的关键是 `await`。它告诉 Python 它必须等待 ⏸ `get_burgers(2)` 完成它的工作 🕙 ,然后将结果存储在 `burgers` 中。这样,Python 就会知道此时它可以去做其他事情 🔀 ⏯ (比如接收另一个请求)。 + +要使 `await` 工作,它必须位于支持这种异步机制的函数内。因此,只需使用 `async def` 声明它: + +```Python hl_lines="1" +async def get_burgers(number: int): + # Do some asynchronous stuff to create the burgers + return burgers +``` + +...而不是 `def`: + +```Python hl_lines="2" +# This is not asynchronous +def get_sequential_burgers(number: int): + # Do some sequential stuff to create the burgers + return burgers +``` + +使用 `async def`,Python 就知道在该函数中,它将遇上 `await`,并且它可以"暂停" ⏸ 执行该函数,直至执行其他操作 🔀 后回来。 + +当你想调用一个 `async def` 函数时,你必须"等待"它。因此,这不会起作用: + +```Python +# This won't work, because get_burgers was defined with: async def +burgers = get_burgers(2) +``` + +--- + +因此,如果您使用的库告诉您可以使用 `await` 调用它,则需要使用 `async def` 创建路径操作函数 ,如: + +```Python hl_lines="2-3" +@app.get('/burgers') +async def read_burgers(): + burgers = await get_burgers(2) + return burgers +``` + +### 更多技术细节 + +您可能已经注意到,`await` 只能在 `async def` 定义的函数内部使用。 + +但与此同时,必须"等待"通过 `async def` 定义的函数。因此,带 `async def` 的函数也只能在 `async def` 定义的函数内部调用。 + +那么,这关于先有鸡还是先有蛋的问题,如何调用第一个 `async` 函数? + +如果您使用 **FastAPI**,你不必担心这一点,因为"第一个"函数将是你的路径操作函数,FastAPI 将知道如何做正确的事情。 + +但如果您想在没有 FastAPI 的情况下使用 `async` / `await`,则可以这样做。 + +### 编写自己的异步代码 + +Starlette (和 **FastAPI**) 是基于 AnyIO 实现的,这使得它们可以兼容 Python 的标准库 asyncioTrio。 + +特别是,你可以直接使用 AnyIO 来处理高级的并发用例,这些用例需要在自己的代码中使用更高级的模式。 + +即使您没有使用 **FastAPI**,您也可以使用 AnyIO 编写自己的异步程序,使其拥有较高的兼容性并获得一些好处(例如, 结构化并发)。 + +### 其他形式的异步代码 + +这种使用 `async` 和 `await` 的风格在语言中相对较新。 + +但它使处理异步代码变得容易很多。 + +这种相同的语法(或几乎相同)最近也包含在现代版本的 JavaScript 中(在浏览器和 NodeJS 中)。 + +但在此之前,处理异步代码非常复杂和困难。 + +在以前版本的 Python,你可以使用多线程或者 Gevent。但代码的理解、调试和思考都要复杂许多。 + +在以前版本的 NodeJS / 浏览器 JavaScript 中,你会使用"回调",因此也可能导致回调地狱。 + +## 协程 + +**协程**只是 `async def` 函数返回的一个非常奇特的东西的称呼。Python 知道它有点像一个函数,它可以启动,也会在某个时刻结束,而且它可能会在内部暂停 ⏸ ,只要内部有一个 `await`。 + +通过使用 `async` 和 `await` 的异步代码的所有功能大多数被概括为"协程"。它可以与 Go 的主要关键特性 "Goroutines" 相媲美。 + +## 结论 + +让我们再来回顾下上文所说的: + +> Python 的现代版本可以通过使用 `async` 和 `await` 语法创建**协程**,并用于支持**异步代码**。 + +现在应该能明白其含义了。✨ + +所有这些使得 FastAPI(通过 Starlette)如此强大,也是它拥有如此令人印象深刻的性能的原因。 + +## 非常技术性的细节 + +!!! warning + 你可以跳过这里。 + + 这些都是 FastAPI 如何在内部工作的技术细节。 + + 如果您有相当多的技术知识(协程、线程、阻塞等),并且对 FastAPI 如何处理 `async def` 与常规 `def` 感到好奇,请继续。 + +### 路径操作函数 + +当你使用 `def` 而不是 `async def` 来声明一个*路径操作函数*时,它运行在外部的线程池中并等待其结果,而不是直接调用(因为它会阻塞服务器)。 + +如果您使用过另一个不以上述方式工作的异步框架,并且您习惯于用普通的 `def` 定义普通的仅计算路径操作函数,以获得微小的性能增益(大约100纳秒),请注意,在 FastAPI 中,效果将完全相反。在这些情况下,最好使用 `async def`,除非路径操作函数内使用执行阻塞 I/O 的代码。 + +在这两种情况下,与您之前的框架相比,**FastAPI** 可能[仍然很快](/#performance){.internal-link target=_blank}。 + +### 依赖 + +这同样适用于[依赖](./tutorial/dependencies/index.md){.internal-link target=_blank}。如果一个依赖是标准的 `def` 函数而不是 `async def`,它将被运行在外部线程池中。 + +### 子依赖 + +你可以拥有多个相互依赖的依赖以及[子依赖](./tutorial/dependencies/sub-dependencies.md){.internal-link target=_blank} (作为函数的参数),它们中的一些可能是通过 `async def` 声明,也可能是通过 `def` 声明。它们仍然可以正常工作,这些通过 `def` 声明的函数将会在外部线程中调用(来自线程池),而不是"被等待"。 + +### 其他函数 + +您可直接调用通过 `def` 或 `async def` 创建的任何其他函数,FastAPI 不会影响您调用它们的方式。 + +这与 FastAPI 为您调用*路径操作函数*和依赖项的逻辑相反。 + +如果你的函数是通过 `def` 声明的,它将被直接调用(在代码中编写的地方),而不会在线程池中,如果这个函数通过 `async def` 声明,当在代码中调用时,你就应该使用 `await` 等待函数的结果。 + +--- + +再次提醒,这些是非常技术性的细节,如果你来搜索它可能对你有用。 + +否则,您最好应该遵守的指导原则赶时间吗?. diff --git a/docs/zh/docs/contributing.md b/docs/zh/docs/contributing.md index 4ebd673150b25..3dfc3db7ceabb 100644 --- a/docs/zh/docs/contributing.md +++ b/docs/zh/docs/contributing.md @@ -1,6 +1,6 @@ # 开发 - 贡献 -首先,你最好先了解 [帮助 FastAPI 及获取帮助](help-fastapi.md){.internal-link target=_blank}的基本方式。 +首先,你可能想了解 [帮助 FastAPI 及获取帮助](help-fastapi.md){.internal-link target=_blank}的基本方式。 ## 开发 @@ -84,6 +84,17 @@ $ python -m venv env 如果显示 `pip` 程序文件位于 `env/bin/pip` 则说明激活成功。 🎉 +确保虚拟环境中的 pip 版本是最新的,以避免后续步骤出现错误: + +
+ +```console +$ python -m pip install --upgrade pip + +---> 100% +``` + +
!!! tip 每一次你在该环境下使用 `pip` 安装了新软件包时,请再次激活该环境。 @@ -114,6 +125,11 @@ $ pip install -r requirements.txt 这样,你不必再去重新"安装"你的本地版本即可测试所有更改。 +!!! note "技术细节" + 仅当你使用此项目中的 `requirements.txt` 安装而不是直接使用 `pip install fastapi` 安装时,才会发生这种情况。 + + 这是因为在 `requirements.txt` 中,本地的 FastAPI 是使用“可编辑” (`-e`)选项安装的 + ### 格式化 你可以运行下面的脚本来格式化和清理所有代码: @@ -126,91 +142,93 @@ $ bash scripts/format.sh
-它还会自动对所有导入代码进行整理。 +它还会自动对所有导入代码进行排序整理。 为了使整理正确进行,你需要在当前环境中安装本地的 FastAPI,即在运行上述段落中的命令时添加 `-e`。 -### 格式化导入 +## 文档 + +首先,请确保按上述步骤设置好环境,这将安装所有需要的依赖。 -还有另一个脚本可以格式化所有导入,并确保你没有未使用的导入代码: +### 实时文档 + +在本地开发时,可以使用该脚本构建站点并检查所做的任何更改,并实时重载:
```console -$ bash scripts/format-imports.sh +$ python ./scripts/docs.py live + +[INFO] Serving on http://127.0.0.1:8008 +[INFO] Start watching changes +[INFO] Start detecting changes ```
-由于它依次运行了多个命令,并修改和还原了许多文件,所以运行时间会更长一些,因此经常地使用 `scripts/format.sh` 然后仅在提交前执行 `scripts/format-imports.sh` 会更好一些。 +文档服务将运行在 `http://127.0.0.1:8008`。 -## 文档 - -首先,请确保按上述步骤设置好环境,这将安装所有需要的依赖。 - -文档使用 MkDocs 生成。 - -并且在 `./scripts/docs.py` 中还有适用的额外工具/脚本来处理翻译。 +这样,你可以编辑文档 / 源文件并实时查看更改。 !!! tip - 你不需要去了解 `./scripts/docs.py` 中的代码,只需在命令行中使用它即可。 + 或者你也可以手动执行和该脚本一样的操作 -所有文档均在 `./docs/en/` 目录中以 Markdown 文件格式保存。 - -许多的教程章节里包含有代码块。 + 进入语言目录,如果是英文文档,目录则是 `docs/en/`: -在大多数情况下,这些代码块是可以直接运行的真实完整的应用程序。 - -实际上,这些代码块不是写在 Markdown 文件内的,它们是位于 `./docs_src/` 目录中的 Python 文件。 + ```console + $ cd docs/en/ + ``` -生成站点时,这些 Python 文件会被包含/注入到文档中。 + 在该目录执行 `mkdocs` 命令 -### 用于测试的文档 + ```console + $ mkdocs serve --dev-addr 8008 + ``` -大多数的测试实际上都是针对文档中的示例源文件运行的。 +#### Typer CLI (可选) -这有助于确保: +本指引向你展示了如何直接用 `python` 运行 `./scripts/docs.py` 中的脚本。 -* 文档始终是最新的。 -* 文档示例可以直接运行。 -* 绝大多数特性既在文档中得以阐述,又通过测试覆盖进行保障。 +但你也可以使用 Typer CLI,而且在安装了补全功能后,你将可以在终端中对命令进行自动补全。 -在本地开发期间,有一个脚本可以实时重载地构建站点并用来检查所做的任何更改: +如果你已经安装 Typer CLI ,则可以使用以下命令安装自动补全功能:
```console -$ python ./scripts/docs.py live +$ typer --install-completion -[INFO] Serving on http://127.0.0.1:8008 -[INFO] Start watching changes -[INFO] Start detecting changes +zsh completion installed in /home/user/.bashrc. +Completion will take effect once you restart the terminal. ```
-它将在 `http://127.0.0.1:8008` 提供对文档的访问。 +### 文档架构 -这样,你可以编辑文档/源文件并实时查看更改。 +文档使用 MkDocs 生成。 -#### Typer CLI (可选) +在 `./scripts/docs.py` 中还有额外工具 / 脚本来处理翻译。 -本指引向你展示了如何直接用 `python` 程序运行 `./scripts/docs.py` 中的脚本。 +!!! tip + 你不需要去了解 `./scripts/docs.py` 中的代码,只需在命令行中使用它即可。 -但你也可以使用 Typer CLI,而且在安装了补全功能后,你将可以在终端中对命令进行自动补全。 +所有文档均在 `./docs/en/` 目录中以 Markdown 文件格式保存。 -如果你打算安装 Typer CLI ,可以使用以下命令安装自动补全功能: +许多的教程中都有一些代码块,大多数情况下,这些代码是可以直接运行的,因为这些代码不是写在 Markdown 文件里的,而是写在 `./docs_src/` 目录中的 Python 文件里。 -
+在生成站点的时候,这些 Python 文件会被打包进文档中。 -```console -$ typer --install-completion +### 测试文档 -zsh completion installed in /home/user/.bashrc. -Completion will take effect once you restart the terminal. -``` +大多数的测试实际上都是针对文档中的示例源文件运行的。 + +这有助于确保: + +* 文档始终是最新的。 +* 文档示例可以直接运行。 +* 绝大多数特性既在文档中得以阐述,又通过测试覆盖进行保障。 -
### 应用和文档同时运行 @@ -230,7 +248,7 @@ $ uvicorn tutorial001:app --reload ### 翻译 -非常感谢你能够参与文档的翻译!这项工作需要社区的帮助才能完成。 🌎 🚀 +**非常感谢**你能够参与文档的翻译!这项工作需要社区的帮助才能完成。 🌎 🚀 以下是参与帮助翻译的步骤。 @@ -243,17 +261,19 @@ $ uvicorn tutorial001:app --reload 详情可查看关于 添加 pull request 评审意见 以同意合并或要求修改的文档。 -* 在 issues 中查找是否有对你所用语言所进行的协作翻译。 +* 检查在 GitHub Discussion 是否有关于你所用语言的协作翻译。 如果有,你可以订阅它,当有一条新的 PR 请求需要评审时,系统会自动将其添加到讨论中,你也会收到对应的推送。 * 每翻译一个页面新增一个 pull request。这将使其他人更容易对其进行评审。 对于我(译注:作者使用西班牙语和英语)不懂的语言,我将在等待其他人评审翻译之后将其合并。 * 你还可以查看是否有你所用语言的翻译,并对其进行评审,这将帮助我了解翻译是否正确以及能否将其合并。 + * 可以在 GitHub Discussions 中查看。 + * 也可以在现有 PR 中通过你使用的语言标签来筛选对应的 PR,举个例子,对于西班牙语,标签是 `lang-es`。 -* 使用相同的 Python 示例并且仅翻译文档中的文本。无需进行任何其他更改示例也能正常工作。 +* 请使用相同的 Python 示例,且只需翻译文档中的文本,不用修改其它东西。 -* 使用相同的图片、文件名以及链接地址。无需进行任何其他调整来让它们兼容。 +* 请使用相同的图片、文件名以及链接地址,不用修改其它东西。 * 你可以从 ISO 639-1 代码列表 表中查找你想要翻译语言的两位字母代码。 @@ -264,7 +284,7 @@ $ uvicorn tutorial001:app --reload 对于西班牙语来说,它的两位字母代码是 `es`。所以西班牙语翻译的目录位于 `docs/es/`。 !!! tip - 主要("官方")语言是英语,位于 `docs/en/`目录。 + 默认语言是英语,位于 `docs/en/`目录。 现在为西班牙语文档运行实时服务器: @@ -281,11 +301,24 @@ $ python ./scripts/docs.py live es
-现在你可以访问 http://127.0.0.1:8008 实时查看你所做的更改。 +!!! tip + 或者你也可以手动执行和该脚本一样的操作 -如果你查看 FastAPI 的线上文档网站,会看到每种语言都有所有页面。但是某些页面并未被翻译并且会有一处关于缺少翻译的提示。 + 进入语言目录,对于西班牙语的翻译,目录是 `docs/es/`: -但是当你像上面这样在本地运行文档时,你只会看到已经翻译的页面。 + ```console + $ cd docs/es/ + ``` + + 在该目录执行 `mkdocs` 命令 + + ```console + $ mkdocs serve --dev-addr 8008 + ``` + +现在你可以访问 http://127.0.0.1:8008 实时查看你所做的更改。 + +如果你查看 FastAPI 的线上文档网站,会看到每种语言都有所有的文档页面,但是某些页面并未被翻译并且会有一处关于缺少翻译的提示。(但是当你像上面这样在本地运行文档时,你只会看到已经翻译的页面。) 现在假设你要为 [Features](features.md){.internal-link target=_blank} 章节添加翻译。 @@ -304,49 +337,9 @@ docs/es/docs/features.md !!! tip 注意路径和文件名的唯一变化是语言代码,从 `en` 更改为 `es`。 -* 现在打开位于英语文档目录下的 MkDocs 配置文件: +回到浏览器你就可以看到刚刚更新的章节了。🎉 -``` -docs/en/docs/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/docs/mkdocs.yml -``` - -* 将其添加到与英语文档完全相同的位置,例如: - -```YAML hl_lines="8" -site_name: FastAPI -# More stuff -nav: -- FastAPI: index.md -- Languages: - - en: / - - es: /es/ -- features.md -``` - -如果配置文件中还有其他条目,请确保你所翻译的新条目和它们之间的顺序与英文版本完全相同。 - -打开浏览器,现在你将看到文档展示了你所加入的新章节。 🎉 - -现在,你可以将它全部翻译完并在保存文件后进行预览。 +现在,你可以翻译这些内容并在保存文件后进行预览。 #### 新语言 @@ -354,7 +347,7 @@ nav: 假设你想要添加克里奥尔语翻译,而且文档中还没有该语言的翻译。 -点击上面提到的链接,可以查到"克里奥尔语"的代码为 `ht`。 +点击上面提到的“ISO 639-1 代码列表”链接,可以查到“克里奥尔语”的代码为 `ht`。 下一步是运行脚本以生成新的翻译目录: @@ -365,55 +358,32 @@ nav: $ python ./scripts/docs.py new-lang ht Successfully initialized: docs/ht -Updating ht -Updating en ```
现在,你可以在编辑器中查看新创建的目录 `docs/ht/`。 -!!! tip - 在添加实际的翻译之前,仅以此创建首个 pull request 来设定新语言的配置。 - - 这样当你在翻译第一个页面时,其他人可以帮助翻译其他页面。🚀 - -首先翻译文档主页 `docs/ht/index.md`。 - -然后,你可以根据上面的"已有语言"的指引继续进行翻译。 +这条命令会生成一个从 `en` 版本继承了所有属性的配置文件 `docs/ht/mkdocs.yml`: -##### 不支持的新语言 - -如果在运行实时服务器脚本时收到关于不支持该语言的错误,类似于: - -``` - raise TemplateNotFound(template) -jinja2.exceptions.TemplateNotFound: partials/language/xx.html +```yaml +INHERIT: ../en/mkdocs.yml ``` -这意味着文档的主题不支持该语言(在这种例子中,编造的语言代码是 `xx`)。 - -但是别担心,你可以将主题语言设置为英语,然后翻译文档的内容。 - -如果你需要这么做,编辑新语言目录下的 `mkdocs.yml`,它将有类似下面的内容: +!!! tip + 你也可以自己手动创建包含这些内容的文件。 -```YAML hl_lines="5" -site_name: FastAPI -# More stuff -theme: - # More stuff - language: xx -``` +这条命令还会生成一个文档主页 `docs/ht/index.md`,你可以从这个文件开始翻译。 -将其中的 language 项从 `xx`(你的语言代码)更改为 `en`。 +然后,你可以根据上面的"已有语言"的指引继续进行翻译。 -然后,你就可以再次启动实时服务器了。 +翻译完成后,你就可以用 `docs/ht/mkdocs.yml` 和 `docs/ht/index.md` 发起 PR 了。🎉 #### 预览结果 -当你通过 `live` 命令使用 `./scripts/docs.py` 中的脚本时,该脚本仅展示当前语言已有的文件和翻译。 +你可以执行 `./scripts/docs.py live` 命令来预览结果(或者 `mkdocs serve`)。 -但是当你完成翻译后,你可以像在线上展示一样测试所有内容。 +但是当你完成翻译后,你可以像在线上展示一样测试所有内容,包括所有其他语言。 为此,首先构建所有文档: @@ -423,19 +393,16 @@ theme: // 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 ```
-这将在 `./docs_build/` 目录中为每一种语言生成全部的文档。还包括添加所有缺少翻译的文件,并带有一条"此文件还没有翻译"的提醒。但是你不需要对该目录执行任何操作。 +这样会对每一种语言构建一个独立的文档站点,并最终把这些站点全部打包输出到 `./site/` 目录。 + -然后,它针对每种语言构建独立的 MkDocs 站点,将它们组合在一起,并在 `./site/` 目录中生成最终的输出。 然后你可以使用命令 `serve` 来运行生成的站点: diff --git a/docs/zh/docs/deployment/cloud.md b/docs/zh/docs/deployment/cloud.md new file mode 100644 index 0000000000000..b086b7b6b8aa0 --- /dev/null +++ b/docs/zh/docs/deployment/cloud.md @@ -0,0 +1,16 @@ +# 在云上部署 FastAPI + +您几乎可以使用**任何云服务商**来部署 FastAPI 应用程序。 + +在大多数情况下,主要的云服务商都有部署 FastAPI 的指南。 + +## 云服务商 - 赞助商 + +一些云服务商 ✨ [**赞助 FastAPI**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨,这确保了FastAPI 及其**生态系统**持续健康地**发展**。 + +这表明了他们对 FastAPI 及其**社区**(您)的真正承诺,因为他们不仅想为您提供**良好的服务**,而且还想确保您拥有一个**良好且健康的框架**:FastAPI。 🙇 + +您可能想尝试他们的服务并阅读他们的指南: + +* Platform.sh +* Porter diff --git a/docs/zh/docs/deployment/concepts.md b/docs/zh/docs/deployment/concepts.md new file mode 100644 index 0000000000000..9c4aaa64b5d6f --- /dev/null +++ b/docs/zh/docs/deployment/concepts.md @@ -0,0 +1,323 @@ +# 部署概念 + +在部署 **FastAPI** 应用程序或任何类型的 Web API 时,有几个概念值得了解,通过掌握这些概念您可以找到**最合适的**方法来**部署您的应用程序**。 + +一些重要的概念是: + +* 安全性 - HTTPS +* 启动时运行 +* 重新启动 +* 复制(运行的进程数) +* 内存 +* 开始前的先前步骤 + +我们接下来了解它们将如何影响**部署**。 + +我们的最终目标是能够以**安全**的方式**为您的 API 客户端**提供服务,同时要**避免中断**,并且尽可能高效地利用**计算资源**( 例如服务器CPU资源)。 🚀 + +我将在这里告诉您更多关于这些**概念**的信息,希望能给您提供**直觉**来决定如何在非常不同的环境中部署 API,甚至在是尚不存在的**未来**的环境里。 + +通过考虑这些概念,您将能够**评估和设计**部署**您自己的 API**的最佳方式。 + +在接下来的章节中,我将为您提供更多部署 FastAPI 应用程序的**具体方法**。 + +但现在,让我们仔细看一下这些重要的**概念**。 这些概念也适用于任何其他类型的 Web API。 💡 + +## 安全性 - HTTPS + +在[上一章有关 HTTPS](./https.md){.internal-link target=_blank} 中,我们了解了 HTTPS 如何为您的 API 提供加密。 + +我们还看到,HTTPS 通常由应用程序服务器的**外部**组件(**TLS 终止代理**)提供。 + +并且必须有某个东西负责**更新 HTTPS 证书**,它可以是相同的组件,也可以是不同的组件。 + + +### HTTPS 示例工具 + +您可以用作 TLS 终止代理的一些工具包括: + +* Traefik + * 自动处理证书更新 ✨ +* Caddy + * 自动处理证书更新 ✨ +* Nginx + * 使用 Certbot 等外部组件进行证书更新 +* HAProxy + * 使用 Certbot 等外部组件进行证书更新 +* 带有 Ingress Controller(如Nginx) 的 Kubernetes + * 使用诸如 cert-manager 之类的外部组件来进行证书更新 +* 由云服务商内部处理,作为其服务的一部分(请阅读下文👇) + +另一种选择是您可以使用**云服务**来完成更多工作,包括设置 HTTPS。 它可能有一些限制或向您收取更多费用等。但在这种情况下,您不必自己设置 TLS 终止代理。 + +我将在接下来的章节中向您展示一些具体示例。 + +--- + +接下来要考虑的概念都是关于运行实际 API 的程序(例如 Uvicorn)。 + +## 程序和进程 + +我们将讨论很多关于正在运行的“**进程**”的内容,因此弄清楚它的含义以及与“**程序**”这个词有什么区别是很有用的。 + +### 什么是程序 + +**程序**这个词通常用来描述很多东西: + +* 您编写的 **代码**,**Python 文件**。 +* 操作系统可以**执行**的**文件**,例如:`python`、`python.exe`或`uvicorn`。 +* 在操作系统上**运行**、使用CPU 并将内容存储在内存上的特定程序。 这也被称为**进程**。 + +### 什么是进程 + +**进程** 这个词通常以更具体的方式使用,仅指在操作系统中运行的东西(如上面的最后一点): + +* 在操作系统上**运行**的特定程序。 + * 这不是指文件,也不是指代码,它**具体**指的是操作系统正在**执行**和管理的东西。 +* 任何程序,任何代码,**只有在执行时才能做事**。 因此,是当有**进程正在运行**时。 +* 该进程可以由您或操作系统**终止**(或“杀死”)。 那时,它停止运行/被执行,并且它可以**不再做事情**。 +* 您计算机上运行的每个应用程序背后都有一些进程,每个正在运行的程序,每个窗口等。并且通常在计算机打开时**同时**运行许多进程。 +* **同一程序**可以有**多个进程**同时运行。 + +如果您检查操作系统中的“任务管理器”或“系统监视器”(或类似工具),您将能够看到许多正在运行的进程。 + +例如,您可能会看到有多个进程运行同一个浏览器程序(Firefox、Chrome、Edge 等)。 他们通常每个tab运行一个进程,再加上一些其他额外的进程。 + + + +--- + +现在我们知道了术语“进程”和“程序”之间的区别,让我们继续讨论部署。 + +## 启动时运行 + +在大多数情况下,当您创建 Web API 时,您希望它**始终运行**、不间断,以便您的客户端始终可以访问它。 这是当然的,除非您有特定原因希望它仅在某些情况下运行,但大多数时候您希望它不断运行并且**可用**。 + +### 在远程服务器中 + +当您设置远程服务器(云服务器、虚拟机等)时,您可以做的最简单的事情就是手动运行 Uvicorn(或类似的),就像本地开发时一样。 + +它将会在**开发过程中**发挥作用并发挥作用。 + +但是,如果您与服务器的连接丢失,**正在运行的进程**可能会终止。 + +如果服务器重新启动(例如更新后或从云提供商迁移后),您可能**不会注意到它**。 因此,您甚至不知道必须手动重新启动该进程。 所以,你的 API 将一直处于挂掉的状态。 😱 + + +### 启动时自动运行 + +一般来说,您可能希望服务器程序(例如 Uvicorn)在服务器启动时自动启动,并且不需要任何**人为干预**,让进程始终与您的 API 一起运行(例如 Uvicorn 运行您的 FastAPI 应用程序) 。 + +### 单独的程序 + +为了实现这一点,您通常会有一个**单独的程序**来确保您的应用程序在启动时运行。 在许多情况下,它还可以确保其他组件或应用程序也运行,例如数据库。 + +### 启动时运行的示例工具 + +可以完成这项工作的工具的一些示例是: + +* Docker +* Kubernetes +* Docker Compose +* Docker in Swarm Mode +* Systemd +* Supervisor +* 作为其服务的一部分由云提供商内部处理 +* 其他的... + +我将在接下来的章节中为您提供更具体的示例。 + + +## 重新启动 + +与确保应用程序在启动时运行类似,您可能还想确保它在挂掉后**重新启动**。 + +### 我们会犯错误 + +作为人类,我们总是会犯**错误**。 软件几乎*总是*在不同的地方隐藏着**bug**。 🐛 + +作为开发人员,当我们发现这些bug并实现新功能(也可能添加新bug😅)时,我们会不断改进代码。 + +### 自动处理小错误 + +使用 FastAPI 构建 Web API 时,如果我们的代码中存在错误,FastAPI 通常会将其包含到触发错误的单个请求中。 🛡 + +对于该请求,客户端将收到 **500 内部服务器错误**,但应用程序将继续处理下一个请求,而不是完全崩溃。 + +### 更大的错误 - 崩溃 + +尽管如此,在某些情况下,我们编写的一些代码可能会导致整个应用程序崩溃,从而导致 Uvicorn 和 Python 崩溃。 💥 + +尽管如此,您可能不希望应用程序因为某个地方出现错误而保持死机状态,您可能希望它**继续运行**,至少对于未破坏的*路径操作*。 + +### 崩溃后重新启动 + +但在那些严重错误导致正在运行的**进程**崩溃的情况下,您需要一个外部组件来负责**重新启动**进程,至少尝试几次...... + +!!! tip + + ...尽管如果整个应用程序只是**立即崩溃**,那么永远重新启动它可能没有意义。 但在这些情况下,您可能会在开发过程中注意到它,或者至少在部署后立即注意到它。 + + 因此,让我们关注主要情况,在**未来**的某些特定情况下,它可能会完全崩溃,但重新启动它仍然有意义。 + +您可能希望让这个东西作为 **外部组件** 负责重新启动您的应用程序,因为到那时,使用 Uvicorn 和 Python 的同一应用程序已经崩溃了,因此同一应用程序的相同代码中没有东西可以对此做出什么。 + +### 自动重新启动的示例工具 + +在大多数情况下,用于**启动时运行程序**的同一工具也用于处理自动**重新启动**。 + +例如,可以通过以下方式处理: + +* Docker +* Kubernetes +* Docker Compose +* Docker in Swarm mode +* Systemd +* Supervisor +* 作为其服务的一部分由云提供商内部处理 +* 其他的... + +## 复制 - 进程和内存 + +对于 FastAPI 应用程序,使用像 Uvicorn 这样的服务器程序,在**一个进程**中运行一次就可以同时为多个客户端提供服务。 + +但在许多情况下,您会希望同时运行多个工作进程。 + +### 多进程 - Workers + +如果您的客户端数量多于单个进程可以处理的数量(例如,如果虚拟机不是太大),并且服务器的 CPU 中有 **多个核心**,那么您可以让 **多个进程** 运行 同时处理同一个应用程序,并在它们之间分发所有请求。 + +当您运行同一 API 程序的**多个进程**时,它们通常称为 **workers**。 + +### 工作进程和端口 + +还记得文档 [About HTTPS](./https.md){.internal-link target=_blank} 中只有一个进程可以侦听服务器中的端口和 IP 地址的一种组合吗? + +现在仍然是对的。 + +因此,为了能够同时拥有**多个进程**,必须有一个**单个进程侦听端口**,然后以某种方式将通信传输到每个工作进程。 + +### 每个进程的内存 + +现在,当程序将内容加载到内存中时,例如,将机器学习模型加载到变量中,或者将大文件的内容加载到变量中,所有这些都会消耗服务器的一点内存 (RAM) 。 + +多个进程通常**不共享任何内存**。 这意味着每个正在运行的进程都有自己的东西、变量和内存。 如果您的代码消耗了大量内存,**每个进程**将消耗等量的内存。 + +### 服务器内存 + +例如,如果您的代码加载 **1 GB 大小**的机器学习模型,则当您使用 API 运行一个进程时,它将至少消耗 1 GB RAM。 如果您启动 **4 个进程**(4 个工作进程),每个进程将消耗 1 GB RAM。 因此,您的 API 总共将消耗 **4 GB RAM**。 + +如果您的远程服务器或虚拟机只有 3 GB RAM,尝试加载超过 4 GB RAM 将导致问题。 🚨 + + +### 多进程 - 一个例子 + +在此示例中,有一个 **Manager Process** 启动并控制两个 **Worker Processes**。 + +该管理器进程可能是监听 IP 中的 **端口** 的进程。 它将所有通信传输到工作进程。 + +这些工作进程将是运行您的应用程序的进程,它们将执行主要计算以接收 **请求** 并返回 **响应**,并且它们将加载您放入 RAM 中的变量中的任何内容。 + + + +当然,除了您的应用程序之外,同一台机器可能还运行**其他进程**。 + +一个有趣的细节是,随着时间的推移,每个进程使用的 **CPU 百分比可能会发生很大变化,但内存 (RAM) 通常会或多或少保持稳定**。 + +如果您有一个每次执行相当数量的计算的 API,并且您有很多客户端,那么 **CPU 利用率** 可能也会保持稳定(而不是不断快速上升和下降)。 + +### 复制工具和策略示例 + +可以通过多种方法来实现这一目标,我将在接下来的章节中向您详细介绍具体策略,例如在谈论 Docker 和容器时。 + +要考虑的主要限制是必须有一个**单个**组件来处理**公共IP**中的**端口**。 然后它必须有一种方法将通信**传输**到复制的**进程/worker**。 + +以下是一些可能的组合和策略: + +* **Gunicorn** 管理 **Uvicorn workers** + * Gunicorn 将是监听 **IP** 和 **端口** 的 **进程管理器**,复制将通过 **多个 Uvicorn 工作进程** 进行 +* **Uvicorn** 管理 **Uvicorn workers** + * 一个 Uvicorn **进程管理器** 将监听 **IP** 和 **端口**,并且它将启动 **多个 Uvicorn 工作进程** +* **Kubernetes** 和其他分布式 **容器系统** + * **Kubernetes** 层中的某些东西将侦听 **IP** 和 **端口**。 复制将通过拥有**多个容器**,每个容器运行**一个 Uvicorn 进程** +* **云服务** 为您处理此问题 + * 云服务可能**为您处理复制**。 它可能会让您定义 **要运行的进程**,或要使用的 **容器映像**,在任何情况下,它很可能是 **单个 Uvicorn 进程**,并且云服务将负责复制它。 + + + +!!! tip + + 如果这些关于 **容器**、Docker 或 Kubernetes 的内容还没有多大意义,请不要担心。 + + 我将在以后的章节中向您详细介绍容器镜像、Docker、Kubernetes 等:[容器中的 FastAPI - Docker](./docker.md){.internal-link target=_blank}。 + +## 启动之前的步骤 + +在很多情况下,您希望在**启动**应用程序之前执行一些步骤。 + +例如,您可能想要运行**数据库迁移**。 + +但在大多数情况下,您只想执行这些步骤**一次**。 + +因此,在启动应用程序之前,您将需要一个**单个进程**来执行这些**前面的步骤**。 + +而且您必须确保它是运行前面步骤的单个进程, *即使*之后您为应用程序本身启动**多个进程**(多个worker)。 如果这些步骤由**多个进程**运行,它们会通过在**并行**运行来**重复**工作,并且如果这些步骤像数据库迁移一样需要小心处理,它们可能会导致每个进程和其他进程发生冲突。 + +当然,也有一些情况,多次运行前面的步骤也没有问题,这样的话就好办多了。 + +!!! tip + + 另外,请记住,根据您的设置,在某些情况下,您在开始应用程序之前**可能甚至不需要任何先前的步骤**。 + + 在这种情况下,您就不必担心这些。 🤷 + + +### 前面步骤策略的示例 + +这将在**很大程度上取决于您部署系统的方式**,并且可能与您启动程序、处理重启等的方式有关。 + +以下是一些可能的想法: + +* Kubernetes 中的“Init Container”在应用程序容器之前运行 +* 一个 bash 脚本,运行前面的步骤,然后启动您的应用程序 + * 您仍然需要一种方法来启动/重新启动 bash 脚本、检测错误等。 + +!!! tip + + 我将在以后的章节中为您提供使用容器执行此操作的更具体示例:[容器中的 FastAPI - Docker](./docker.md){.internal-link target=_blank}。 + +## 资源利用率 + +您的服务器是一个**资源**,您可以通过您的程序消耗或**利用**CPU 上的计算时间以及可用的 RAM 内存。 + +您想要消耗/利用多少系统资源? 您可能很容易认为“不多”,但实际上,您可能希望在不崩溃的情况下**尽可能多地消耗**。 + +如果您支付了 3 台服务器的费用,但只使用了它们的一点点 RAM 和 CPU,那么您可能**浪费金钱** 💸,并且可能 **浪费服务器电力** 🌎,等等。 + +在这种情况下,最好只拥有 2 台服务器并使用更高比例的资源(CPU、内存、磁盘、网络带宽等)。 + +另一方面,如果您有 2 台服务器,并且正在使用 **100% 的 CPU 和 RAM**,则在某些时候,一个进程会要求更多内存,并且服务器将不得不使用磁盘作为“内存” (这可能会慢数千倍),甚至**崩溃**。 或者一个进程可能需要执行一些计算,并且必须等到 CPU 再次空闲。 + +在这种情况下,最好购买**一台额外的服务器**并在其上运行一些进程,以便它们都有**足够的 RAM 和 CPU 时间**。 + +由于某种原因,您的 API 的使用量也有可能出现**激增**。 也许它像病毒一样传播开来,或者也许其他一些服务或机器人开始使用它。 在这些情况下,您可能需要额外的资源来保证安全。 + +您可以将一个**任意数字**设置为目标,例如,资源利用率**在 50% 到 90%** 之间。 重点是,这些可能是您想要衡量和用来调整部署的主要内容。 + +您可以使用“htop”等简单工具来查看服务器中使用的 CPU 和 RAM 或每个进程使用的数量。 或者您可以使用更复杂的监控工具,这些工具可能分布在服务器等上。 + + +## 回顾 + +您在这里阅读了一些在决定如何部署应用程序时可能需要牢记的主要概念: + +* 安全性 - HTTPS +* 启动时运行 +* 重新启动 +* 复制(运行的进程数) +* 内存 +* 开始前的先前步骤 + +了解这些想法以及如何应用它们应该会给您足够的直觉在配置和调整部署时做出任何决定。 🤓 + +在接下来的部分中,我将为您提供更具体的示例,说明您可以遵循的可能策略。 🚀 diff --git a/docs/zh/docs/deployment/deta.md b/docs/zh/docs/deployment/deta.md new file mode 100644 index 0000000000000..a7390f7869229 --- /dev/null +++ b/docs/zh/docs/deployment/deta.md @@ -0,0 +1,244 @@ +# 在 Deta 上部署 FastAPI + +本节介绍如何使用 Deta 免费方案部署 **FastAPI** 应用。🎁 + +部署操作需要大约 10 分钟。 + +!!! info "说明" + + Deta 是 **FastAPI** 的赞助商。 🎉 + +## 基础 **FastAPI** 应用 + +* 创建应用文件夹,例如 `./fastapideta/`,进入文件夹 + +### FastAPI 代码 + +* 创建包含如下代码的 `main.py`: + +```Python +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): + return {"item_id": item_id} +``` + +### 需求项 + +在文件夹里新建包含如下内容的 `requirements.txt` 文件: + +```text +fastapi +``` + +!!! tip "提示" + + 在 Deta 上部署时无需安装 Uvicorn,虽然在本地测试应用时需要安装。 + +### 文件夹架构 + +`./fastapideta/` 文件夹中现在有两个文件: + +``` +. +└── main.py +└── requirements.txt +``` + +## 创建免费 Deta 账号 + +创建免费的 Deta 账号,只需要电子邮件和密码。 + +甚至不需要信用卡。 + +## 安装 CLI + +创建账号后,安装 Deta CLI: + +=== "Linux, macOS" + +
+ + ```console + $ curl -fsSL https://get.deta.dev/cli.sh | sh + ``` + +
+ +=== "Windows PowerShell" + +
+ + ```console + $ iwr https://get.deta.dev/cli.ps1 -useb | iex + ``` + +
+ +安装完 CLI 后,打开新的 Terminal,就能检测到刚安装的 CLI。 + +在新的 Terminal 里,用以下命令确认 CLI 是否正确安装: + +
+ +```console +$ deta --help + +Deta command line interface for managing deta micros. +Complete documentation available at https://docs.deta.sh + +Usage: + deta [flags] + deta [command] + +Available Commands: + auth Change auth settings for a deta micro + +... +``` + +
+ +!!! tip "提示" + + 安装 CLI 遇到问题时,请参阅 Deta 官档。 + +## 使用 CLI 登录 + +现在,使用 CLI 登录 Deta: + +
+ +```console +$ deta login + +Please, log in from the web page. Waiting.. +Logged in successfully. +``` + +
+ +这个命令会打开浏览器并自动验证身份。 + +## 使用 Deta 部署 + +接下来,使用 Deta CLI 部署应用: + +
+ +```console +$ deta new + +Successfully created a new micro + +// Notice the "endpoint" 🔍 + +{ + "name": "fastapideta", + "runtime": "python3.7", + "endpoint": "https://qltnci.deta.dev", + "visor": "enabled", + "http_auth": "enabled" +} + +Adding dependencies... + + +---> 100% + + +Successfully installed fastapi-0.61.1 pydantic-1.7.2 starlette-0.13.6 +``` + +
+ +您会看到如下 JSON 信息: + +```JSON hl_lines="4" +{ + "name": "fastapideta", + "runtime": "python3.7", + "endpoint": "https://qltnci.deta.dev", + "visor": "enabled", + "http_auth": "enabled" +} +``` + +!!! tip "提示" + + 您部署时的 `"endpoint"` URL 可能会有所不同。 + +## 查看效果 + +打开浏览器,跳转到 `endpoint` URL。本例中是 `https://qltnci.deta.dev`,但您的链接可能与此不同。 + +FastAPI 应用会返回如下 JSON 响应: + +```JSON +{ + "Hello": "World" +} +``` + +接下来,跳转到 API 文档 `/docs`,本例中是 `https://qltnci.deta.dev/docs`。 + +文档显示如下: + + + +## 启用公开访问 + +默认情况下,Deta 使用您的账号 Cookies 处理身份验证。 + +应用一切就绪之后,使用如下命令让公众也能看到您的应用: + +
+ +```console +$ deta auth disable + +Successfully disabled http auth +``` + +
+ +现在,就可以把 URL 分享给大家,他们就能访问您的 API 了。🚀 + +## HTTPS + +恭喜!您已经在 Deta 上部署了 FastAPI 应用!🎉 🍰 + +还要注意,Deta 能够正确处理 HTTPS,因此您不必操心 HTTPS,您的客户端肯定能有安全加密的连接。 ✅ 🔒 + +## 查看 Visor + +从 API 文档(URL 是 `https://gltnci.deta.dev/docs`)发送请求至*路径操作* `/items/{item_id}`。 + +例如,ID `5`。 + +现在跳转至 https://web.deta.sh。 + +左边栏有个 "Micros" 标签,里面是所有的应用。 + +还有一个 **Details** 和 **Visor** 标签,跳转到 **Visor** 标签。 + +在这里查看最近发送给应用的请求。 + +您可以编辑或重新使用这些请求。 + + + +## 更多内容 + +如果要持久化保存应用数据,可以使用提供了**免费方案**的 Deta Base。 + +详见 Deta 官档。 diff --git a/docs/zh/docs/deployment/docker.md b/docs/zh/docs/deployment/docker.md new file mode 100644 index 0000000000000..0f8906704128e --- /dev/null +++ b/docs/zh/docs/deployment/docker.md @@ -0,0 +1,728 @@ +# 容器中的 FastAPI - Docker + +部署 FastAPI 应用程序时,常见的方法是构建 **Linux 容器镜像**。 通常使用 **Docker** 完成。 然后,你可以通过几种可能的方式之一部署该容器镜像。 + +使用 Linux 容器有几个优点,包括**安全性**、**可复制性**、**简单性**等。 + +!!! tip + 赶时间并且已经知道这些东西了? 跳转到下面的 [`Dockerfile` 👇](#为-fastapi-构建-docker-镜像)。 + + +
+Dockerfile Preview 👀 + +```Dockerfile +FROM python:3.9 + +WORKDIR /code + +COPY ./requirements.txt /code/requirements.txt + +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt + +COPY ./app /code/app + +CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] + +# If running behind a proxy like Nginx or Traefik add --proxy-headers +# CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80", "--proxy-headers"] +``` + +
+ +## 什么是容器 + +容器(主要是 Linux 容器)是一种非常**轻量级**的打包应用程序的方式,其包括所有依赖项和必要的文件,同时它们可以和同一系统中的其他容器(或者其他应用程序/组件)相互隔离。 + +Linux 容器使用宿主机(如物理服务器、虚拟机、云服务器等)的Linux 内核运行。 这意味着它们非常轻量(与模拟整个操作系统的完整虚拟机相比)。 + +通过这样的方式,容器消耗**很少的资源**,与直接运行进程相当(虚拟机会消耗更多)。 + +容器的进程(通常只有一个)、文件系统和网络都运行在隔离的环境,这简化了部署、安全、开发等。 + +## 什么是容器镜像 + +**容器**是从**容器镜像**运行的。 + +容器镜像是容器中文件、环境变量和默认命令/程序的**静态**版本。 **静态**这里的意思是容器**镜像**还没有运行,只是打包的文件和元数据。 + +与存储静态内容的“**容器镜像**”相反,“**容器**”通常指正在运行的实例,即正在**执行的**。 + +当**容器**启动并运行时(从**容器镜像**启动),它可以创建或更改文件、环境变量等。这些更改将仅存在于该容器中,而不会持久化到底层的容器镜像中(不会保存到磁盘)。 + +容器镜像相当于**程序**和文件,例如 `python`命令 和某些文件 如`main.py`。 + +而**容器**本身(与**容器镜像**相反)是镜像的实际运行实例,相当于**进程**。 事实上,容器仅在有**进程运行**时才运行(通常它只是一个单独的进程)。 当容器中没有进程运行时,容器就会停止。 + + + +## 容器镜像 + +Docker 一直是创建和管理**容器镜像**和**容器**的主要工具之一。 + +还有一个公共 Docker Hub ,其中包含预制的 **官方容器镜像**, 适用于许多工具、环境、数据库和应用程序。 + +例如,有一个官方的 Python 镜像。 + +还有许多其他镜像用于不同的需要(例如数据库),例如: + + +* PostgreSQL +* MySQL +* MongoDB +* Redis, etc. + + +通过使用预制的容器镜像,可以非常轻松地**组合**并使用不同的工具。 例如,尝试一个新的数据库。 在大多数情况下,你可以使用**官方镜像**,只需为其配置环境变量即可。 + +这样,在许多情况下,你可以了解容器和 Docker,并通过许多不同的工具和组件重复使用这些知识。 + +因此,你可以运行带有不同内容的**多个容器**,例如数据库、Python 应用程序、带有 React 前端应用程序的 Web 服务器,并通过内部网络将它们连接在一起。 + +所有容器管理系统(如 Docker 或 Kubernetes)都集成了这些网络功能。 + +## 容器和进程 + +**容器镜像**通常在其元数据中包含启动**容器**时应运行的默认程序或命令以及要传递给该程序的参数。 与在命令行中的情况非常相似。 + +当 **容器** 启动时,它将运行该命令/程序(尽管你可以覆盖它并使其运行不同的命令/程序)。 + +只要**主进程**(命令或程序)在运行,容器就在运行。 + +容器通常有一个**单个进程**,但也可以从主进程启动子进程,这样你就可以在同一个容器中拥有**多个进程**。 + +但是,如果没有**至少一个正在运行的进程**,就不可能有一个正在运行的容器。 如果主进程停止,容器也会停止。 + + +## 为 FastAPI 构建 Docker 镜像 + +好吧,让我们现在构建一些东西! 🚀 + +我将向你展示如何基于 **官方 Python** 镜像 **从头开始** 为 FastAPI 构建 **Docker 镜像**。 + +这是你在**大多数情况**下想要做的,例如: + +* 使用 **Kubernetes** 或类似工具 +* 在 **Raspberry Pi** 上运行时 +* 使用可为你运行容器镜像的云服务等。 + +### 依赖项 + +你通常会在某个文件中包含应用程序的**依赖项**。 + +具体做法取决于你**安装**这些依赖时所使用的工具。 + +最常见的方法是创建一个`requirements.txt`文件,其中每行包含一个包名称和它的版本。 + +你当然也可以使用在[关于 FastAPI 版本](./versions.md){.internal-link target=_blank} 中讲到的方法来设置版本范围。 + +例如,你的`requirements.txt`可能如下所示: + + +``` +fastapi>=0.68.0,<0.69.0 +pydantic>=1.8.0,<2.0.0 +uvicorn>=0.15.0,<0.16.0 +``` + +你通常会使用`pip`安装这些依赖项: + +
+ +```console +$ pip install -r requirements.txt +---> 100% +Successfully installed fastapi pydantic uvicorn +``` + +
+ +!!! info + 还有其他文件格式和工具来定义和安装依赖项。 + + 我将在下面的部分中向你展示一个使用 Poetry 的示例。 👇 + +### 创建 **FastAPI** 代码 + +* 创建`app`目录并进入。 +* 创建一个空文件`__init__.py`。 +* 创建一个 `main.py` 文件: + + + +```Python +from typing import Union + +from fastapi import FastAPI + +app = FastAPI() + + +@app.get("/") +def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} +``` + +### Dockerfile + +现在在相同的project目录创建一个名为`Dockerfile`的文件: + +```{ .dockerfile .annotate } +# (1) +FROM python:3.9 + +# (2) +WORKDIR /code + +# (3) +COPY ./requirements.txt /code/requirements.txt + +# (4) +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt + +# (5) +COPY ./app /code/app + +# (6) +CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] +``` + +1. 从官方Python基础镜像开始。 + +2. 将当前工作目录设置为`/code`。 + + 这是我们放置`requirements.txt`文件和`app`目录的位置。 + +3. 将符合要求的文件复制到`/code`目录中。 + + 首先仅复制requirements.txt文件,而不复制其余代码。 + + 由于此文件**不经常更改**,Docker 将检测到它并在这一步中使用**缓存**,从而为下一步启用缓存。 + +4. 安装需求文件中的包依赖项。 + + `--no-cache-dir` 选项告诉 `pip` 不要在本地保存下载的包,因为只有当 `pip` 再次运行以安装相同的包时才会这样,但在与容器一起工作时情况并非如此。 + + !!! 笔记 + `--no-cache-dir` 仅与 `pip` 相关,与 Docker 或容器无关。 + + `--upgrade` 选项告诉 `pip` 升级软件包(如果已经安装)。 + + 因为上一步复制文件可以被 **Docker 缓存** 检测到,所以此步骤也将 **使用 Docker 缓存**(如果可用)。 + + 在开发过程中一次又一次构建镜像时,在此步骤中使用缓存将为你节省大量**时间**,而不是**每次**都**下载和安装**所有依赖项。 + + +5. 将“./app”目录复制到“/code”目录中。 + + 由于其中包含**更改最频繁**的所有代码,因此 Docker **缓存**不会轻易用于此操作或任何**后续步骤**。 + + 因此,将其放在`Dockerfile`**接近最后**的位置非常重要,以优化容器镜像的构建时间。 + +6. 设置**命令**来运行 `uvicorn` 服务器。 + + `CMD` 接受一个字符串列表,每个字符串都是你在命令行中输入的内容,并用空格分隔。 + + 该命令将从 **当前工作目录** 运行,即你上面使用`WORKDIR /code`设置的同一`/code`目录。 + + 因为程序将从`/code`启动,并且其中包含你的代码的目录`./app`,所以**Uvicorn**将能够从`app.main`中查看并**import**`app`。 + +!!! tip + 通过单击代码中的每个数字气泡来查看每行的作用。 👆 + +你现在应该具有如下目录结构: +``` +. +├── app +│   ├── __init__.py +│ └── main.py +├── Dockerfile +└── requirements.txt +``` + + +#### 在 TLS 终止代理后面 + +如果你在 Nginx 或 Traefik 等 TLS 终止代理(负载均衡器)后面运行容器,请添加选项 `--proxy-headers`,这将告诉 Uvicorn 信任该代理发送的标头,告诉它应用程序正在 HTTPS 后面运行等信息 + +```Dockerfile +CMD ["uvicorn", "app.main:app", "--proxy-headers", "--host", "0.0.0.0", "--port", "80"] +``` + +#### Docker 缓存 + +这个`Dockerfile`中有一个重要的技巧,我们首先只单独复制**包含依赖项的文件**,而不是其余代码。 让我来告诉你这是为什么。 + +```Dockerfile +COPY ./requirements.txt /code/requirements.txt +``` + +Docker之类的构建工具是通过**增量**的方式来构建这些容器镜像的。具体做法是从`Dockerfile`顶部开始,每一条指令生成的文件都是镜像的“一层”,同过把这些“层”一层一层地叠加到基础镜像上,最后我们就得到了最终的镜像。 + +Docker 和类似工具在构建镜像时也会使用**内部缓存**,如果自上次构建容器镜像以来文件没有更改,那么它将**重新使用上次创建的同一层**,而不是再次复制文件并从头开始创建新层。 + +仅仅避免文件的复制不一定会有太多速度提升,但是如果在这一步使用了缓存,那么才可以**在下一步中使用缓存**。 例如,可以使用安装依赖项那条指令的缓存: + +```Dockerfile +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt +``` + + +包含包依赖项的文件**不会频繁更改**。 只复制该文件(不复制其他的应用代码),Docker 才能在这一步**使用缓存**。 + +Docker 进而能**使用缓存进行下一步**,即下载并安装这些依赖项。 这才是我们**节省大量时间**的地方。 ✨ ...可以避免无聊的等待。 😪😆 + +下载和安装依赖项**可能需要几分钟**,但使用**缓存**最多**只需要几秒钟**。 + +由于你在开发过程中会一次又一次地构建容器镜像以检查代码更改是否有效,因此可以累计节省大量时间。 + +在`Dockerfile`末尾附近,我们再添加复制代码的指令。 由于代码是**更改最频繁的**,所以将其放在最后,因为这一步之后的内容基本上都是无法使用缓存的。 + +```Dockerfile +COPY ./app /code/app +``` + +### 构建 Docker 镜像 + +现在所有文件都已就位,让我们构建容器镜像。 + +* 转到项目目录(在`Dockerfile`所在的位置,包含`app`目录)。 +* 构建你的 FastAPI 镜像: + + +
+ +```console +$ docker build -t myimage . + +---> 100% +``` + +
+ + +!!! tip + 注意最后的 `.`,它相当于`./`,它告诉 Docker 用于构建容器镜像的目录。 + + 在本例中,它是相同的当前目录(`.`)。 + +### 启动 Docker 容器 + +* 根据你的镜像运行容器: + +
+ +```console +$ docker run -d --name mycontainer -p 80:80 myimage +``` + +
+ +## 检查一下 + + +你应该能在Docker容器的URL中检查它,例如: http://192.168.99.100/items/5?q=somequeryhttp://127.0.0.1/items/5?q=somequery (或其他等价的,使用 Docker 主机). + +你会看到类似内容: + +```JSON +{"item_id": 5, "q": "somequery"} +``` + +## 交互式 API 文档 + +现在你可以转到 http://192.168.99.100/docshttp://127.0.0.1/docs (或其他等价的,使用 Docker 主机)。 + +你将看到自动交互式 API 文档(由 Swagger UI): + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +## 备选的 API 文档 + +你还可以访问 http://192.168.99.100/redochttp://127.0.0.1/redoc (或其他等价的,使用 Docker 主机)。 + +你将看到备选的自动文档(由 ReDoc 提供): + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +## 使用单文件 FastAPI 构建 Docker 镜像 + +如果你的 FastAPI 是单个文件,例如没有`./app`目录的`main.py`,则你的文件结构可能如下所示: + +``` +. +├── Dockerfile +├── main.py +└── requirements.txt +``` + +然后你只需更改相应的路径即可将文件复制到`Dockerfile`中: + +```{ .dockerfile .annotate hl_lines="10 13" } +FROM python:3.9 + +WORKDIR /code + +COPY ./requirements.txt /code/requirements.txt + +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt + +# (1) +COPY ./main.py /code/ + +# (2) +CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] +``` + +1. 直接将`main.py`文件复制到`/code`目录中(不包含任何`./app`目录)。 + +2. 运行 Uvicorn 并告诉它从 `main` 导入 `app` 对象(而不是从 `app.main` 导入)。 + +然后调整Uvicorn命令使用新模块`main`而不是`app.main`来导入FastAPI 实例`app`。 + +## 部署概念 + +我们再谈谈容器方面的一些相同的[部署概念](./concepts.md){.internal-link target=_blank}。 + +容器主要是一种简化**构建和部署**应用程序的过程的工具,但它们并不强制执行特定的方法来处理这些**部署概念**,并且有几种可能的策略。 + +**好消息**是,对于每种不同的策略,都有一种方法可以涵盖所有部署概念。 🎉 + +让我们从容器的角度回顾一下这些**部署概念**: + +* HTTPS +* 启动时运行 +* 重新启动 +* 复制(运行的进程数) +* 内存 +* 开始前的先前步骤 + + +## HTTPS + +如果我们只关注 FastAPI 应用程序的 **容器镜像**(以及稍后运行的 **容器**),HTTPS 通常会由另一个工具在 **外部** 处理。 + +它可以是另一个容器,例如使用 Traefik,处理 **HTTPS** 和 **自动**获取**证书**。 + +!!! tip + Traefik可以与 Docker、Kubernetes 等集成,因此使用它为容器设置和配置 HTTPS 非常容易。 + +或者,HTTPS 可以由云服务商作为其服务之一进行处理(同时仍在容器中运行应用程序)。 + +## 在启动和重新启动时运行 + +通常还有另一个工具负责**启动和运行**你的容器。 + +它可以直接是**Docker**, 或者**Docker Compose**、**Kubernetes**、**云服务**等。 + +在大多数(或所有)情况下,有一个简单的选项可以在启动时运行容器并在失败时重新启动。 例如,在 Docker 中,它是命令行选项 `--restart`。 + +如果不使用容器,让应用程序在启动时运行并重新启动可能会很麻烦且困难。 但在大多数情况下,当**使用容器**时,默认情况下会包含该功能。 ✨ + +## 复制 - 进程数 + +如果你有一个 集群, 比如 **Kubernetes**、Docker Swarm、Nomad 或其他类似的复杂系统来管理多台机器上的分布式容器,那么你可能希望在**集群级别**处理复制**,而不是在每个容器中使用**进程管理器**(如带有Worker的 Gunicorn) 。 + +像 Kubernetes 这样的分布式容器管理系统通常有一些集成的方法来处理**容器的复制**,同时仍然支持传入请求的**负载均衡**。 全部都在**集群级别**。 + +在这些情况下,你可能希望从头开始构建一个 **Docker 镜像**,如[上面所解释](#dockerfile)的那样,安装依赖项并运行 **单个 Uvicorn 进程**,而不是运行 Gunicorn 和 Uvicorn workers这种。 + + +### 负载均衡器 + +使用容器时,通常会有一些组件**监听主端口**。 它可能是处理 **HTTPS** 的 **TLS 终止代理** 或一些类似的工具的另一个容器。 + +由于该组件将接受请求的**负载**并(希望)以**平衡**的方式在worker之间分配该请求,因此它通常也称为**负载均衡器**。 + +!!! tip + 用于 HTTPS **TLS 终止代理** 的相同组件也可能是 **负载均衡器**。 + +当使用容器时,你用来启动和管理容器的同一系统已经具有内部工具来传输来自该**负载均衡器**(也可以是**TLS 终止代理**) 的**网络通信**(例如HTTP请求)到你的应用程序容器。 + +### 一个负载均衡器 - 多个worker容器 + +当使用 **Kubernetes** 或类似的分布式容器管理系统时,使用其内部网络机制将允许单个在主 **端口** 上侦听的 **负载均衡器** 将通信(请求)传输到可能的 **多个** 运行你应用程序的容器。 + +运行你的应用程序的每个容器通常**只有一个进程**(例如,运行 FastAPI 应用程序的 Uvicorn 进程)。 它们都是**相同的容器**,运行相同的东西,但每个容器都有自己的进程、内存等。这样你就可以在 CPU 的**不同核心**, 甚至在**不同的机器**充分利用**并行化(parallelization)**。 + +具有**负载均衡器**的分布式容器系统将**将请求轮流分配**给你的应用程序的每个容器。 因此,每个请求都可以由运行你的应用程序的多个**复制容器**之一来处理。 + +通常,这个**负载均衡器**能够处理发送到集群中的*其他*应用程序的请求(例如发送到不同的域,或在不同的 URL 路径前缀下),并正确地将该通信传输到在集群中运行的*其他*应用程序的对应容器。 + + + + + + +### 每个容器一个进程 + +在这种类型的场景中,你可能希望**每个容器有一个(Uvicorn)进程**,因为你已经在集群级别处理复制。 + +因此,在这种情况下,你**不会**希望拥有像 Gunicorn 和 Uvicorn worker一样的进程管理器,或者 Uvicorn 使用自己的 Uvicorn worker。 你可能希望每个容器(但可能有多个容器)只有一个**单独的 Uvicorn 进程**。 + +在容器内拥有另一个进程管理器(就像使用 Gunicorn 或 Uvicorn 管理 Uvicorn 工作线程一样)只会增加**不必要的复杂性**,而你很可能已经在集群系统中处理这些复杂性了。 + +### 具有多个进程的容器 + +当然,在某些**特殊情况**,你可能希望拥有 **一个容器**,其中包含 **Gunicorn 进程管理器**,并在其中启动多个 **Uvicorn worker进程**。 + +在这些情况下,你可以使用 **官方 Docker 镜像**,其中包含 **Gunicorn** 作为运行多个 **Uvicorn 工作进程** 的进程管理器,以及一些默认设置来根据当前情况调整工作进程数量 自动CPU核心。 我将在下面的 [Gunicorn - Uvicorn 官方 Docker 镜像](#official-docker-image-with-gunicorn-uvicorn) 中告诉你更多相关信息。 + +下面一些什么时候这种做法有意义的示例: + + +#### 一个简单的应用程序 + +如果你的应用程序**足够简单**,你不需要(至少现在不需要)过多地微调进程数量,并且你可以使用自动默认值,那么你可能需要容器中的进程管理器 (使用官方 Docker 镜像),并且你在**单个服务器**而不是集群上运行它。 + +#### Docker Compose + +你可以使用 **Docker Compose** 部署到**单个服务器**(而不是集群),因此你没有一种简单的方法来管理容器的复制(使用 Docker Compose),同时保留共享网络和 **负载均衡**。 + +然后,你可能希望拥有一个**单个容器**,其中有一个**进程管理器**,在其中启动**多个worker进程**。 + +#### Prometheus和其他原因 + +你还可能有**其他原因**,这将使你更容易拥有一个带有**多个进程**的**单个容器**,而不是拥有每个容器中都有**单个进程**的**多个容器**。 + +例如(取决于你的设置)你可以在同一个容器中拥有一些工具,例如 Prometheus exporter,该工具应该有权访问**每个请求**。 + +在这种情况下,如果你有**多个容器**,默认情况下,当 Prometheus 来**读取metrics**时,它每次都会获取**单个容器**的metrics(对于处理该特定请求的容器),而不是获取所有复制容器的**累积metrics**。 + +在这种情况, 这种做法会更加简单:让**一个容器**具有**多个进程**,并在同一个容器上使用本地工具(例如 Prometheus exporter)收集所有内部进程的 Prometheus 指标并公开单个容器上的这些指标。 + +--- + +要点是,这些都**不是**你必须盲目遵循的**一成不变的规则**。 你可以根据这些思路**评估你自己的场景**并决定什么方法是最适合你的的系统,考虑如何管理以下概念: + +* 安全性 - HTTPS +* 启动时运行 +* 重新启动 +* 复制(运行的进程数) +* 内存 +* 开始前的先前步骤 + +## 内存 + +如果你**每个容器运行一个进程**,那么每个容器所消耗的内存或多或少是定义明确的、稳定的且有限的(如果它们是复制的,则不止一个)。 + +然后,你可以在容器管理系统的配置中设置相同的内存限制和要求(例如在 **Kubernetes** 中)。 这样,它将能够在**可用机器**中**复制容器**,同时考虑容器所需的内存量以及集群中机器中的可用内存量。 + +如果你的应用程序很**简单**,这可能**不是问题**,并且你可能不需要指定内存限制。 但是,如果你**使用大量内存**(例如使用**机器学习**模型),则应该检查你消耗了多少内存并调整**每台机器**中运行的**容器数量**(也许可以向集群添加更多机器)。 + +如果你**每个容器运行多个进程**(例如使用官方 Docker 镜像),你必须确保启动的进程数量不会消耗比可用内存**更多的内存**。 + +## 启动之前的步骤和容器 + +如果你使用容器(例如 Docker、Kubernetes),那么你可以使用两种主要方法。 + + +### 多个容器 + +如果你有 **多个容器**,可能每个容器都运行一个 **单个进程**(例如,在 **Kubernetes** 集群中),那么你可能希望有一个 **单独的容器** 执行以下操作: 在单个容器中运行单个进程执行**先前步骤**,即运行复制的worker容器之前。 + +!!! info + 如果你使用 Kubernetes,这可能是 Init Container。 + +如果在你的用例中,运行前面的步骤**并行多次**没有问题(例如,如果你没有运行数据库迁移,而只是检查数据库是否已准备好),那么你也可以将它们放在开始主进程之前在每个容器中。 + +### 单容器 + +如果你有一个简单的设置,使用一个**单个容器**,然后启动多个**工作进程**(或者也只是一个进程),那么你可以在启动进程之前在应用程序同一个容器中运行先前的步骤。 官方 Docker 镜像内部支持这一点。 + +## 带有 Gunicorn 的官方 Docker 镜像 - Uvicorn + +有一个官方 Docker 镜像,其中包含与 Uvicorn worker一起运行的 Gunicorn,如上一章所述:[服务器工作线程 - Gunicorn 与 Uvicorn](./server-workers.md){.internal-link target=_blank}。 + +该镜像主要在上述情况下有用:[具有多个进程和特殊情况的容器](#containers-with-multiple-processes-and-special-cases)。 + + + +* tiangolo/uvicorn-gunicorn-fastapi. + + +!!! warning + 你很有可能不需要此基础镜像或任何其他类似的镜像,最好从头开始构建镜像,如[上面所述:为 FastAPI 构建 Docker 镜像](#build-a-docker-image-for-fastapi)。 + +该镜像包含一个**自动调整**机制,用于根据可用的 CPU 核心设置**worker进程数**。 + +它具有**合理的默认值**,但你仍然可以使用**环境变量**或配置文件更改和更新所有配置。 + +它还支持通过一个脚本运行**开始前的先前步骤** 。 + +!!! tip + 要查看所有配置和选项,请转到 Docker 镜像页面: tiangolo/uvicorn-gunicorn-fastapi。 + +### 官方 Docker 镜像上的进程数 + +此镜像上的**进程数**是根据可用的 CPU **核心**自动计算的。 + +这意味着它将尝试尽可能多地**榨取**CPU 的**性能**。 + +你还可以使用 **环境变量** 等配置来调整它。 + +但这也意味着,由于进程数量取决于容器运行的 CPU,因此**消耗的内存量**也将取决于该数量。 + +因此,如果你的应用程序消耗大量内存(例如机器学习模型),并且你的服务器有很多 CPU 核心**但内存很少**,那么你的容器最终可能会尝试使用比实际情况更多的内存 可用,并且性能会下降很多(甚至崩溃)。 🚨 + +### 创建一个`Dockerfile` + +以下是如何根据此镜像创建`Dockerfile`: + + +```Dockerfile +FROM tiangolo/uvicorn-gunicorn-fastapi:python3.9 + +COPY ./requirements.txt /app/requirements.txt + +RUN pip install --no-cache-dir --upgrade -r /app/requirements.txt + +COPY ./app /app +``` + +### 更大的应用程序 + +如果你按照有关创建[具有多个文件的更大应用程序](../tutorial/bigger-applications.md){.internal-link target=_blank}的部分进行操作,你的`Dockerfile`可能看起来这样: + +```Dockerfile hl_lines="7" +FROM tiangolo/uvicorn-gunicorn-fastapi:python3.9 + +COPY ./requirements.txt /app/requirements.txt + +RUN pip install --no-cache-dir --upgrade -r /app/requirements.txt + +COPY ./app /app/app +``` + +### 何时使用 + +如果你使用 **Kubernetes** (或其他)并且你已经在集群级别设置 **复制**,并且具有多个 **容器**。 在这些情况下,你最好按照上面的描述 **从头开始构建镜像**:[为 FastAPI 构建 Docker 镜像](#build-a-docker-image-for-fastapi)。 + +该镜像主要在[具有多个进程的容器和特殊情况](#containers-with-multiple-processes-and-special-cases)中描述的特殊情况下有用。 例如,如果你的应用程序**足够简单**,基于 CPU 设置默认进程数效果很好,你不想在集群级别手动配置复制,并且不会运行更多进程, 或者你使用 **Docker Compose** 进行部署,在单个服务器上运行等。 + +## 部署容器镜像 + +拥有容器(Docker)镜像后,有多种方法可以部署它。 + +例如: + +* 在单个服务器中使用 **Docker Compose** +* 使用 **Kubernetes** 集群 +* 使用 Docker Swarm 模式集群 +* 使用Nomad等其他工具 +* 使用云服务获取容器镜像并部署它 + +## Docker 镜像与Poetry + +如果你使用 Poetry 来管理项目的依赖项,你可以使用 Docker 多阶段构建: + + + +```{ .dockerfile .annotate } +# (1) +FROM python:3.9 as requirements-stage + +# (2) +WORKDIR /tmp + +# (3) +RUN pip install poetry + +# (4) +COPY ./pyproject.toml ./poetry.lock* /tmp/ + +# (5) +RUN poetry export -f requirements.txt --output requirements.txt --without-hashes + +# (6) +FROM python:3.9 + +# (7) +WORKDIR /code + +# (8) +COPY --from=requirements-stage /tmp/requirements.txt /code/requirements.txt + +# (9) +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt + +# (10) +COPY ./app /code/app + +# (11) +CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] +``` + +1. 这是第一阶段,称为`requirements-stage`。 + +2. 将 `/tmp` 设置为当前工作目录。 + + 这是我们生成文件`requirements.txt`的地方 + +3. 在此阶段安装Poetry。 + +4. 将`pyproject.toml`和`poetry.lock`文件复制到`/tmp`目录。 + + 因为它使用 `./poetry.lock*` (以 `*` 结尾),所以如果该文件尚不可用,它不会崩溃。 + +5. 生成`requirements.txt`文件。 + +6. 这是最后阶段,这里的任何内容都将保留在最终的容器镜像中。 + +7. 将当前工作目录设置为`/code`。 + +8. 将 `requirements.txt` 文件复制到 `/code` 目录。 + + 该文件仅存在于前一个阶段,这就是为什么我们使用 `--from-requirements-stage` 来复制它。 + +9. 安装生成的`requirements.txt`文件中的依赖项。 + +10. 将`app`目录复制到`/code`目录。 + +11. 运行`uvicorn`命令,告诉它使用从`app.main`导入的`app`对象。 + +!!! tip + 单击气泡数字可查看每行的作用。 + +**Docker stage** 是 `Dockerfile` 的一部分,用作 **临时容器镜像**,仅用于生成一些稍后使用的文件。 + +第一阶段仅用于 **安装 Poetry** 并使用 Poetry 的 `pyproject.toml` 文件中的项目依赖项 **生成 `requirements.txt`**。 + +此`requirements.txt`文件将在**下一阶段**与`pip`一起使用。 + +在最终的容器镜像中**仅保留最后阶段**。 之前的阶段将被丢弃。 + +使用 Poetry 时,使用 **Docker 多阶段构建** 是有意义的,因为你实际上并不需要在最终的容器镜像中安装 Poetry 及其依赖项,你 **只需要** 生成用于安装项目依赖项的`requirements.txt`文件。 + +然后,在下一个(也是最后一个)阶段,你将或多或少地以与前面描述的相同的方式构建镜像。 + +### 在TLS 终止代理后面 - Poetry + +同样,如果你在 Nginx 或 Traefik 等 TLS 终止代理(负载均衡器)后面运行容器,请将选项`--proxy-headers`添加到命令中: + + +```Dockerfile +CMD ["uvicorn", "app.main:app", "--proxy-headers", "--host", "0.0.0.0", "--port", "80"] +``` + +## 回顾 + +使用容器系统(例如使用**Docker**和**Kubernetes**),处理所有**部署概念**变得相当简单: + +* HTTPS +* 启动时运行 +* 重新启动 +* 复制(运行的进程数) +* 内存 +* 开始前的先前步骤 + +在大多数情况下,你可能不想使用任何基础镜像,而是基于官方 Python Docker 镜像 **从头开始构建容器镜像** 。 + +处理好`Dockerfile`和 **Docker 缓存**中指令的**顺序**,你可以**最小化构建时间**,从而最大限度地提高生产力(并避免无聊)。 😎 + +在某些特殊情况下,你可能需要使用 FastAPI 的官方 Docker 镜像。 🤓 diff --git a/docs/zh/docs/deployment/https.md b/docs/zh/docs/deployment/https.md new file mode 100644 index 0000000000000..cf01a4585bec2 --- /dev/null +++ b/docs/zh/docs/deployment/https.md @@ -0,0 +1,192 @@ +# 关于 HTTPS + +人们很容易认为 HTTPS 仅仅是“启用”或“未启用”的东西。 + +但实际情况比这复杂得多。 + +!!!提示 + 如果你很赶时间或不在乎,请继续阅读下一部分,下一部分会提供一个step-by-step的教程,告诉你怎么使用不同技术来把一切都配置好。 + +要从用户的视角**了解 HTTPS 的基础知识**,请查看 https://howhttps.works/。 + +现在,从**开发人员的视角**,在了解 HTTPS 时需要记住以下几点: + +* 要使用 HTTPS,**服务器**需要拥有由**第三方**生成的**"证书(certificate)"**。 + * 这些证书实际上是从第三方**获取**的,而不是“生成”的。 +* 证书有**生命周期**。 + * 它们会**过期**。 + * 然后它们需要**更新**,**再次从第三方获取**。 +* 连接的加密发生在 **TCP 层**。 + * 这是 HTTP 协议**下面的一层**。 + * 因此,**证书和加密**处理是在 **HTTP之前**完成的。 +* **TCP 不知道域名**。 仅仅知道 IP 地址。 + * 有关所请求的 **特定域名** 的信息位于 **HTTP 数据**中。 +* **HTTPS 证书**“证明”**某个域名**,但协议和加密发生在 TCP 层,在知道正在处理哪个域名**之前**。 +* **默认情况下**,这意味着你**每个 IP 地址只能拥有一个 HTTPS 证书**。 + * 无论你的服务器有多大,或者服务器上的每个应用程序有多小。 + * 不过,对此有一个**解决方案**。 +* **TLS** 协议(在 HTTP 之下的TCP 层处理加密的协议)有一个**扩展**,称为 **SNI**。 + * SNI 扩展允许一台服务器(具有 **单个 IP 地址**)拥有 **多个 HTTPS 证书** 并提供 **多个 HTTPS 域名/应用程序**。 + * 为此,服务器上会有**单独**的一个组件(程序)侦听**公共 IP 地址**,这个组件必须拥有服务器中的**所有 HTTPS 证书**。 +* **获得安全连接后**,通信协议**仍然是HTTP**。 + * 内容是 **加密过的**,即使它们是通过 **HTTP 协议** 发送的。 + +通常的做法是在服务器上运行**一个程序/HTTP 服务器**并**管理所有 HTTPS 部分**:接收**加密的 HTTPS 请求**, 将 **解密的 HTTP 请求** 发送到在同一服务器中运行的实际 HTTP 应用程序(在本例中为 **FastAPI** 应用程序),从应用程序中获取 **HTTP 响应**, 使用适当的 **HTTPS 证书**对其进行加密并使用 **HTTPS** 将其发送回客户端。 此服务器通常被称为 **TLS 终止代理(TLS Termination Proxy)**。 + +你可以用作 TLS 终止代理的一些选项包括: + +* Traefik(也可以处理证书更新) +* Caddy(也可以处理证书更新) +* Nginx +* HAProxy + +## Let's Encrypt + +在 Let's Encrypt 之前,这些 **HTTPS 证书** 由受信任的第三方出售。 + +过去,获得这些证书的过程非常繁琐,需要大量的文书工作,而且证书非常昂贵。 + +但随后 **Let's Encrypt** 创建了。 + +它是 Linux 基金会的一个项目。 它以自动方式免费提供 **HTTPS 证书**。 这些证书可以使用所有符合标准的安全加密,并且有效期很短(大约 3 个月),因此**安全性实际上更好**,因为它们的生命周期缩短了。 + +域可以被安全地验证并自动生成证书。 这还允许自动更新这些证书。 + +我们的想法是自动获取和更新这些证书,以便你可以永远免费拥有**安全的 HTTPS**。 + +## 面向开发人员的 HTTPS + +这里有一个 HTTPS API 看起来是什么样的示例,我们会分步说明,并且主要关注对开发人员重要的部分。 + + +### 域名 + +第一步我们要先**获取**一些**域名(Domain Name)**。 然后可以在 DNS 服务器(可能是你的同一家云服务商提供的)中配置它。 + +你可能拥有一个云服务器(虚拟机)或类似的东西,并且它会有一个固定 **公共IP地址**。 + +在 DNS 服务器中,你可以配置一条记录(“A 记录”)以将 **你的域名** 指向你服务器的公共 **IP 地址**。 + +这个操作一般只需要在最开始执行一次。 + +!!! tip + 域名这部分发生在 HTTPS 之前,由于这一切都依赖于域名和 IP 地址,所以先在这里提一下。 + +### DNS + +现在让我们关注真正的 HTTPS 部分。 + +首先,浏览器将通过 **DNS 服务器** 查询**域名的IP** 是什么,在本例中为 `someapp.example.com`。 + +DNS 服务器会告诉浏览器使用某个特定的 **IP 地址**。 这将是你在 DNS 服务器中为你的服务器配置的公共 IP 地址。 + + + +### TLS 握手开始 + +然后,浏览器将在**端口 443**(HTTPS 端口)上与该 IP 地址进行通信。 + +通信的第一部分只是建立客户端和服务器之间的连接并决定它们将使用的加密密钥等。 + + + +客户端和服务器之间建立 TLS 连接的过程称为 **TLS 握手**。 + +### 带有 SNI 扩展的 TLS + +**服务器中只有一个进程**可以侦听特定 **IP 地址**的特定 **端口**。 可能有其他进程在同一 IP 地址的其他端口上侦听,但每个 IP 地址和端口组合只有一个进程。 + +TLS (HTTPS) 默认使用端口`443`。 这就是我们需要的端口。 + +由于只有一个进程可以监听此端口,因此监听端口的进程将是 **TLS 终止代理**。 + +TLS 终止代理可以访问一个或多个 **TLS 证书**(HTTPS 证书)。 + +使用上面讨论的 **SNI 扩展**,TLS 终止代理将检查应该用于此连接的可用 TLS (HTTPS) 证书,并使用与客户端期望的域名相匹配的证书。 + +在这种情况下,它将使用`someapp.example.com`的证书。 + + + +客户端已经**信任**生成该 TLS 证书的实体(在本例中为 Let's Encrypt,但我们稍后会看到),因此它可以**验证**该证书是否有效。 + +然后,通过使用证书,客户端和 TLS 终止代理 **决定如何加密** **TCP 通信** 的其余部分。 这就完成了 **TLS 握手** 部分。 + +此后,客户端和服务器就拥有了**加密的 TCP 连接**,这就是 TLS 提供的功能。 然后他们可以使用该连接来启动实际的 **HTTP 通信**。 + +这就是 **HTTPS**,它只是 **安全 TLS 连接** 内的普通 **HTTP**,而不是纯粹的(未加密的)TCP 连接。 + +!!! tip + 请注意,通信加密发生在 **TCP 层**,而不是 HTTP 层。 + +### HTTPS 请求 + +现在客户端和服务器(特别是浏览器和 TLS 终止代理)具有 **加密的 TCP 连接**,它们可以开始 **HTTP 通信**。 + +接下来,客户端发送一个 **HTTPS 请求**。 这其实只是一个通过 TLS 加密连接的 HTTP 请求。 + + + +### 解密请求 + +TLS 终止代理将使用协商好的加密算法**解密请求**,并将**(解密的)HTTP 请求**传输到运行应用程序的进程(例如运行 FastAPI 应用的 Uvicorn 进程)。 + + + +### HTTP 响应 + +应用程序将处理请求并向 TLS 终止代理发送**(未加密)HTTP 响应**。 + + + +### HTTPS 响应 + +然后,TLS 终止代理将使用之前协商的加密算法(以`someapp.example.com`的证书开头)对响应进行加密,并将其发送回浏览器。 + +接下来,浏览器将验证响应是否有效和是否使用了正确的加密密钥等。然后它会**解密响应**并处理它。 + + + +客户端(浏览器)将知道响应来自正确的服务器,因为它使用了他们之前使用 **HTTPS 证书** 协商出的加密算法。 + +### 多个应用程序 + +在同一台(或多台)服务器中,可能存在**多个应用程序**,例如其他 API 程序或数据库。 + +只有一个进程可以处理特定的 IP 和端口(在我们的示例中为 TLS 终止代理),但其他应用程序/进程也可以在服务器上运行,只要它们不尝试使用相同的 **公共 IP 和端口的组合**。 + + + +这样,TLS 终止代理就可以为多个应用程序处理**多个域名**的 HTTPS 和证书,然后在每种情况下将请求传输到正确的应用程序。 + +### 证书更新 + +在未来的某个时候,每个证书都会**过期**(大约在获得证书后 3 个月)。 + +然后,会有另一个程序(在某些情况下是另一个程序,在某些情况下可能是同一个 TLS 终止代理)与 Let's Encrypt 通信并更新证书。 + + + +**TLS 证书** **与域名相关联**,而不是与 IP 地址相关联。 + +因此,要更新证书,更新程序需要向权威机构(Let's Encrypt)**证明**它确实**“拥有”并控制该域名**。 + +有多种方法可以做到这一点。 一些流行的方式是: + +* **修改一些DNS记录**。 + * 为此,续订程序需要支持 DNS 提供商的 API,因此,要看你使用的 DNS 提供商是否提供这一功能。 +* **在与域名关联的公共 IP 地址上作为服务器运行**(至少在证书获取过程中)。 + * 正如我们上面所说,只有一个进程可以监听特定的 IP 和端口。 + * 这就是当同一个 TLS 终止代理还负责证书续订过程时它非常有用的原因之一。 + * 否则,你可能需要暂时停止 TLS 终止代理,启动续订程序以获取证书,然后使用 TLS 终止代理配置它们,然后重新启动 TLS 终止代理。 这并不理想,因为你的应用程序在 TLS 终止代理关闭期间将不可用。 + +通过拥有一个**单独的系统来使用 TLS 终止代理来处理 HTTPS**, 而不是直接将 TLS 证书与应用程序服务器一起使用 (例如 Uvicorn),你可以在 +更新证书的过程中同时保持提供服务。 + +## 回顾 + +拥有**HTTPS** 非常重要,并且在大多数情况下相当**关键**。 作为开发人员,你围绕 HTTPS 所做的大部分努力就是**理解这些概念**以及它们的工作原理。 + +一旦你了解了**面向开发人员的 HTTPS** 的基础知识,你就可以轻松组合和配置不同的工具,以帮助你以简单的方式管理一切。 + +在接下来的一些章节中,我将向你展示几个为 **FastAPI** 应用程序设置 **HTTPS** 的具体示例。 🔒 diff --git a/docs/zh/docs/deployment/index.md b/docs/zh/docs/deployment/index.md new file mode 100644 index 0000000000000..1ec0c5c5b5976 --- /dev/null +++ b/docs/zh/docs/deployment/index.md @@ -0,0 +1,21 @@ +# 部署 + +部署 **FastAPI** 应用程序相对容易。 + +## 部署是什么意思 + +**部署**应用程序意味着执行必要的步骤以使其**可供用户使用**。 + +对于**Web API**来说,通常涉及将上传到**云服务器**中,搭配一个性能和稳定性都不错的**服务器程序**,以便你的**用户**可以高效地**访问**你的应用程序,而不会出现中断或其他问题。 + +这与**开发**阶段形成鲜明对比,在**开发**阶段,你不断更改代码、破坏代码、修复代码, 来回停止和重启服务器等。 + +## 部署策略 + +根据你的使用场景和使用的工具,有多种方法可以实现此目的。 + +你可以使用一些工具自行**部署服务器**,你也可以使用能为你完成部分工作的**云服务**,或其他可能的选项。 + +我将向你展示在部署 **FastAPI** 应用程序时你可能应该记住的一些主要概念(尽管其中大部分适用于任何其他类型的 Web 应用程序)。 + +在接下来的部分中,你将看到更多需要记住的细节以及一些技巧。 ✨ diff --git a/docs/zh/docs/deployment/manually.md b/docs/zh/docs/deployment/manually.md new file mode 100644 index 0000000000000..15588043fecbb --- /dev/null +++ b/docs/zh/docs/deployment/manually.md @@ -0,0 +1,148 @@ +# 手动运行服务器 - Uvicorn + +在远程服务器计算机上运行 **FastAPI** 应用程序所需的主要东西是 ASGI 服务器程序,例如 **Uvicorn**。 + +有 3 个主要可选方案: + +* Uvicorn:高性能 ASGI 服务器。 +* Hypercorn:与 HTTP/2 和 Trio 等兼容的 ASGI 服务器。 +* Daphne:为 Django Channels 构建的 ASGI 服务器。 + +## 服务器主机和服务器程序 + +关于名称,有一个小细节需要记住。 💡 + +“**服务器**”一词通常用于指远程/云计算机(物理机或虚拟机)以及在该计算机上运行的程序(例如 Uvicorn)。 + +请记住,当您一般读到“服务器”这个名词时,它可能指的是这两者之一。 + +当提到远程主机时,通常将其称为**服务器**,但也称为**机器**(machine)、**VM**(虚拟机)、**节点**。 这些都是指某种类型的远程计算机,通常运行 Linux,您可以在其中运行程序。 + + +## 安装服务器程序 + +您可以使用以下命令安装 ASGI 兼容服务器: + +=== "Uvicorn" + + * Uvicorn,一个快如闪电 ASGI 服务器,基于 uvloop 和 httptools 构建。 + +
+ + ```console + $ pip install "uvicorn[standard]" + + ---> 100% + ``` + +
+ + !!! tip + 通过添加`standard`,Uvicorn 将安装并使用一些推荐的额外依赖项。 + + 其中包括`uvloop`,它是`asyncio`的高性能替代品,它提供了巨大的并发性能提升。 + +=== "Hypercorn" + + * Hypercorn,一个也与 HTTP/2 兼容的 ASGI 服务器。 + +
+ + ```console + $ pip install hypercorn + + ---> 100% + ``` + +
+ + ...或任何其他 ASGI 服务器。 + + +## 运行服务器程序 + +您可以按照之前教程中的相同方式运行应用程序,但不使用`--reload`选项,例如: + +=== "Uvicorn" + +
+ + ```console + $ uvicorn main:app --host 0.0.0.0 --port 80 + + INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) + ``` + +
+ + +=== "Hypercorn" + +
+ + ```console + $ hypercorn main:app --bind 0.0.0.0:80 + + Running on 0.0.0.0:8080 over http (CTRL + C to quit) + ``` + +
+ +!!! warning + 如果您正在使用`--reload`选项,请记住删除它。 + + `--reload` 选项消耗更多资源,并且更不稳定。 + + 它在**开发**期间有很大帮助,但您**不应该**在**生产环境**中使用它。 + +## Hypercorn with Trio + +Starlette 和 **FastAPI** 基于 AnyIO, 所以它们才能同时与 Python 的标准库 asyncioTrio 兼容。 + +尽管如此,Uvicorn 目前仅与 asyncio 兼容,并且通常使用 `uvloop`, 它是`asyncio`的高性能替代品。 + +但如果你想直接使用**Trio**,那么你可以使用**Hypercorn**,因为它支持它。 ✨ + +### 安装具有 Trio 的 Hypercorn + +首先,您需要安装具有 Trio 支持的 Hypercorn: + +
+ +```console +$ pip install "hypercorn[trio]" +---> 100% +``` + +
+ +### Run with Trio + +然后你可以传递值`trio`给命令行选项`--worker-class`: + +
+ +```console +$ hypercorn main:app --worker-class trio +``` + +
+ +这将通过您的应用程序启动 Hypercorn,并使用 Trio 作为后端。 + +现在您可以在应用程序内部使用 Trio。 或者更好的是,您可以使用 AnyIO,使您的代码与 Trio 和 asyncio 兼容。 🎉 + +## 部署概念 + +这些示例运行服务器程序(例如 Uvicorn),启动**单个进程**,在所有 IP(`0.0.0.0`)上监听预定义端口(例如`80`)。 + +这是基本思路。 但您可能需要处理一些其他事情,例如: + +* 安全性 - HTTPS +* 启动时运行 +* 重新启动 +* Replication(运行的进程数) +* 内存 +* 开始前的步骤 + +在接下来的章节中,我将向您详细介绍每个概念、如何思考它们,以及一些具体示例以及处理它们的策略。 🚀 diff --git a/docs/zh/docs/deployment/server-workers.md b/docs/zh/docs/deployment/server-workers.md new file mode 100644 index 0000000000000..ee3de9b5da406 --- /dev/null +++ b/docs/zh/docs/deployment/server-workers.md @@ -0,0 +1,184 @@ +# Server Workers - Gunicorn with Uvicorn + +让我们回顾一下之前的部署概念: + +* 安全性 - HTTPS +* 启动时运行 +* 重新启动 +* **复制(运行的进程数)** +* 内存 +* 启动前的先前步骤 + +到目前为止,通过文档中的所有教程,您可能已经在**单个进程**上运行了像 Uvicorn 这样的**服务器程序**。 + +部署应用程序时,您可能希望进行一些**进程复制**,以利用**多核**并能够处理更多请求。 + +正如您在上一章有关[部署概念](./concepts.md){.internal-link target=_blank}中看到的,您可以使用多种策略。 + +在这里我将向您展示如何将 **Gunicorn** 与 **Uvicorn worker 进程** 一起使用。 + +!!! info + 如果您正在使用容器,例如 Docker 或 Kubernetes,我将在下一章中告诉您更多相关信息:[容器中的 FastAPI - Docker](./docker.md){.internal-link target=_blank}。 + + 特别是,当在 **Kubernetes** 上运行时,您可能**不想**使用 Gunicorn,而是运行 **每个容器一个 Uvicorn 进程**,但我将在本章后面告诉您这一点。 + + + +## Gunicorn with Uvicorn Workers + +**Gunicorn**主要是一个使用**WSGI标准**的应用服务器。 这意味着 Gunicorn 可以为 Flask 和 Django 等应用程序提供服务。 Gunicorn 本身与 **FastAPI** 不兼容,因为 FastAPI 使用最新的 **ASGI 标准**。 + +但 Gunicorn 支持充当 **进程管理器** 并允许用户告诉它要使用哪个特定的 **worker类**。 然后 Gunicorn 将使用该类启动一个或多个 **worker进程**。 + +**Uvicorn** 有一个 Gunicorn 兼容的worker类。 + +使用这种组合,Gunicorn 将充当 **进程管理器**,监听 **端口** 和 **IP**。 它会将通信**传输**到运行**Uvicorn类**的worker进程。 + +然后与Gunicorn兼容的**Uvicorn worker**类将负责将Gunicorn发送的数据转换为ASGI标准以供FastAPI使用。 + +## 安装 Gunicorn 和 Uvicorn + +
+ +```console +$ pip install "uvicorn[standard]" gunicorn + +---> 100% +``` + +
+ +这将安装带有`standard`扩展包(以获得高性能)的 Uvicorn 和 Gunicorn。 + +## Run Gunicorn with Uvicorn Workers + +接下来你可以通过以下命令运行Gunicorn: + +
+ +```console +$ gunicorn main:app --workers 4 --worker-class uvicorn.workers.UvicornWorker --bind 0.0.0.0:80 + +[19499] [INFO] Starting gunicorn 20.1.0 +[19499] [INFO] Listening at: http://0.0.0.0:80 (19499) +[19499] [INFO] Using worker: uvicorn.workers.UvicornWorker +[19511] [INFO] Booting worker with pid: 19511 +[19513] [INFO] Booting worker with pid: 19513 +[19514] [INFO] Booting worker with pid: 19514 +[19515] [INFO] Booting worker with pid: 19515 +[19511] [INFO] Started server process [19511] +[19511] [INFO] Waiting for application startup. +[19511] [INFO] Application startup complete. +[19513] [INFO] Started server process [19513] +[19513] [INFO] Waiting for application startup. +[19513] [INFO] Application startup complete. +[19514] [INFO] Started server process [19514] +[19514] [INFO] Waiting for application startup. +[19514] [INFO] Application startup complete. +[19515] [INFO] Started server process [19515] +[19515] [INFO] Waiting for application startup. +[19515] [INFO] Application startup complete. +``` + +
+ + +让我们看看每个选项的含义: + +* `main:app`:这与 Uvicorn 使用的语法相同,`main` 表示名为"`main`"的 Python 模块,因此是文件 `main.py`。 `app` 是 **FastAPI** 应用程序的变量名称。 + * 你可以想象 `main:app` 相当于一个 Python `import` 语句,例如: + + ```Python + from main import app + ``` + + * 因此,`main:app` 中的冒号相当于 `from main import app` 中的 Python `import` 部分。 + +* `--workers`:要使用的worker进程数量,每个进程将运行一个 Uvicorn worker进程,在本例中为 4 个worker进程。 + +* `--worker-class`:在worker进程中使用的与 Gunicorn 兼容的工作类。 + * 这里我们传递了 Gunicorn 可以导入和使用的类: + + ```Python + import uvicorn.workers.UvicornWorker + ``` + +* `--bind`:这告诉 Gunicorn 要监听的 IP 和端口,使用冒号 (`:`) 分隔 IP 和端口。 + * 如果您直接运行 Uvicorn,则可以使用`--host 0.0.0.0`和`--port 80`,而不是`--bind 0.0.0.0:80`(Gunicorn 选项)。 + + +在输出中,您可以看到它显示了每个进程的 **PID**(进程 ID)(它只是一个数字)。 + +你可以看到: + +* Gunicorn **进程管理器** 以 PID `19499` 开头(在您的情况下,它将是一个不同的数字)。 +* 然后它开始`Listening at: http://0.0.0.0:80`。 +* 然后它检测到它必须使用 `uvicorn.workers.UvicornWorker` 处的worker类。 +* 然后它启动**4个worker**,每个都有自己的PID:`19511`、`19513`、`19514`和`19515`。 + +Gunicorn 还将负责管理**死进程**和**重新启动**新进程(如果需要保持worker数量)。 因此,这在一定程度上有助于上面列表中**重启**的概念。 + +尽管如此,您可能还希望有一些外部的东西,以确保在必要时**重新启动 Gunicorn**,并且**在启动时运行它**等。 + +## Uvicorn with Workers + +Uvicorn 也有一个选项可以启动和运行多个 **worker进程**。 + +然而,到目前为止,Uvicorn 处理worker进程的能力比 Gunicorn 更有限。 因此,如果您想拥有这个级别(Python 级别)的进程管理器,那么最好尝试使用 Gunicorn 作为进程管理器。 + +无论如何,您都可以像这样运行它: + +
+ +```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. +``` + +
+ +这里唯一的新选项是 `--workers` 告诉 Uvicorn 启动 4 个工作进程。 + +您还可以看到它显示了每个进程的 **PID**,父进程(这是 **进程管理器**)的 PID 为`27365`,每个工作进程的 PID 为:`27368`、`27369`, `27370`和`27367`。 + +## 部署概念 + +在这里,您了解了如何使用 **Gunicorn**(或 Uvicorn)管理 **Uvicorn 工作进程**来**并行**应用程序的执行,利用 CPU 中的 **多核**,并 能够满足**更多请求**。 + +从上面的部署概念列表来看,使用worker主要有助于**复制**部分,并对**重新启动**有一点帮助,但您仍然需要照顾其他部分: + +* **安全 - HTTPS** +* **启动时运行** +* ***重新启动*** +* 复制(运行的进程数) +* **内存** +* **启动之前的先前步骤** + +## 容器和 Docker + +在关于 [容器中的 FastAPI - Docker](./docker.md){.internal-link target=_blank} 的下一章中,我将介绍一些可用于处理其他 **部署概念** 的策略。 + +我还将向您展示 **官方 Docker 镜像**,其中包括 **Gunicorn 和 Uvicorn worker** 以及一些对简单情况有用的默认配置。 + +在那里,我还将向您展示如何 **从头开始构建自己的镜像** 以运行单个 Uvicorn 进程(没有 Gunicorn)。 这是一个简单的过程,并且可能是您在使用像 **Kubernetes** 这样的分布式容器管理系统时想要做的事情。 + +## 回顾 + +您可以使用**Gunicorn**(或Uvicorn)作为Uvicorn工作进程的进程管理器,以利用**多核CPU**,**并行运行多个进程**。 + +如果您要设置**自己的部署系统**,同时自己处理其他部署概念,则可以使用这些工具和想法。 + +请查看下一章,了解带有容器(例如 Docker 和 Kubernetes)的 **FastAPI**。 您将看到这些工具也有简单的方法来解决其他**部署概念**。 ✨ diff --git a/docs/zh/docs/deployment/versions.md b/docs/zh/docs/deployment/versions.md new file mode 100644 index 0000000000000..75b870139cbd4 --- /dev/null +++ b/docs/zh/docs/deployment/versions.md @@ -0,0 +1,87 @@ +# 关于 FastAPI 版本 + +**FastAPI** 已在许多应用程序和系统的生产环境中使用。 并且测试覆盖率保持在100%。 但其开发进度仍在快速推进。 + +经常添加新功能,定期修复错误,并且代码仍在持续改进。 + +这就是为什么当前版本仍然是`0.x.x`,这反映出每个版本都可能有Breaking changes。 这遵循语义版本控制的约定。 + +你现在就可以使用 **FastAPI** 创建生产环境应用程序(你可能已经这样做了一段时间),你只需确保使用的版本可以与其余代码正确配合即可。 + +## 固定你的 `fastapi` 版本 + +你应该做的第一件事是将你正在使用的 **FastAPI** 版本“固定”到你知道适用于你的应用程序的特定最新版本。 + +例如,假设你在应用程序中使用版本`0.45.0`。 + +如果你使用`requirements.txt`文件,你可以使用以下命令指定版本: + +````txt +fastapi==0.45.0 +```` + +这意味着你将使用版本`0.45.0`。 + +或者你也可以将其固定为: + +````txt +fastapi>=0.45.0,<0.46.0 +```` + +这意味着你将使用`0.45.0`或更高版本,但低于`0.46.0`,例如,版本`0.45.2`仍会被接受。 + +如果你使用任何其他工具来管理你的安装,例如 Poetry、Pipenv 或其他工具,它们都有一种定义包的特定版本的方法。 + +## 可用版本 + +你可以在[发行说明](../release-notes.md){.internal-link target=_blank}中查看可用版本(例如查看当前最新版本)。 + +## 关于版本 + +遵循语义版本控制约定,任何低于`1.0.0`的版本都可能会添加 breaking changes。 + +FastAPI 还遵循这样的约定:任何`PATCH`版本更改都是为了bug修复和non-breaking changes。 + +!!! tip + "PATCH"是最后一个数字,例如,在`0.2.3`中,PATCH版本是`3`。 + +因此,你应该能够固定到如下版本: + +```txt +fastapi>=0.45.0,<0.46.0 +``` + +"MINOR"版本中会添加breaking changes和新功能。 + +!!! tip + "MINOR"是中间的数字,例如,在`0.2.3`中,MINOR版本是`2`。 + +## 升级FastAPI版本 + +你应该为你的应用程序添加测试。 + +使用 **FastAPI** 编写测试非常简单(感谢 Starlette),请参考文档:[测试](../tutorial/testing.md){.internal-link target=_blank} + +添加测试后,你可以将 **FastAPI** 版本升级到更新版本,并通过运行测试来确保所有代码都能正常工作。 + +如果一切正常,或者在进行必要的更改之后,并且所有测试都通过了,那么你可以将`fastapi`固定到新的版本。 + +## 关于Starlette + +你不应该固定`starlette`的版本。 + +不同版本的 **FastAPI** 将使用特定的较新版本的 Starlette。 + +因此,**FastAPI** 自己可以使用正确的 Starlette 版本。 + +## 关于 Pydantic + +Pydantic 包含针对 **FastAPI** 的测试及其自己的测试,因此 Pydantic 的新版本(`1.0.0`以上)始终与 FastAPI 兼容。 + +你可以将 Pydantic 固定到适合你的`1.0.0`以上和`2.0.0`以下的任何版本。 + +例如: + +````txt +pydantic>=1.2.0,<2.0.0 +```` diff --git a/docs/zh/docs/external-links.md b/docs/zh/docs/external-links.md new file mode 100644 index 0000000000000..8c919fa384871 --- /dev/null +++ b/docs/zh/docs/external-links.md @@ -0,0 +1,83 @@ +# 外部链接与文章 + +**FastAPI** 社区正在不断壮大。 + +有关 **FastAPI** 的帖子、文章、工具和项目越来越多。 + +以下是 **FastAPI** 各种资源的不完整列表。 + +!!! tip "提示" + + 如果您的文章、项目、工具或其它任何与 **FastAPI** 相关的内容尚未收入此表,请在此创建 PR。 + +## 文章 + +### 英文 + +{% if external_links %} +{% for article in external_links.articles.english %} + +* {{ article.title }} by {{ article.author }}. +{% endfor %} +{% endif %} + +### 日文 + +{% if external_links %} +{% for article in external_links.articles.japanese %} + +* {{ article.title }} by {{ article.author }}. +{% endfor %} +{% endif %} + +### 越南语 + +{% if external_links %} +{% for article in external_links.articles.vietnamese %} + +* {{ article.title }} by {{ article.author }}. +{% endfor %} +{% endif %} + +### 俄语 + +{% if external_links %} +{% for article in external_links.articles.russian %} + +* {{ article.title }} by {{ article.author }}. +{% endfor %} +{% endif %} + +### 德语 + +{% if external_links %} +{% for article in external_links.articles.german %} + +* {{ article.title }} by {{ article.author }}. +{% endfor %} +{% endif %} + +## 播客 + +{% if external_links %} +{% for article in external_links.podcasts.english %} + +* {{ article.title }} by {{ article.author }}. +{% endfor %} +{% endif %} + +## 访谈 + +{% if external_links %} +{% for article in external_links.talks.english %} + +* {{ article.title }} by {{ article.author }}. +{% endfor %} +{% endif %} + +## 项目 + +GitHub 上最新的 `fastapi` 主题项目: + +
+
diff --git a/docs/zh/docs/fastapi-people.md b/docs/zh/docs/fastapi-people.md index 5d7b0923f33c4..7ef3f3c1a688a 100644 --- a/docs/zh/docs/fastapi-people.md +++ b/docs/zh/docs/fastapi-people.md @@ -40,7 +40,7 @@ FastAPI 有一个非常棒的社区,它欢迎来自各个领域和背景的朋 {% if people %}
-{% for user in people.last_month_active %} +{% for user in people.last_month_experts[:10] %}
@{{ user.login }}
Issues replied: {{ user.count }}
{% endfor %} @@ -58,7 +58,7 @@ FastAPI 有一个非常棒的社区,它欢迎来自各个领域和背景的朋 {% if people %}
-{% for user in people.experts %} +{% for user in people.experts[:50] %}
@{{ user.login }}
Issues replied: {{ user.count }}
{% endfor %} @@ -76,7 +76,7 @@ FastAPI 有一个非常棒的社区,它欢迎来自各个领域和背景的朋 {% if people %}
-{% for user in people.top_contributors %} +{% for user in people.top_contributors[:50] %}
@{{ user.login }}
Pull Requests: {{ user.count }}
{% endfor %} @@ -100,7 +100,7 @@ FastAPI 有一个非常棒的社区,它欢迎来自各个领域和背景的朋 {% if people %}
-{% for user in people.top_reviewers %} +{% for user in people.top_translations_reviewers[:50] %}
@{{ user.login }}
Reviews: {{ user.count }}
{% endfor %} diff --git a/docs/zh/docs/features.md b/docs/zh/docs/features.md index 2db7f852a9e83..d8190032f6233 100644 --- a/docs/zh/docs/features.md +++ b/docs/zh/docs/features.md @@ -179,7 +179,7 @@ FastAPI 有一个使用非常简单,但是非常强大的IDE/linter/brain** 适配: * 因为 pydantic 数据结构仅仅是你定义的类的实例;自动补全,linting,mypy 以及你的直觉应该可以和你验证的数据一起正常工作。 -* **更快**: - * 在 基准测试 中,Pydantic 比其他被测试的库都要快。 * 验证**复杂结构**: * 使用分层的 Pydantic 模型, Python `typing`的 `List` 和 `Dict` 等等。 * 验证器使我们能够简单清楚的将复杂的数据模式定义、检查并记录为 JSON Schema。 diff --git a/docs/zh/docs/help-fastapi.md b/docs/zh/docs/help-fastapi.md index 2a99950e31ea6..9b70d115a2c34 100644 --- a/docs/zh/docs/help-fastapi.md +++ b/docs/zh/docs/help-fastapi.md @@ -114,8 +114,6 @@ 聊天室仅供闲聊。 -我们之前还使用过 Gitter chat,但它不支持频道等高级功能,聊天也比较麻烦,所以现在推荐使用 Discord。 - ### 别在聊天室里提问 注意,聊天室更倾向于“闲聊”,经常有人会提出一些笼统得让人难以回答的问题,所以在这里提问一般没人回答。 diff --git a/docs/zh/docs/history-design-future.md b/docs/zh/docs/history-design-future.md new file mode 100644 index 0000000000000..798b8fb5f4592 --- /dev/null +++ b/docs/zh/docs/history-design-future.md @@ -0,0 +1,78 @@ +# 历史、设计、未来 + +不久前,曾有 **FastAPI** 用户问过: + +> 这个项目有怎样的历史?好像它只用了几周就从默默无闻变得众所周知…… + +在此,我们简单回顾一下 **FastAPI** 的历史。 + +## 备选方案 + +有那么几年,我曾领导数个开发团队为诸多复杂需求创建各种 API,这些需求包括机器学习、分布系统、异步任务、NoSQL 数据库等领域。 + +作为工作的一部分,我需要调研很多备选方案、还要测试并且使用这些备选方案。 + +**FastAPI** 其实只是延续了这些前辈的历史。 + +正如[备选方案](alternatives.md){.internal-link target=_blank}一章所述: + +
+没有大家之前所做的工作,**FastAPI** 就不会存在。 + +以前创建的这些工具为它的出现提供了灵感。 + +在那几年中,我一直回避创建新的框架。首先,我尝试使用各种框架、插件、工具解决 **FastAPI** 现在的功能。 + +但到了一定程度之后,我别无选择,只能从之前的工具中汲取最优思路,并以尽量好的方式把这些思路整合在一起,使用之前甚至是不支持的语言特性(Python 3.6+ 的类型提示),从而创建一个能满足我所有需求的框架。 + +
+ +## 调研 + +通过使用之前所有的备选方案,我有机会从它们之中学到了很多东西,获取了很多想法,并以我和我的开发团队能想到的最好方式把这些思路整合成一体。 + +例如,大家都清楚,在理想状态下,它应该基于标准的 Python 类型提示。 + +而且,最好的方式是使用现有的标准。 + +因此,甚至在开发 **FastAPI** 前,我就花了几个月的时间研究 OpenAPI、JSON Schema、OAuth2 等规范。深入理解它们之间的关系、重叠及区别之处。 + +## 设计 + +然后,我又花了一些时间从用户角度(使用 FastAPI 的开发者)设计了开发者 **API**。 + +同时,我还在最流行的 Python 代码编辑器中测试了很多思路,包括 PyCharm、VS Code、基于 Jedi 的编辑器。 + +根据最新 Python 开发者调研报告显示,这几种编辑器覆盖了约 80% 的用户。 + +也就是说,**FastAPI** 针对差不多 80% 的 Python 开发者使用的编辑器进行了测试,而且其它大多数编辑器的工作方式也与之类似,因此,**FastAPI** 的优势几乎能在所有编辑器上体现。 + +通过这种方式,我就能找到尽可能减少代码重复的最佳方式,进而实现处处都有自动补全、类型提示与错误检查等支持。 + +所有这些都是为了给开发者提供最佳的开发体验。 + +## 需求项 + +经过测试多种备选方案,我最终决定使用 **Pydantic**,并充分利用它的优势。 + +我甚至为它做了不少贡献,让它完美兼容了 JSON Schema,支持多种方式定义约束声明,并基于多个编辑器,改进了它对编辑器支持(类型检查、自动补全)。 + +在开发期间,我还为 **Starlette** 做了不少贡献,这是另一个关键需求项。 + +## 开发 + +当我启动 **FastAPI** 开发的时候,绝大多数部件都已经就位,设计已经定义,需求项和工具也已经准备就绪,相关标准与规范的知识储备也非常清晰而新鲜。 + +## 未来 + +至此,**FastAPI** 及其理念已经为很多人所用。 + +对于很多用例,它比以前很多备选方案都更适用。 + +很多开发者和开发团队已经依赖 **FastAPI** 开发他们的项目(包括我和我的团队)。 + +但,**FastAPI** 仍有很多改进的余地,也还需要添加更多的功能。 + +总之,**FastAPI** 前景光明。 + +在此,我们衷心感谢[您的帮助](help-fastapi.md){.internal-link target=_blank}。 diff --git a/docs/zh/docs/index.md b/docs/zh/docs/index.md index 1de2a8d36d09a..a480d6640783c 100644 --- a/docs/zh/docs/index.md +++ b/docs/zh/docs/index.md @@ -24,7 +24,7 @@ --- -FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框架,使用 Python 3.6+ 并基于标准的 Python 类型提示。 +FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框架,使用 Python 3.8+ 并基于标准的 Python 类型提示。 关键特性: @@ -107,12 +107,12 @@ FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框 ## 依赖 -Python 3.6 及更高版本 +Python 3.8 及更高版本 FastAPI 站在以下巨人的肩膀之上: * Starlette 负责 web 部分。 -* Pydantic 负责数据部分。 +* Pydantic 负责数据部分。 ## 安装 @@ -323,7 +323,7 @@ def update_item(item_id: int, item: Item): 你不需要去学习新的语法、了解特定库的方法或类,等等。 -只需要使用标准的 **Python 3.6 及更高版本**。 +只需要使用标准的 **Python 3.8 及更高版本**。 举个例子,比如声明 `int` 类型: @@ -443,7 +443,7 @@ item: Item * httpx - 使用 `TestClient` 时安装。 * jinja2 - 使用默认模板配置时安装。 -* python-multipart - 需要通过 `request.form()` 对表单进行「解析」时安装。 +* python-multipart - 需要通过 `request.form()` 对表单进行「解析」时安装。 * itsdangerous - 需要 `SessionMiddleware` 支持时安装。 * pyyaml - 使用 Starlette 提供的 `SchemaGenerator` 时安装(有 FastAPI 你可能并不需要它)。 * graphene - 需要 `GraphQLApp` 支持时安装。 diff --git a/docs/zh/docs/learn/index.md b/docs/zh/docs/learn/index.md new file mode 100644 index 0000000000000..38696f6feae03 --- /dev/null +++ b/docs/zh/docs/learn/index.md @@ -0,0 +1,5 @@ +# 学习 + +以下是学习 **FastAPI** 的介绍部分和教程。 + +您可以认为这是一本 **书**,一门 **课程**,是 **官方** 且推荐的学习FastAPI的方法。😎 diff --git a/docs/zh/docs/project-generation.md b/docs/zh/docs/project-generation.md new file mode 100644 index 0000000000000..feafa533316bd --- /dev/null +++ b/docs/zh/docs/project-generation.md @@ -0,0 +1,84 @@ +# 项目生成 - 模板 + +项目生成器一般都会提供很多初始设置、安全措施、数据库,甚至还准备好了第一个 API 端点,能帮助您快速上手。 + +项目生成器的设置通常都很主观,您可以按需更新或修改,但对于您的项目来说,它是非常好的起点。 + +## 全栈 FastAPI + PostgreSQL + +GitHub:https://github.com/tiangolo/full-stack-fastapi-postgresql + +### 全栈 FastAPI + PostgreSQL - 功能 + +* 完整的 **Docker** 集成(基于 Docker) +* Docker Swarm 开发模式 +* **Docker Compose** 本地开发集成与优化 +* **生产可用**的 Python 网络服务器,使用 Uvicorn 或 Gunicorn +* Python **FastAPI** 后端: +* * **速度快**:可与 **NodeJS** 和 **Go** 比肩的极高性能(归功于 Starlette 和 Pydantic) + * **直观**:强大的编辑器支持,处处皆可自动补全,减少调试时间 + * **简单**:易学、易用,阅读文档所需时间更短 + * **简短**:代码重复最小化,每次参数声明都可以实现多个功能 + * **健壮**: 生产级别的代码,还有自动交互文档 + * **基于标准**:完全兼容并基于 API 开放标准:OpenAPIJSON Schema + * **更多功能**包括自动验证、序列化、交互文档、OAuth2 JWT 令牌身份验证等 +* **安全密码**,默认使用密码哈希 +* **JWT 令牌**身份验证 +* **SQLAlchemy** 模型(独立于 Flask 扩展,可直接用于 Celery Worker) +* 基础的用户模型(可按需修改或删除) +* **Alembic** 迁移 +* **CORS**(跨域资源共享) +* **Celery** Worker 可从后端其它部分有选择地导入并使用模型和代码 +* REST 后端测试基于 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** + * 基于 **Nginx** 的 Docker 服务器(优化了 Vue-router 配置) + * Docker 多阶段构建,无需保存或提交编译的代码 + * 在构建时运行前端测试(可禁用) + * 尽量模块化,开箱即用,但仍可使用 Vue CLI 重新生成或创建所需项目,或复用所需内容 +* 使用 **PGAdmin** 管理 PostgreSQL 数据库,可轻松替换为 PHPMyAdmin 或 MySQL +* 使用 **Flower** 监控 Celery 任务 +* 使用 **Traefik** 处理前后端负载平衡,可把前后端放在同一个域下,按路径分隔,但在不同容器中提供服务 +* Traefik 集成,包括自动生成 Let's Encrypt **HTTPS** 凭证 +* GitLab **CI**(持续集成),包括前后端测试 + +## 全栈 FastAPI + Couchbase + +GitHub:https://github.com/tiangolo/full-stack-fastapi-couchbase + +⚠️ **警告** ⚠️ + +如果您想从头开始创建新项目,建议使用以下备选方案。 + +例如,项目生成器全栈 FastAPI + PostgreSQL 会更适用,这个项目的维护积极,用的人也多,还包括了所有新功能和改进内容。 + +当然,您也可以放心使用这个基于 Couchbase 的生成器,它也能正常使用。就算用它生成项目也没有任何问题(为了更好地满足需求,您可以自行更新这个项目)。 + +详见资源仓库中的文档。 + +## 全栈 FastAPI + MongoDB + +……敬请期待,得看我有没有时间做这个项目。😅 🎉 + +## FastAPI + spaCy 机器学习模型 + +GitHub:https://github.com/microsoft/cookiecutter-spacy-fastapi + +### FastAPI + spaCy 机器学习模型 - 功能 + +* 集成 **spaCy** NER 模型 +* 内置 **Azure 认知搜索**请求格式 +* **生产可用**的 Python 网络服务器,使用 Uvicorn 与 Gunicorn +* 内置 **Azure DevOps** Kubernetes (AKS) CI/CD 开发 +* **多语**支持,可在项目设置时选择 spaCy 内置的语言 +* 不仅局限于 spaCy,可**轻松扩展**至其它模型框架(Pytorch、TensorFlow) diff --git a/docs/zh/docs/python-types.md b/docs/zh/docs/python-types.md index 6cdb4b58838d7..214b47611e804 100644 --- a/docs/zh/docs/python-types.md +++ b/docs/zh/docs/python-types.md @@ -237,7 +237,7 @@ John Doe ## Pydantic 模型 -Pydantic 是一个用来用来执行数据校验的 Python 库。 +Pydantic 是一个用来用来执行数据校验的 Python 库。 你可以将数据的"结构"声明为具有属性的类。 @@ -254,7 +254,7 @@ John Doe ``` !!! info - 想进一步了解 Pydantic,请阅读其文档. + 想进一步了解 Pydantic,请阅读其文档. 整个 **FastAPI** 建立在 Pydantic 的基础之上。 diff --git a/docs/zh/docs/tutorial/background-tasks.md b/docs/zh/docs/tutorial/background-tasks.md new file mode 100644 index 0000000000000..94b75d4fddf08 --- /dev/null +++ b/docs/zh/docs/tutorial/background-tasks.md @@ -0,0 +1,126 @@ +# 后台任务 + +你可以定义在返回响应后运行的后台任务。 + +这对需要在请求之后执行的操作很有用,但客户端不必在接收响应之前等待操作完成。 + +包括这些例子: + +* 执行操作后发送的电子邮件通知: + * 由于连接到电子邮件服务器并发送电子邮件往往很“慢”(几秒钟),您可以立即返回响应并在后台发送电子邮件通知。 +* 处理数据: + * 例如,假设您收到的文件必须经过一个缓慢的过程,您可以返回一个"Accepted"(HTTP 202)响应并在后台处理它。 + +## 使用 `BackgroundTasks` + +首先导入 `BackgroundTasks` 并在 *路径操作函数* 中使用类型声明 `BackgroundTasks` 定义一个参数: + +```Python hl_lines="1 13" +{!../../../docs_src/background_tasks/tutorial001.py!} +``` + +**FastAPI** 会创建一个 `BackgroundTasks` 类型的对象并作为该参数传入。 + +## 创建一个任务函数 + +创建要作为后台任务运行的函数。 + +它只是一个可以接收参数的标准函数。 + +它可以是 `async def` 或普通的 `def` 函数,**FastAPI** 知道如何正确处理。 + +在这种情况下,任务函数将写入一个文件(模拟发送电子邮件)。 + +由于写操作不使用 `async` 和 `await`,我们用普通的 `def` 定义函数: + +```Python hl_lines="6-9" +{!../../../docs_src/background_tasks/tutorial001.py!} +``` + +## 添加后台任务 + +在你的 *路径操作函数* 里,用 `.add_task()` 方法将任务函数传到 *后台任务* 对象中: + +```Python hl_lines="14" +{!../../../docs_src/background_tasks/tutorial001.py!} +``` + +`.add_task()` 接收以下参数: + +* 在后台运行的任务函数(`write_notification`)。 +* 应按顺序传递给任务函数的任意参数序列(`email`)。 +* 应传递给任务函数的任意关键字参数(`message="some notification"`)。 + +## 依赖注入 + +使用 `BackgroundTasks` 也适用于依赖注入系统,你可以在多个级别声明 `BackgroundTasks` 类型的参数:在 *路径操作函数* 里,在依赖中(可依赖),在子依赖中,等等。 + +**FastAPI** 知道在每种情况下该做什么以及如何复用同一对象,因此所有后台任务被合并在一起并且随后在后台运行: + +=== "Python 3.10+" + + ```Python hl_lines="13 15 22 25" + {!> ../../../docs_src/background_tasks/tutorial002_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="13 15 22 25" + {!> ../../../docs_src/background_tasks/tutorial002_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="14 16 23 26" + {!> ../../../docs_src/background_tasks/tutorial002_an.py!} + ``` + +=== "Python 3.10+ 没Annotated" + + !!! tip + 尽可能选择使用 `Annotated` 的版本。 + + ```Python hl_lines="11 13 20 23" + {!> ../../../docs_src/background_tasks/tutorial002_py310.py!} + ``` + +=== "Python 3.8+ 没Annotated" + + !!! tip + 尽可能选择使用 `Annotated` 的版本。 + + ```Python hl_lines="13 15 22 25" + {!> ../../../docs_src/background_tasks/tutorial002.py!} + ``` + +该示例中,信息会在响应发出 *之后* 被写到 `log.txt` 文件。 + +如果请求中有查询,它将在后台任务中写入日志。 + +然后另一个在 *路径操作函数* 生成的后台任务会使用路径参数 `email` 写入一条信息。 + +## 技术细节 + +`BackgroundTasks` 类直接来自 `starlette.background`。 + +它被直接导入/包含到FastAPI以便你可以从 `fastapi` 导入,并避免意外从 `starlette.background` 导入备用的 `BackgroundTask` (后面没有 `s`)。 + +通过仅使用 `BackgroundTasks` (而不是 `BackgroundTask`),使得能将它作为 *路径操作函数* 的参数 ,并让**FastAPI**为您处理其余部分, 就像直接使用 `Request` 对象。 + +在FastAPI中仍然可以单独使用 `BackgroundTask`,但您必须在代码中创建对象,并返回包含它的Starlette `Response`。 + +更多细节查看 Starlette's official docs for Background Tasks. + +## 告诫 + +如果您需要执行繁重的后台计算,并且不一定需要由同一进程运行(例如,您不需要共享内存、变量等),那么使用其他更大的工具(如 Celery)可能更好。 + +它们往往需要更复杂的配置,即消息/作业队列管理器,如RabbitMQ或Redis,但它们允许您在多个进程中运行后台任务,甚至是在多个服务器中。 + +要查看示例,查阅 [Project Generators](../project-generation.md){.internal-link target=_blank},它们都包括已经配置的Celery。 + +但是,如果您需要从同一个**FastAPI**应用程序访问变量和对象,或者您需要执行小型后台任务(如发送电子邮件通知),您只需使用 `BackgroundTasks` 即可。 + +## 回顾 + +导入并使用 `BackgroundTasks` 通过 *路径操作函数* 中的参数和依赖项来添加后台任务。 diff --git a/docs/zh/docs/tutorial/bigger-applications.md b/docs/zh/docs/tutorial/bigger-applications.md index 9f0134f683c9e..1389595669313 100644 --- a/docs/zh/docs/tutorial/bigger-applications.md +++ b/docs/zh/docs/tutorial/bigger-applications.md @@ -79,7 +79,7 @@ 你可以导入它并通过与 `FastAPI` 类相同的方式创建一个「实例」: -```Python hl_lines="1 3" +```Python hl_lines="1 3" title="app/routers/users.py" {!../../../docs_src/bigger_applications/app/routers/users.py!} ``` @@ -89,7 +89,7 @@ 使用方式与 `FastAPI` 类相同: -```Python hl_lines="6 11 16" +```Python hl_lines="6 11 16" title="app/routers/users.py" {!../../../docs_src/bigger_applications/app/routers/users.py!} ``` @@ -112,7 +112,7 @@ 现在我们将使用一个简单的依赖项来读取一个自定义的 `X-Token` 请求首部: -```Python hl_lines="1 4-6" +```Python hl_lines="1 4-6" title="app/dependencies.py" {!../../../docs_src/bigger_applications/app/dependencies.py!} ``` @@ -143,7 +143,7 @@ 因此,我们可以将其添加到 `APIRouter` 中,而不是将其添加到每个路径操作中。 -```Python hl_lines="5-10 16 21" +```Python hl_lines="5-10 16 21" title="app/routers/items.py" {!../../../docs_src/bigger_applications/app/routers/items.py!} ``` @@ -195,7 +195,7 @@ async def read_item(item_id: str): 因此,我们通过 `..` 对依赖项使用了相对导入: -```Python hl_lines="3" +```Python hl_lines="3" title="app/routers/items.py" {!../../../docs_src/bigger_applications/app/routers/items.py!} ``` @@ -265,7 +265,7 @@ from ...dependencies import get_token_header 但是我们仍然可以添加*更多*将会应用于特定的*路径操作*的 `tags`,以及一些特定于该*路径操作*的额外 `responses`: -```Python hl_lines="30-31" +```Python hl_lines="30-31" title="app/routers/items.py" {!../../../docs_src/bigger_applications/app/routers/items.py!} ``` @@ -290,7 +290,7 @@ from ...dependencies import get_token_header 我们甚至可以声明[全局依赖项](dependencies/global-dependencies.md){.internal-link target=_blank},它会和每个 `APIRouter` 的依赖项组合在一起: -```Python hl_lines="1 3 7" +```Python hl_lines="1 3 7" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` @@ -298,7 +298,7 @@ from ...dependencies import get_token_header 现在,我们导入具有 `APIRouter` 的其他子模块: -```Python hl_lines="5" +```Python hl_lines="5" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` @@ -360,7 +360,7 @@ from .routers.users import router 因此,为了能够在同一个文件中使用它们,我们直接导入子模块: -```Python hl_lines="4" +```Python hl_lines="5" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` @@ -368,7 +368,7 @@ from .routers.users import router 现在,让我们来包含来自 `users` 和 `items` 子模块的 `router`。 -```Python hl_lines="10-11" +```Python hl_lines="10-11" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` @@ -401,7 +401,7 @@ from .routers.users import router 对于此示例,它将非常简单。但是假设由于它是与组织中的其他项目所共享的,因此我们无法对其进行修改,以及直接在 `APIRouter` 中添加 `prefix`、`dependencies`、`tags` 等: -```Python hl_lines="3" +```Python hl_lines="3" title="app/internal/admin.py" {!../../../docs_src/bigger_applications/app/internal/admin.py!} ``` @@ -409,7 +409,7 @@ from .routers.users import router 我们可以通过将这些参数传递给 `app.include_router()` 来完成所有的声明,而不必修改原始的 `APIRouter`: -```Python hl_lines="14-17" +```Python hl_lines="14-17" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` @@ -432,7 +432,7 @@ from .routers.users import router 这里我们这样做了...只是为了表明我们可以做到🤷: -```Python hl_lines="21-23" +```Python hl_lines="21-23" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` diff --git a/docs/zh/docs/tutorial/body-fields.md b/docs/zh/docs/tutorial/body-fields.md index 053cae71c7c6f..fb6c6d9b6a45e 100644 --- a/docs/zh/docs/tutorial/body-fields.md +++ b/docs/zh/docs/tutorial/body-fields.md @@ -6,9 +6,41 @@ 首先,你必须导入它: -```Python hl_lines="2" -{!../../../docs_src/body_fields/tutorial001.py!} -``` +=== "Python 3.10+" + + ```Python hl_lines="4" + {!> ../../../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.8+" + + ```Python hl_lines="4" + {!> ../../../docs_src/body_fields/tutorial001_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip + 尽可能选择使用 `Annotated` 的版本。 + + ```Python hl_lines="2" + {!> ../../../docs_src/body_fields/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + 尽可能选择使用 `Annotated` 的版本。 + + ```Python hl_lines="4" + {!> ../../../docs_src/body_fields/tutorial001.py!} + ``` !!! warning 注意,`Field` 是直接从 `pydantic` 导入的,而不是像其他的(`Query`,`Path`,`Body` 等)都从 `fastapi` 导入。 @@ -17,9 +49,41 @@ 然后,你可以对模型属性使用 `Field`: -```Python hl_lines="9-10" -{!../../../docs_src/body_fields/tutorial001.py!} -``` +=== "Python 3.10+" + + ```Python hl_lines="11-14" + {!> ../../../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.8+" + + ```Python hl_lines="12-15" + {!> ../../../docs_src/body_fields/tutorial001_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip + Prefer to use the `Annotated` version if possible. + + ```Python hl_lines="9-12" + {!> ../../../docs_src/body_fields/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + Prefer to use the `Annotated` version if possible. + + ```Python hl_lines="11-14" + {!> ../../../docs_src/body_fields/tutorial001.py!} + ``` `Field` 的工作方式和 `Query`、`Path` 和 `Body` 相同,包括它们的参数等等也完全相同。 diff --git a/docs/zh/docs/tutorial/body-multiple-params.md b/docs/zh/docs/tutorial/body-multiple-params.md index 34fa5b638ff1d..c93ef2f5cebc0 100644 --- a/docs/zh/docs/tutorial/body-multiple-params.md +++ b/docs/zh/docs/tutorial/body-multiple-params.md @@ -8,9 +8,41 @@ 你还可以通过将默认值设置为 `None` 来将请求体参数声明为可选参数: -```Python hl_lines="17-19" -{!../../../docs_src/body_multiple_params/tutorial001.py!} -``` +=== "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.8+" + + ```Python hl_lines="19-21" + {!> ../../../docs_src/body_multiple_params/tutorial001_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip + 尽可能选择使用 `Annotated` 的版本。 + + ```Python hl_lines="17-19" + {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + 尽可能选择使用 `Annotated` 的版本。 + + ```Python hl_lines="19-21" + {!> ../../../docs_src/body_multiple_params/tutorial001.py!} + ``` !!! note 请注意,在这种情况下,将从请求体获取的 `item` 是可选的。因为它的默认值为 `None`。 @@ -30,9 +62,17 @@ 但是你也可以声明多个请求体参数,例如 `item` 和 `user`: -```Python hl_lines="20" -{!../../../docs_src/body_multiple_params/tutorial002.py!} -``` +=== "Python 3.10+" + + ```Python hl_lines="20" + {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="22" + {!> ../../../docs_src/body_multiple_params/tutorial002.py!} + ``` 在这种情况下,**FastAPI** 将注意到该函数中有多个请求体参数(两个 Pydantic 模型参数)。 @@ -72,9 +112,41 @@ 但是你可以使用 `Body` 指示 **FastAPI** 将其作为请求体的另一个键进行处理。 -```Python hl_lines="22" -{!../../../docs_src/body_multiple_params/tutorial003.py!} -``` +=== "Python 3.10+" + + ```Python hl_lines="23" + {!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="23" + {!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="24" + {!> ../../../docs_src/body_multiple_params/tutorial003_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip + 尽可能选择使用 `Annotated` 的版本。 + + ```Python hl_lines="20" + {!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + 尽可能选择使用 `Annotated` 的版本。 + + ```Python hl_lines="22" + {!> ../../../docs_src/body_multiple_params/tutorial003.py!} + ``` 在这种情况下,**FastAPI** 将期望像这样的请求体: @@ -109,9 +181,41 @@ q: str = None 比如: -```Python hl_lines="25" -{!../../../docs_src/body_multiple_params/tutorial004.py!} -``` +=== "Python 3.10+" + + ```Python hl_lines="27" + {!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="27" + {!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="28" + {!> ../../../docs_src/body_multiple_params/tutorial004_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip + 尽可能选择使用 `Annotated` 的版本。 + + ```Python hl_lines="25" + {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + 尽可能选择使用 `Annotated` 的版本。 + + ```Python hl_lines="27" + {!> ../../../docs_src/body_multiple_params/tutorial004.py!} + ``` !!! info `Body` 同样具有与 `Query`、`Path` 以及其他后面将看到的类完全相同的额外校验和元数据参数。 @@ -131,9 +235,41 @@ item: Item = Body(embed=True) 比如: -```Python hl_lines="15" -{!../../../docs_src/body_multiple_params/tutorial005.py!} -``` +=== "Python 3.10+" + + ```Python hl_lines="17" + {!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="17" + {!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="18" + {!> ../../../docs_src/body_multiple_params/tutorial005_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip + 尽可能选择使用 `Annotated` 的版本。 + + ```Python hl_lines="15" + {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + 尽可能选择使用 `Annotated` 的版本。 + + ```Python hl_lines="17" + {!> ../../../docs_src/body_multiple_params/tutorial005.py!} + ``` 在这种情况下,**FastAPI** 将期望像这样的请求体: diff --git a/docs/zh/docs/tutorial/body-nested-models.md b/docs/zh/docs/tutorial/body-nested-models.md index 7649ee6feafed..3f519ae33a16b 100644 --- a/docs/zh/docs/tutorial/body-nested-models.md +++ b/docs/zh/docs/tutorial/body-nested-models.md @@ -6,9 +6,17 @@ 你可以将一个属性定义为拥有子元素的类型。例如 Python `list`: -```Python hl_lines="12" -{!../../../docs_src/body_nested_models/tutorial001.py!} -``` +=== "Python 3.10+" + + ```Python hl_lines="12" + {!> ../../../docs_src/body_nested_models/tutorial001_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="14" + {!> ../../../docs_src/body_nested_models/tutorial001.py!} + ``` 这将使 `tags` 成为一个由元素组成的列表。不过它没有声明每个元素的类型。 @@ -21,7 +29,7 @@ 首先,从 Python 的标准库 `typing` 模块中导入 `List`: ```Python hl_lines="1" -{!../../../docs_src/body_nested_models/tutorial002.py!} +{!> ../../../docs_src/body_nested_models/tutorial002.py!} ``` ### 声明具有子类型的 List @@ -43,9 +51,23 @@ my_list: List[str] 因此,在我们的示例中,我们可以将 `tags` 明确地指定为一个「字符串列表」: -```Python hl_lines="14" -{!../../../docs_src/body_nested_models/tutorial002.py!} -``` +=== "Python 3.10+" + + ```Python hl_lines="12" + {!> ../../../docs_src/body_nested_models/tutorial002_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="14" + {!> ../../../docs_src/body_nested_models/tutorial002_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="14" + {!> ../../../docs_src/body_nested_models/tutorial002.py!} + ``` ## Set 类型 @@ -55,9 +77,23 @@ Python 具有一种特殊的数据类型来保存一组唯一的元素,即 `se 然后我们可以导入 `Set` 并将 `tag` 声明为一个由 `str` 组成的 `set`: -```Python hl_lines="1 14" -{!../../../docs_src/body_nested_models/tutorial003.py!} -``` +=== "Python 3.10+" + + ```Python hl_lines="12" + {!> ../../../docs_src/body_nested_models/tutorial003_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="14" + {!> ../../../docs_src/body_nested_models/tutorial003_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="1 14" + {!> ../../../docs_src/body_nested_models/tutorial003.py!} + ``` 这样,即使你收到带有重复数据的请求,这些数据也会被转换为一组唯一项。 @@ -79,17 +115,45 @@ Pydantic 模型的每个属性都具有类型。 例如,我们可以定义一个 `Image` 模型: -```Python hl_lines="9 10 11" -{!../../../docs_src/body_nested_models/tutorial004.py!} -``` +=== "Python 3.10+" + + ```Python hl_lines="7-9" + {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="9-11" + {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9-11" + {!> ../../../docs_src/body_nested_models/tutorial004.py!} + ``` ### 将子模型用作类型 然后我们可以将其用作一个属性的类型: -```Python hl_lines="20" -{!../../../docs_src/body_nested_models/tutorial004.py!} -``` +=== "Python 3.10+" + + ```Python hl_lines="18" + {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="20" + {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="20" + {!> ../../../docs_src/body_nested_models/tutorial004.py!} + ``` 这意味着 **FastAPI** 将期望类似于以下内容的请求体: @@ -118,13 +182,27 @@ Pydantic 模型的每个属性都具有类型。 除了普通的单一值类型(如 `str`、`int`、`float` 等)外,你还可以使用从 `str` 继承的更复杂的单一值类型。 -要了解所有的可用选项,请查看关于 来自 Pydantic 的外部类型 的文档。你将在下一章节中看到一些示例。 +要了解所有的可用选项,请查看关于 来自 Pydantic 的外部类型 的文档。你将在下一章节中看到一些示例。 例如,在 `Image` 模型中我们有一个 `url` 字段,我们可以把它声明为 Pydantic 的 `HttpUrl`,而不是 `str`: -```Python hl_lines="4 10" -{!../../../docs_src/body_nested_models/tutorial005.py!} -``` +=== "Python 3.10+" + + ```Python hl_lines="2 8" + {!> ../../../docs_src/body_nested_models/tutorial005_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="4 10" + {!> ../../../docs_src/body_nested_models/tutorial005_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="4 10" + {!> ../../../docs_src/body_nested_models/tutorial005.py!} + ``` 该字符串将被检查是否为有效的 URL,并在 JSON Schema / OpenAPI 文档中进行记录。 @@ -132,9 +210,23 @@ Pydantic 模型的每个属性都具有类型。 你还可以将 Pydantic 模型用作 `list`、`set` 等的子类型: -```Python hl_lines="20" -{!../../../docs_src/body_nested_models/tutorial006.py!} -``` +=== "Python 3.10+" + + ```Python hl_lines="18" + {!> ../../../docs_src/body_nested_models/tutorial006_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="20" + {!> ../../../docs_src/body_nested_models/tutorial006_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="20" + {!> ../../../docs_src/body_nested_models/tutorial006.py!} + ``` 这将期望(转换,校验,记录文档等)下面这样的 JSON 请求体: @@ -169,9 +261,23 @@ Pydantic 模型的每个属性都具有类型。 你可以定义任意深度的嵌套模型: -```Python hl_lines="9 14 20 23 27" -{!../../../docs_src/body_nested_models/tutorial007.py!} -``` +=== "Python 3.10+" + + ```Python hl_lines="7 12 18 21 25" + {!> ../../../docs_src/body_nested_models/tutorial007_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="9 14 20 23 27" + {!> ../../../docs_src/body_nested_models/tutorial007_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9 14 20 23 27" + {!> ../../../docs_src/body_nested_models/tutorial007.py!} + ``` !!! info 请注意 `Offer` 拥有一组 `Item` 而反过来 `Item` 又是一个可选的 `Image` 列表是如何发生的。 @@ -186,9 +292,17 @@ images: List[Image] 例如: -```Python hl_lines="15" -{!../../../docs_src/body_nested_models/tutorial008.py!} -``` +=== "Python 3.9+" + + ```Python hl_lines="13" + {!> ../../../docs_src/body_nested_models/tutorial008_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="15" + {!> ../../../docs_src/body_nested_models/tutorial008.py!} + ``` ## 无处不在的编辑器支持 @@ -218,9 +332,17 @@ images: List[Image] 在下面的例子中,你将接受任意键为 `int` 类型并且值为 `float` 类型的 `dict`: -```Python hl_lines="15" -{!../../../docs_src/body_nested_models/tutorial009.py!} -``` +=== "Python 3.9+" + + ```Python hl_lines="7" + {!> ../../../docs_src/body_nested_models/tutorial009_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9" + {!> ../../../docs_src/body_nested_models/tutorial009.py!} + ``` !!! tip 请记住 JSON 仅支持将 `str` 作为键。 diff --git a/docs/zh/docs/tutorial/body.md b/docs/zh/docs/tutorial/body.md index 45a9095cc0d6d..fa8b54d0245ee 100644 --- a/docs/zh/docs/tutorial/body.md +++ b/docs/zh/docs/tutorial/body.md @@ -6,7 +6,7 @@ FastAPI 使用**请求体**从客户端(例如浏览器)向 API 发送数据 API 基本上肯定要发送**响应体**,但是客户端不一定发送**请求体**。 -使用 Pydantic 模型声明**请求体**,能充分利用它的功能和优点。 +使用 Pydantic 模型声明**请求体**,能充分利用它的功能和优点。 !!! info "说明" @@ -20,9 +20,17 @@ API 基本上肯定要发送**响应体**,但是客户端不一定发送**请 从 `pydantic` 中导入 `BaseModel`: -```Python hl_lines="4" -{!../../../docs_src/body/tutorial001.py!} -``` +=== "Python 3.10+" + + ```Python hl_lines="2" + {!> ../../../docs_src/body/tutorial001_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="4" + {!> ../../../docs_src/body/tutorial001.py!} + ``` ## 创建数据模型 @@ -30,9 +38,17 @@ API 基本上肯定要发送**响应体**,但是客户端不一定发送**请 使用 Python 标准类型声明所有属性: -```Python hl_lines="7-11" -{!../../../docs_src/body/tutorial001.py!} -``` +=== "Python 3.10+" + + ```Python hl_lines="5-9" + {!> ../../../docs_src/body/tutorial001_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="7-11" + {!> ../../../docs_src/body/tutorial001.py!} + ``` 与声明查询参数一样,包含默认值的模型属性是可选的,否则就是必选的。默认值为 `None` 的模型属性也是可选的。 @@ -60,9 +76,17 @@ API 基本上肯定要发送**响应体**,但是客户端不一定发送**请 使用与声明路径和查询参数相同的方式声明请求体,把请求体添加至*路径操作*: -```Python hl_lines="18" -{!../../../docs_src/body/tutorial001.py!} -``` +=== "Python 3.10+" + + ```Python hl_lines="16" + {!> ../../../docs_src/body/tutorial001_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="18" + {!> ../../../docs_src/body/tutorial001.py!} + ``` ……此处,请求体参数的类型为 `Item` 模型。 @@ -127,9 +151,17 @@ Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文 在*路径操作*函数内部直接访问模型对象的属性: -```Python hl_lines="21" -{!../../../docs_src/body/tutorial002.py!} -``` +=== "Python 3.10+" + + ```Python hl_lines="19" + {!> ../../../docs_src/body/tutorial002_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="21" + {!> ../../../docs_src/body/tutorial002.py!} + ``` ## 请求体 + 路径参数 @@ -137,9 +169,17 @@ Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文 **FastAPI** 能识别与**路径参数**匹配的函数参数,还能识别从**请求体**中获取的类型为 Pydantic 模型的函数参数。 -```Python hl_lines="17-18" -{!../../../docs_src/body/tutorial003.py!} -``` +=== "Python 3.10+" + + ```Python hl_lines="15-16" + {!> ../../../docs_src/body/tutorial003_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="17-18" + {!> ../../../docs_src/body/tutorial003.py!} + ``` ## 请求体 + 路径参数 + 查询参数 @@ -147,9 +187,17 @@ Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文 **FastAPI** 能够正确识别这三种参数,并从正确的位置获取数据。 -```Python hl_lines="18" -{!../../../docs_src/body/tutorial004.py!} -``` +=== "Python 3.10+" + + ```Python hl_lines="16" + {!> ../../../docs_src/body/tutorial004_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="18" + {!> ../../../docs_src/body/tutorial004.py!} + ``` 函数参数按如下规则进行识别: diff --git a/docs/zh/docs/tutorial/cookie-params.md b/docs/zh/docs/tutorial/cookie-params.md index d67daf0f9051e..8571422ddf725 100644 --- a/docs/zh/docs/tutorial/cookie-params.md +++ b/docs/zh/docs/tutorial/cookie-params.md @@ -1,34 +1,100 @@ # Cookie 参数 -你可以像定义 `Query` 参数和 `Path` 参数一样来定义 `Cookie` 参数。 + 定义 `Cookie` 参数与定义 `Query` 和 `Path` 参数一样。 ## 导入 `Cookie` -首先,导入 `Cookie`: +首先,导入 `Cookie`: -```Python hl_lines="3" -{!../../../docs_src/cookie_params/tutorial001.py!} -``` +=== "Python 3.10+" + + ```Python hl_lines="3" + {!> ../../../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.8+" + + ```Python hl_lines="3" + {!> ../../../docs_src/cookie_params/tutorial001_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip + 尽可能选择使用 `Annotated` 的版本。 + + ```Python hl_lines="1" + {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + 尽可能选择使用 `Annotated` 的版本。 + + ```Python hl_lines="3" + {!> ../../../docs_src/cookie_params/tutorial001.py!} + ``` ## 声明 `Cookie` 参数 -声明 `Cookie` 参数的结构与声明 `Query` 参数和 `Path` 参数时相同。 +声明 `Cookie` 参数的方式与声明 `Query` 和 `Path` 参数相同。 + +第一个值是默认值,还可以传递所有验证参数或注释参数: -第一个值是参数的默认值,同时也可以传递所有验证参数或注释参数,来校验参数: +=== "Python 3.10+" -```Python hl_lines="9" -{!../../../docs_src/cookie_params/tutorial001.py!} -``` + ```Python hl_lines="9" + {!> ../../../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.8+" + + ```Python hl_lines="10" + {!> ../../../docs_src/cookie_params/tutorial001_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip + 尽可能选择使用 `Annotated` 的版本。 + + ```Python hl_lines="7" + {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + 尽可能选择使用 `Annotated` 的版本。 + + ```Python hl_lines="9" + {!> ../../../docs_src/cookie_params/tutorial001.py!} + ``` !!! note "技术细节" - `Cookie` 、`Path` 、`Query`是兄弟类,它们都继承自公共的 `Param` 类 - 但请记住,当你从 `fastapi` 导入的 `Query`、`Path`、`Cookie` 或其他参数声明函数,这些实际上是返回特殊类的函数。 + `Cookie` 、`Path` 、`Query` 是**兄弟类**,都继承自共用的 `Param` 类。 + + 注意,从 `fastapi` 导入的 `Query`、`Path`、`Cookie` 等对象,实际上是返回特殊类的函数。 + +!!! info "说明" -!!! info - 你需要使用 `Cookie` 来声明 cookie 参数,否则参数将会被解释为查询参数。 + 必须使用 `Cookie` 声明 cookie 参数,否则该参数会被解释为查询参数。 -## 总结 +## 小结 -使用 `Cookie` 声明 cookie 参数,使用方式与 `Query` 和 `Path` 类似。 +使用 `Cookie` 声明 cookie 参数的方式与 `Query` 和 `Path` 相同。 diff --git a/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md index f404820df0119..1866da29842b5 100644 --- a/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md @@ -12,7 +12,7 @@ {!> ../../../docs_src/dependencies/tutorial001_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9" {!> ../../../docs_src/dependencies/tutorial001.py!} @@ -85,7 +85,7 @@ fluffy = Cat(name="Mr Fluffy") {!> ../../../docs_src/dependencies/tutorial002_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="11-15" {!> ../../../docs_src/dependencies/tutorial002.py!} diff --git a/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md new file mode 100644 index 0000000000000..e24b9409f6160 --- /dev/null +++ b/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md @@ -0,0 +1,253 @@ +# 使用yield的依赖项 + +FastAPI支持在完成后执行一些额外步骤的依赖项. + +为此,请使用 `yield` 而不是 `return`,然后再编写额外的步骤(代码)。 + +!!! 提示 + 确保只使用一次 `yield` 。 + +!!! 注意 "技术细节" + + 任何一个可以与以下内容一起使用的函数: + + * `@contextlib.contextmanager` 或者 + * `@contextlib.asynccontextmanager` + + 都可以作为 **FastAPI** 的依赖项。 + + 实际上,FastAPI内部就使用了这两个装饰器。 + + +## 使用 `yield` 的数据库依赖项 + +例如,您可以使用这种方式创建一个数据库会话,并在完成后关闭它。 + +在发送响应之前,只会执行 `yield` 语句及之前的代码: + +```Python hl_lines="2-4" +{!../../../docs_src/dependencies/tutorial007.py!} +``` + +生成的值会注入到*路径操作*和其他依赖项中: + +```Python hl_lines="4" +{!../../../docs_src/dependencies/tutorial007.py!} +``` + +"yield"语句后面的代码会在发送响应后执行:: + +```Python hl_lines="5-6" +{!../../../docs_src/dependencies/tutorial007.py!} +``` + +!!! 提示 + + 您可以使用 `async` 或普通函数。 + + **FastAPI** 会像处理普通依赖关系一样,对每个依赖关系做正确的处理。 + +## 同时包含了 `yield` 和 `try` 的依赖项 + +如果在带有 `yield` 的依赖关系中使用 `try` 代码块,就会收到使用依赖关系时抛出的任何异常。 + +例如,如果中间某个代码在另一个依赖中或在*路径操作*中使数据库事务 "回滚 "或产生任何其他错误,您就会在依赖中收到异常。 + +因此,你可以使用 `except SomeException` 在依赖关系中查找特定的异常。 + +同样,您也可以使用 `finally` 来确保退出步骤得到执行,无论是否存在异常。 + +```Python hl_lines="3 5" +{!../../../docs_src/dependencies/tutorial007.py!} +``` +## 使用`yield`的子依赖项 + +你可以拥有任意大小和形状的子依赖和子依赖的“树”,而且它们中的任何一个或所有的都可以使用`yield`。 + +**FastAPI** 会确保每个带有`yield`的依赖中的“退出代码”按正确顺序运行。 + +例如,`dependency_c` 可以依赖于 `dependency_b`,而 `dependency_b` 则依赖于 `dependency_a`。 + +=== "Python 3.9+" + + ```Python hl_lines="6 14 22" + {!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="5 13 21" + {!> ../../../docs_src/dependencies/tutorial008_an.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + 如果可能,请尽量使用“ Annotated”版本。 + + ```Python hl_lines="4 12 20" + {!> ../../../docs_src/dependencies/tutorial008.py!} + ``` + +所有这些依赖都可以使用`yield`。 + +在这种情况下,`dependency_c` 在执行其退出代码时需要`dependency_b`(此处称为 `dep_b`)的值仍然可用。 + +而`dependency_b` 反过来则需要`dependency_a`(此处称为 `dep_a`)的值在其退出代码中可用。 + +=== "Python 3.9+" + + ```Python hl_lines="18-19 26-27" + {!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="17-18 25-26" + {!> ../../../docs_src/dependencies/tutorial008_an.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + 如果可能,请尽量使用“ Annotated”版本。 + + ```Python hl_lines="16-17 24-25" + {!> ../../../docs_src/dependencies/tutorial008.py!} + ``` + +同样,你可以有混合了`yield`和`return`的依赖。 + +你也可以有一个单一的依赖需要多个其他带有`yield`的依赖,等等。 + +你可以拥有任何你想要的依赖组合。 + +**FastAPI** 将确保按正确的顺序运行所有内容。 + +!!! note "技术细节" + + 这是由 Python 的上下文管理器完成的。 + + **FastAPI** 在内部使用它们来实现这一点。 + + +## 使用 `yield` 和 `HTTPException` 的依赖项 + +您看到可以使用带有 `yield` 的依赖项,并且具有捕获异常的 `try` 块。 + +在 `yield` 后抛出 `HTTPException` 或类似的异常是很诱人的,但是**这不起作用**。 + +带有`yield`的依赖中的退出代码在响应发送之后执行,因此[异常处理程序](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}已经运行过。没有任何东西可以捕获退出代码(在`yield`之后)中的依赖抛出的异常。 + +所以,如果在`yield`之后抛出`HTTPException`,默认(或任何自定义)异常处理程序捕获`HTTPException`并返回HTTP 400响应的机制将不再能够捕获该异常。 + +这就是允许在依赖中设置的任何东西(例如数据库会话(DB session))可以被后台任务使用的原因。 + +后台任务在响应发送之后运行。因此,无法触发`HTTPException`,因为甚至没有办法更改*已发送*的响应。 + +但如果后台任务产生了数据库错误,至少你可以在带有`yield`的依赖中回滚或清理关闭会话,并且可能记录错误或将其报告给远程跟踪系统。 + +如果你知道某些代码可能会引发异常,那就做最“Pythonic”的事情,就是在代码的那部分添加一个`try`块。 + +如果你有自定义异常,希望在返回响应之前处理,并且可能修改响应甚至触发`HTTPException`,可以创建[自定义异常处理程序](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}。 + +!!! tip + + 在`yield`之前仍然可以引发包括`HTTPException`在内的异常,但在`yield`之后则不行。 + +执行的顺序大致如下图所示。时间从上到下流动。每列都是相互交互或执行代码的其中一部分。 + +```mermaid +sequenceDiagram + +participant client as Client +participant handler as Exception handler +participant dep as Dep with yield +participant operation as Path Operation +participant tasks as Background tasks + + Note over client,tasks: Can raise exception for dependency, handled after response is sent + Note over client,operation: Can raise HTTPException and can change the response + client ->> dep: Start request + Note over dep: Run code up to yield + opt raise + dep -->> handler: Raise HTTPException + handler -->> client: HTTP error response + dep -->> dep: Raise other exception + end + dep ->> operation: Run dependency, e.g. DB session + opt raise + operation -->> dep: Raise HTTPException + dep -->> handler: Auto forward exception + handler -->> client: HTTP error response + operation -->> dep: Raise other exception + dep -->> handler: Auto forward exception + end + operation ->> client: Return response to client + Note over client,operation: Response is already sent, can't change it anymore + opt Tasks + operation -->> tasks: Send background tasks + end + opt Raise other exception + tasks -->> dep: Raise other exception + end + Note over dep: After yield + opt Handle other exception + dep -->> dep: Handle exception, can't change response. E.g. close DB session. + end +``` + +!!! info + 只会向客户端发送**一次响应**,可能是一个错误响应之一,也可能是来自*路径操作*的响应。 + + 在发送了其中一个响应之后,就无法再发送其他响应了。 + +!!! tip + 这个图表展示了`HTTPException`,但你也可以引发任何其他你创建了[自定义异常处理程序](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}的异常。 + + 如果你引发任何异常,它将传递给带有`yield`的依赖,包括`HTTPException`,然后**再次**传递给异常处理程序。如果没有针对该异常的异常处理程序,那么它将被默认的内部`ServerErrorMiddleware`处理,返回500 HTTP状态码,告知客户端服务器发生了错误。 + +## 上下文管理器 + +### 什么是“上下文管理器” + +“上下文管理器”是您可以在`with`语句中使用的任何Python对象。 + +例如,您可以使用`with`读取文件: + +```Python +with open("./somefile.txt") as f: + contents = f.read() + print(contents) +``` + +在底层,`open("./somefile.txt")`创建了一个被称为“上下文管理器”的对象。 + +当`with`块结束时,它会确保关闭文件,即使发生了异常也是如此。 + +当你使用`yield`创建一个依赖项时,**FastAPI**会在内部将其转换为上下文管理器,并与其他相关工具结合使用。 + +### 在依赖项中使用带有`yield`的上下文管理器 + +!!! warning + 这是一个更为“高级”的想法。 + + 如果您刚开始使用**FastAPI**,您可能暂时可以跳过它。 + +在Python中,你可以通过创建一个带有`__enter__()`和`__exit__()`方法的类来创建上下文管理器。 + +你也可以在**FastAPI**的依赖项中使用带有`yield`的`with`或`async with`语句,通过在依赖函数内部使用它们。 + +```Python hl_lines="1-9 13" +{!../../../docs_src/dependencies/tutorial010.py!} +``` + +!!! tip + 另一种创建上下文管理器的方法是: + + * `@contextlib.contextmanager`或者 + * `@contextlib.asynccontextmanager` + + 使用上下文管理器装饰一个只有单个`yield`的函数。这就是**FastAPI**在内部用于带有`yield`的依赖项的方式。 + + 但是你不需要为FastAPI的依赖项使用这些装饰器(而且也不应该)。FastAPI会在内部为你处理这些。 diff --git a/docs/zh/docs/tutorial/encoder.md b/docs/zh/docs/tutorial/encoder.md index 76ed846ce35e4..859ebc2e87cc7 100644 --- a/docs/zh/docs/tutorial/encoder.md +++ b/docs/zh/docs/tutorial/encoder.md @@ -26,7 +26,7 @@ {!> ../../../docs_src/encoder/tutorial001_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="5 22" {!> ../../../docs_src/encoder/tutorial001.py!} diff --git a/docs/zh/docs/tutorial/extra-data-types.md b/docs/zh/docs/tutorial/extra-data-types.md index ac3e076545f48..cf39de0dd8e04 100644 --- a/docs/zh/docs/tutorial/extra-data-types.md +++ b/docs/zh/docs/tutorial/extra-data-types.md @@ -36,7 +36,7 @@ * `datetime.timedelta`: * 一个 Python `datetime.timedelta`. * 在请求和响应中将表示为 `float` 代表总秒数。 - * Pydantic 也允许将其表示为 "ISO 8601 时间差异编码", 查看文档了解更多信息。 + * Pydantic 也允许将其表示为 "ISO 8601 时间差异编码", 查看文档了解更多信息。 * `frozenset`: * 在请求和响应中,作为 `set` 对待: * 在请求中,列表将被读取,消除重复,并将其转换为一个 `set`。 @@ -44,23 +44,87 @@ * 产生的模式将指定那些 `set` 的值是唯一的 (使用 JSON 模式的 `uniqueItems`)。 * `bytes`: * 标准的 Python `bytes`。 - * 在请求和相应中被当作 `str` 处理。 + * 在请求和响应中被当作 `str` 处理。 * 生成的模式将指定这个 `str` 是 `binary` "格式"。 * `Decimal`: * 标准的 Python `Decimal`。 - * 在请求和相应中被当做 `float` 一样处理。 -* 您可以在这里检查所有有效的pydantic数据类型: Pydantic data types. + * 在请求和响应中被当做 `float` 一样处理。 +* 您可以在这里检查所有有效的pydantic数据类型: Pydantic data types. ## 例子 下面是一个*路径操作*的示例,其中的参数使用了上面的一些类型。 -```Python hl_lines="1 3 12-16" -{!../../../docs_src/extra_data_types/tutorial001.py!} -``` +=== "Python 3.10+" + + ```Python hl_lines="1 3 12-16" + {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="1 3 12-16" + {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="1 3 13-17" + {!> ../../../docs_src/extra_data_types/tutorial001_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip + 尽可能选择使用 `Annotated` 的版本。 + + ```Python hl_lines="1 2 11-15" + {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + 尽可能选择使用 `Annotated` 的版本。 + + ```Python hl_lines="1 2 12-16" + {!> ../../../docs_src/extra_data_types/tutorial001.py!} + ``` 注意,函数内的参数有原生的数据类型,你可以,例如,执行正常的日期操作,如: -```Python hl_lines="18-19" -{!../../../docs_src/extra_data_types/tutorial001.py!} -``` +=== "Python 3.10+" + + ```Python hl_lines="18-19" + {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="18-19" + {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="19-20" + {!> ../../../docs_src/extra_data_types/tutorial001_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip + 尽可能选择使用 `Annotated` 的版本。 + + ```Python hl_lines="17-18" + {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + 尽可能选择使用 `Annotated` 的版本。 + + ```Python hl_lines="18-19" + {!> ../../../docs_src/extra_data_types/tutorial001.py!} + ``` diff --git a/docs/zh/docs/tutorial/extra-models.md b/docs/zh/docs/tutorial/extra-models.md index 1fbe77be8de70..f89d58dd12c6c 100644 --- a/docs/zh/docs/tutorial/extra-models.md +++ b/docs/zh/docs/tutorial/extra-models.md @@ -17,9 +17,17 @@ 下面是应该如何根据它们的密码字段以及使用位置去定义模型的大概思路: -```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" -{!../../../docs_src/extra_models/tutorial001.py!} -``` +=== "Python 3.10+" + + ```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" + {!> ../../../docs_src/extra_models/tutorial001_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" + {!> ../../../docs_src/extra_models/tutorial001.py!} + ``` ### 关于 `**user_in.dict()` @@ -150,9 +158,17 @@ UserInDB( 这样,我们可以仅声明模型之间的差异部分(具有明文的 `password`、具有 `hashed_password` 以及不包括密码)。 -```Python hl_lines="9 15-16 19-20 23-24" -{!../../../docs_src/extra_models/tutorial002.py!} -``` +=== "Python 3.10+" + + ```Python hl_lines="7 13-14 17-18 21-22" + {!> ../../../docs_src/extra_models/tutorial002_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9 15-16 19-20 23-24" + {!> ../../../docs_src/extra_models/tutorial002.py!} + ``` ## `Union` 或者 `anyOf` @@ -164,11 +180,19 @@ UserInDB( !!! note - 定义一个 `Union` 类型时,首先包括最详细的类型,然后是不太详细的类型。在下面的示例中,更详细的 `PlaneItem` 位于 `Union[PlaneItem,CarItem]` 中的 `CarItem` 之前。 + 定义一个 `Union` 类型时,首先包括最详细的类型,然后是不太详细的类型。在下面的示例中,更详细的 `PlaneItem` 位于 `Union[PlaneItem,CarItem]` 中的 `CarItem` 之前。 -```Python hl_lines="1 14-15 18-20 33" -{!../../../docs_src/extra_models/tutorial003.py!} -``` +=== "Python 3.10+" + + ```Python hl_lines="1 14-15 18-20 33" + {!> ../../../docs_src/extra_models/tutorial003_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="1 14-15 18-20 33" + {!> ../../../docs_src/extra_models/tutorial003.py!} + ``` ## 模型列表 @@ -176,9 +200,17 @@ UserInDB( 为此,请使用标准的 Python `typing.List`: -```Python hl_lines="1 20" -{!../../../docs_src/extra_models/tutorial004.py!} -``` +=== "Python 3.9+" + + ```Python hl_lines="18" + {!> ../../../docs_src/extra_models/tutorial004_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="1 20" + {!> ../../../docs_src/extra_models/tutorial004.py!} + ``` ## 任意 `dict` 构成的响应 @@ -188,9 +220,17 @@ UserInDB( 在这种情况下,你可以使用 `typing.Dict`: -```Python hl_lines="1 8" -{!../../../docs_src/extra_models/tutorial005.py!} -``` +=== "Python 3.9+" + + ```Python hl_lines="6" + {!> ../../../docs_src/extra_models/tutorial005_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="1 8" + {!> ../../../docs_src/extra_models/tutorial005.py!} + ``` ## 总结 diff --git a/docs/zh/docs/tutorial/handling-errors.md b/docs/zh/docs/tutorial/handling-errors.md index 9b066bc2cee65..701cd241e40fa 100644 --- a/docs/zh/docs/tutorial/handling-errors.md +++ b/docs/zh/docs/tutorial/handling-errors.md @@ -145,7 +145,7 @@ ``` -访问 `/items/foo`,可以看到以下内容替换了默认 JSON 错误信息: +访问 `/items/foo`,可以看到默认的 JSON 错误信息: ```JSON { @@ -163,7 +163,7 @@ ``` -以下是文本格式的错误信息: +被替换为了以下文本格式的错误信息: ``` 1 validation error @@ -179,7 +179,7 @@ path -> item_id 如果您觉得现在还用不到以下技术细节,可以先跳过下面的内容。 -`RequestValidationError` 是 Pydantic 的 `ValidationError` 的子类。 +`RequestValidationError` 是 Pydantic 的 `ValidationError` 的子类。 **FastAPI** 调用的就是 `RequestValidationError` 类,因此,如果在 `response_model` 中使用 Pydantic 模型,且数据有错误时,在日志中就会看到这个错误。 diff --git a/docs/zh/docs/tutorial/header-params.md b/docs/zh/docs/tutorial/header-params.md index c4b1c38ceecc8..25dfeba87ac88 100644 --- a/docs/zh/docs/tutorial/header-params.md +++ b/docs/zh/docs/tutorial/header-params.md @@ -1,79 +1,219 @@ # Header 参数 -你可以使用定义 `Query`, `Path` 和 `Cookie` 参数一样的方法定义 Header 参数。 +定义 `Header` 参数的方式与定义 `Query`、`Path`、`Cookie` 参数相同。 ## 导入 `Header` -首先导入 `Header`: +首先,导入 `Header`: -```Python hl_lines="3" -{!../../../docs_src/header_params/tutorial001.py!} -``` +=== "Python 3.10+" + + ```Python hl_lines="3" + {!> ../../../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.8+" + + ```Python hl_lines="3" + {!> ../../../docs_src/header_params/tutorial001_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip + 尽可能选择使用 `Annotated` 的版本。 + + ```Python hl_lines="1" + {!> ../../../docs_src/header_params/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + 尽可能选择使用 `Annotated` 的版本。 + + ```Python hl_lines="3" + {!> ../../../docs_src/header_params/tutorial001.py!} + ``` ## 声明 `Header` 参数 -然后使用和`Path`, `Query` and `Cookie` 一样的结构定义 header 参数 +然后,使用和 `Path`、`Query`、`Cookie` 一样的结构定义 header 参数。 -第一个值是默认值,你可以传递所有的额外验证或注释参数: +第一个值是默认值,还可以传递所有验证参数或注释参数: -```Python hl_lines="9" -{!../../../docs_src/header_params/tutorial001.py!} -``` +=== "Python 3.10+" + + ```Python hl_lines="9" + {!> ../../../docs_src/header_params/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="9" + {!> ../../../docs_src/header_params/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="10" + {!> ../../../docs_src/header_params/tutorial001_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip + 尽可能选择使用 `Annotated` 的版本。 + + ```Python hl_lines="7" + {!> ../../../docs_src/header_params/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + 尽可能选择使用 `Annotated` 的版本。 + + ```Python hl_lines="9" + {!> ../../../docs_src/header_params/tutorial001.py!} + ``` !!! note "技术细节" - `Header` 是 `Path`, `Query` 和 `Cookie` 的兄弟类型。它也继承自通用的 `Param` 类. - 但是请记得,当你从`fastapi`导入 `Query`, `Path`, `Header`, 或其他时,实际上导入的是返回特定类型的函数。 + `Header` 是 `Path`、`Query`、`Cookie` 的**兄弟类**,都继承自共用的 `Param` 类。 -!!! info - 为了声明headers, 你需要使用`Header`, 因为否则参数将被解释为查询参数。 + 注意,从 `fastapi` 导入的 `Query`、`Path`、`Header` 等对象,实际上是返回特殊类的函数。 + +!!! info "说明" + + 必须使用 `Header` 声明 header 参数,否则该参数会被解释为查询参数。 ## 自动转换 -`Header` 在 `Path`, `Query` 和 `Cookie` 提供的功能之上有一点额外的功能。 +`Header` 比 `Path`、`Query` 和 `Cookie` 提供了更多功能。 -大多数标准的headers用 "连字符" 分隔,也称为 "减号" (`-`)。 +大部分标准请求头用**连字符**分隔,即**减号**(`-`)。 -但是像 `user-agent` 这样的变量在Python中是无效的。 +但是 `user-agent` 这样的变量在 Python 中是无效的。 -因此, 默认情况下, `Header` 将把参数名称的字符从下划线 (`_`) 转换为连字符 (`-`) 来提取并记录 headers. +因此,默认情况下,`Header` 把参数名中的字符由下划线(`_`)改为连字符(`-`)来提取并存档请求头 。 -同时,HTTP headers 是大小写不敏感的,因此,因此可以使用标准Python样式(也称为 "snake_case")声明它们。 +同时,HTTP 的请求头不区分大小写,可以使用 Python 标准样式(即 **snake_case**)进行声明。 -因此,您可以像通常在Python代码中那样使用 `user_agent` ,而不需要将首字母大写为 `User_Agent` 或类似的东西。 +因此,可以像在 Python 代码中一样使用 `user_agent` ,无需把首字母大写为 `User_Agent` 等形式。 -如果出于某些原因,你需要禁用下划线到连字符的自动转换,设置`Header`的参数 `convert_underscores` 为 `False`: +如需禁用下划线自动转换为连字符,可以把 `Header` 的 `convert_underscores` 参数设置为 `False`: -```Python hl_lines="10" -{!../../../docs_src/header_params/tutorial002.py!} -``` +=== "Python 3.10+" -!!! warning - 在设置 `convert_underscores` 为 `False` 之前,请记住,一些HTTP代理和服务器不允许使用带有下划线的headers。 + ```Python hl_lines="10" + {!> ../../../docs_src/header_params/tutorial002_an_py310.py!} + ``` +=== "Python 3.9+" -## 重复的 headers + ```Python hl_lines="11" + {!> ../../../docs_src/header_params/tutorial002_an_py39.py!} + ``` -有可能收到重复的headers。这意味着,相同的header具有多个值。 +=== "Python 3.8+" -您可以在类型声明中使用一个list来定义这些情况。 + ```Python hl_lines="12" + {!> ../../../docs_src/header_params/tutorial002_an.py!} + ``` -你可以通过一个Python `list` 的形式获得重复header的所有值。 +=== "Python 3.10+ non-Annotated" -比如, 为了声明一个 `X-Token` header 可以出现多次,你可以这样写: + !!! tip + 尽可能选择使用 `Annotated` 的版本。 -```Python hl_lines="9" -{!../../../docs_src/header_params/tutorial003.py!} -``` + ```Python hl_lines="8" + {!> ../../../docs_src/header_params/tutorial002_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + 尽可能选择使用 `Annotated` 的版本。 + + ```Python hl_lines="10" + {!> ../../../docs_src/header_params/tutorial002.py!} + ``` + +!!! warning "警告" + + 注意,使用 `convert_underscores = False` 要慎重,有些 HTTP 代理和服务器不支持使用带有下划线的请求头。 + + +## 重复的请求头 + +有时,可能需要接收重复的请求头。即同一个请求头有多个值。 + +类型声明中可以使用 `list` 定义多个请求头。 + +使用 Python `list` 可以接收重复请求头所有的值。 + +例如,声明 `X-Token` 多次出现的请求头,可以写成这样: + +=== "Python 3.10+" + + ```Python hl_lines="9" + {!> ../../../docs_src/header_params/tutorial003_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="9" + {!> ../../../docs_src/header_params/tutorial003_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="10" + {!> ../../../docs_src/header_params/tutorial003_an.py!} + ``` + +=== "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 + 尽可能选择使用 `Annotated` 的版本。 + + ```Python hl_lines="9" + {!> ../../../docs_src/header_params/tutorial003_py39.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + 尽可能选择使用 `Annotated` 的版本。 + + ```Python hl_lines="9" + {!> ../../../docs_src/header_params/tutorial003.py!} + ``` -如果你与*路径操作*通信时发送两个HTTP headers,就像: +与*路径操作*通信时,以下面的方式发送两个 HTTP 请求头: ``` X-Token: foo X-Token: bar ``` -响应会是: +响应结果是: ```JSON { @@ -84,8 +224,8 @@ X-Token: bar } ``` -## 回顾 +## 小结 -使用 `Header` 来声明 header , 使用和 `Query`, `Path` 与 `Cookie` 相同的模式。 +使用 `Header` 声明请求头的方式与 `Query`、`Path` 、`Cookie` 相同。 -不用担心变量中的下划线,**FastAPI** 会负责转换它们。 +不用担心变量中的下划线,**FastAPI** 可以自动转换。 diff --git a/docs/zh/docs/tutorial/metadata.md b/docs/zh/docs/tutorial/metadata.md index 3e669bc72fa24..09b106273c58c 100644 --- a/docs/zh/docs/tutorial/metadata.md +++ b/docs/zh/docs/tutorial/metadata.md @@ -1,40 +1,35 @@ # 元数据和文档 URL +你可以在 FastAPI 应用程序中自定义多个元数据配置。 -你可以在 **FastAPI** 应用中自定义几个元数据配置。 +## API 元数据 -## 标题、描述和版本 +你可以在设置 OpenAPI 规范和自动 API 文档 UI 中使用的以下字段: -你可以设定: +| 参数 | 类型 | 描述 | +|------------|------|-------------| +| `title` | `str` | API 的标题。 | +| `summary` | `str` | API 的简短摘要。 自 OpenAPI 3.1.0、FastAPI 0.99.0 起可用。. | +| `description` | `str` | API 的简短描述。可以使用Markdown。 | +| `version` | `string` | API 的版本。这是您自己的应用程序的版本,而不是 OpenAPI 的版本。例如 `2.5.0` 。 | +| `terms_of_service` | `str` | API 服务条款的 URL。如果提供,则必须是 URL。 | +| `contact` | `dict` | 公开的 API 的联系信息。它可以包含多个字段。
contact 字段
参数Type描述
namestr联系人/组织的识别名称。
urlstr指向联系信息的 URL。必须采用 URL 格式。
emailstr联系人/组织的电子邮件地址。必须采用电子邮件地址的格式。
| +| `license_info` | `dict` | 公开的 API 的许可证信息。它可以包含多个字段。
license_info 字段
参数类型描述
namestr必须的 (如果设置了license_info). 用于 API 的许可证名称。
identifierstr一个API的SPDX许可证表达。 The identifier field is mutually exclusive of the url field. 自 OpenAPI 3.1.0、FastAPI 0.99.0 起可用。
urlstr用于 API 的许可证的 URL。必须采用 URL 格式。
| -* **Title**:在 OpenAPI 和自动 API 文档用户界面中作为 API 的标题/名称使用。 -* **Description**:在 OpenAPI 和自动 API 文档用户界面中用作 API 的描述。 -* **Version**:API 版本,例如 `v2` 或者 `2.5.0`。 - * 如果你之前的应用程序版本也使用 OpenAPI 会很有用。 - -使用 `title`、`description` 和 `version` 来设置它们: +你可以按如下方式设置它们: ```Python hl_lines="4-6" {!../../../docs_src/metadata/tutorial001.py!} ``` +!!! tip + 您可以在 `description` 字段中编写 Markdown,它将在输出中呈现。 + 通过这样设置,自动 API 文档看起来会像: ## 标签元数据 -你也可以使用参数 `openapi_tags`,为用于分组路径操作的不同标签添加额外的元数据。 - -它接受一个列表,这个列表包含每个标签对应的一个字典。 - -每个字典可以包含: - -* `name`(**必要**):一个 `str`,它与*路径操作*和 `APIRouter` 中使用的 `tags` 参数有相同的标签名。 -* `description`:一个用于简短描述标签的 `str`。它支持 Markdown 并且会在文档用户界面中显示。 -* `externalDocs`:一个描述外部文档的 `dict`: - * `description`:用于简短描述外部文档的 `str`。 - * `url`(**必要**):外部文档的 URL `str`。 - ### 创建标签元数据 让我们在带有标签的示例中为 `users` 和 `items` 试一下。 diff --git a/docs/zh/docs/tutorial/path-params-numeric-validations.md b/docs/zh/docs/tutorial/path-params-numeric-validations.md index 13512a08edf06..9b41ad7cf4f18 100644 --- a/docs/zh/docs/tutorial/path-params-numeric-validations.md +++ b/docs/zh/docs/tutorial/path-params-numeric-validations.md @@ -6,9 +6,41 @@ 首先,从 `fastapi` 导入 `Path`: -```Python hl_lines="1" -{!../../../docs_src/path_params_numeric_validations/tutorial001.py!} -``` +=== "Python 3.10+" + + ```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.8+" + + ```Python hl_lines="3-4" + {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip + 尽可能选择使用 `Annotated` 的版本。 + + ```Python hl_lines="1" + {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + 尽可能选择使用 `Annotated` 的版本。 + + ```Python hl_lines="3" + {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} + ``` ## 声明元数据 @@ -16,9 +48,41 @@ 例如,要声明路径参数 `item_id`的 `title` 元数据值,你可以输入: -```Python hl_lines="8" -{!../../../docs_src/path_params_numeric_validations/tutorial001.py!} -``` +=== "Python 3.10+" + + ```Python hl_lines="10" + {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="10" + {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="11" + {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip + 尽可能选择使用 `Annotated` 的版本。 + + ```Python hl_lines="8" + {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + 尽可能选择使用 `Annotated` 的版本。 + + ```Python hl_lines="10" + {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} + ``` !!! note 路径参数总是必需的,因为它必须是路径的一部分。 @@ -43,9 +107,14 @@ 因此,你可以将函数声明为: -```Python hl_lines="7" -{!../../../docs_src/path_params_numeric_validations/tutorial002.py!} -``` +=== "Python 3.8 non-Annotated" + + !!! tip + 尽可能选择使用 `Annotated` 的版本。 + + ```Python hl_lines="7" + {!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!} + ``` ## 按需对参数排序的技巧 diff --git a/docs/zh/docs/tutorial/path-params.md b/docs/zh/docs/tutorial/path-params.md index 1b428d6627112..5bb4eba8054d4 100644 --- a/docs/zh/docs/tutorial/path-params.md +++ b/docs/zh/docs/tutorial/path-params.md @@ -93,7 +93,7 @@ ## Pydantic -所有的数据校验都由 Pydantic 在幕后完成,所以你可以从它所有的优点中受益。并且你知道它在这方面非常胜任。 +所有的数据校验都由 Pydantic 在幕后完成,所以你可以从它所有的优点中受益。并且你知道它在这方面非常胜任。 你可以使用同样的类型声明来声明 `str`、`float`、`bool` 以及许多其他的复合数据类型。 diff --git a/docs/zh/docs/tutorial/query-params-str-validations.md b/docs/zh/docs/tutorial/query-params-str-validations.md index 070074839f634..af0428837e2fa 100644 --- a/docs/zh/docs/tutorial/query-params-str-validations.md +++ b/docs/zh/docs/tutorial/query-params-str-validations.md @@ -4,9 +4,17 @@ 让我们以下面的应用程序为例: -```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial001.py!} -``` +=== "Python 3.10+" + + ```Python hl_lines="7" + {!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9" + {!> ../../../docs_src/query_params_str_validations/tutorial001.py!} + ``` 查询参数 `q` 的类型为 `str`,默认值为 `None`,因此它是可选的。 @@ -144,7 +152,7 @@ q: Union[str, None] = Query(default=None, min_length=3) ``` !!! tip - Pydantic 是 FastAPI 中所有数据验证和序列化的核心,当你在没有设默认值的情况下使用 `Optional` 或 `Union[Something, None]` 时,它具有特殊行为,你可以在 Pydantic 文档中阅读有关必需可选字段的更多信息。 + Pydantic 是 FastAPI 中所有数据验证和序列化的核心,当你在没有设默认值的情况下使用 `Optional` 或 `Union[Something, None]` 时,它具有特殊行为,你可以在 Pydantic 文档中阅读有关必需可选字段的更多信息。 ### 使用Pydantic中的`Required`代替省略号(`...`) diff --git a/docs/zh/docs/tutorial/query-params.md b/docs/zh/docs/tutorial/query-params.md index b1668a2d2523f..a0cc7fea39310 100644 --- a/docs/zh/docs/tutorial/query-params.md +++ b/docs/zh/docs/tutorial/query-params.md @@ -63,9 +63,18 @@ http://127.0.0.1:8000/items/?skip=20 通过同样的方式,你可以将它们的默认值设置为 `None` 来声明可选查询参数: -```Python hl_lines="7" -{!../../../docs_src/query_params/tutorial002.py!} -``` +=== "Python 3.10+" + + ```Python hl_lines="7" + {!> ../../../docs_src/query_params/tutorial002_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9" + {!> ../../../docs_src/query_params/tutorial002.py!} + ``` + 在这个例子中,函数参数 `q` 将是可选的,并且默认值为 `None`。 diff --git a/docs/zh/docs/tutorial/request-files.md b/docs/zh/docs/tutorial/request-files.md index 03474907ee94b..1cd3518cfb016 100644 --- a/docs/zh/docs/tutorial/request-files.md +++ b/docs/zh/docs/tutorial/request-files.md @@ -6,7 +6,7 @@ 因为上传文件以「表单数据」形式发送。 - 所以接收上传文件,要预先安装 `python-multipart`。 + 所以接收上传文件,要预先安装 `python-multipart`。 例如: `pip install python-multipart`。 @@ -130,7 +130,7 @@ contents = myfile.file.read() {!> ../../../docs_src/request_files/tutorial001_02_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9 17" {!> ../../../docs_src/request_files/tutorial001_02.py!} @@ -158,7 +158,7 @@ FastAPI 支持同时上传多个文件。 {!> ../../../docs_src/request_files/tutorial002_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="10 15" {!> ../../../docs_src/request_files/tutorial002.py!} @@ -183,7 +183,7 @@ FastAPI 支持同时上传多个文件。 {!> ../../../docs_src/request_files/tutorial003_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="18" {!> ../../../docs_src/request_files/tutorial003.py!} diff --git a/docs/zh/docs/tutorial/request-forms-and-files.md b/docs/zh/docs/tutorial/request-forms-and-files.md index 70cd70f98650c..f58593669229f 100644 --- a/docs/zh/docs/tutorial/request-forms-and-files.md +++ b/docs/zh/docs/tutorial/request-forms-and-files.md @@ -4,7 +4,7 @@ FastAPI 支持同时使用 `File` 和 `Form` 定义文件和表单字段。 !!! info "说明" - 接收上传文件或表单数据,要预先安装 `python-multipart`。 + 接收上传文件或表单数据,要预先安装 `python-multipart`。 例如,`pip install python-multipart`。 diff --git a/docs/zh/docs/tutorial/request-forms.md b/docs/zh/docs/tutorial/request-forms.md index 6436ffbcdc26e..e4fcd88ff02e5 100644 --- a/docs/zh/docs/tutorial/request-forms.md +++ b/docs/zh/docs/tutorial/request-forms.md @@ -4,7 +4,7 @@ !!! info "说明" - 要使用表单,需预先安装 `python-multipart`。 + 要使用表单,需预先安装 `python-multipart`。 例如,`pip install python-multipart`。 diff --git a/docs/zh/docs/tutorial/response-model.md b/docs/zh/docs/tutorial/response-model.md index ea3d0666ded6e..0f1b3b4b919a4 100644 --- a/docs/zh/docs/tutorial/response-model.md +++ b/docs/zh/docs/tutorial/response-model.md @@ -8,9 +8,23 @@ * `@app.delete()` * 等等。 -```Python hl_lines="17" -{!../../../docs_src/response_model/tutorial001.py!} -``` +=== "Python 3.10+" + + ```Python hl_lines="17 22 24-27" + {!> ../../../docs_src/response_model/tutorial001_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="17 22 24-27" + {!> ../../../docs_src/response_model/tutorial001_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="17 22 24-27" + {!> ../../../docs_src/response_model/tutorial001.py!} + ``` !!! note 注意,`response_model`是「装饰器」方法(`get`,`post` 等)的一个参数。不像之前的所有参数和请求体,它不属于*路径操作函数*。 @@ -58,21 +72,45 @@ FastAPI 将使用此 `response_model` 来: 相反,我们可以创建一个有明文密码的输入模型和一个没有明文密码的输出模型: -```Python hl_lines="9 11 16" -{!../../../docs_src/response_model/tutorial003.py!} -``` +=== "Python 3.10+" + + ```Python hl_lines="9 11 16" + {!> ../../../docs_src/response_model/tutorial003_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9 11 16" + {!> ../../../docs_src/response_model/tutorial003.py!} + ``` 这样,即便我们的*路径操作函数*将会返回包含密码的相同输入用户: -```Python hl_lines="24" -{!../../../docs_src/response_model/tutorial003.py!} -``` +=== "Python 3.10+" + + ```Python hl_lines="24" + {!> ../../../docs_src/response_model/tutorial003_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="24" + {!> ../../../docs_src/response_model/tutorial003.py!} + ``` ...我们已经将 `response_model` 声明为了不包含密码的 `UserOut` 模型: -```Python hl_lines="22" -{!../../../docs_src/response_model/tutorial003.py!} -``` +=== "Python 3.10+" + + ```Python hl_lines="22" + {!> ../../../docs_src/response_model/tutorial003_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="22" + {!> ../../../docs_src/response_model/tutorial003.py!} + ``` 因此,**FastAPI** 将会负责过滤掉未在输出模型中声明的所有数据(使用 Pydantic)。 @@ -122,7 +160,7 @@ FastAPI 将使用此 `response_model` 来: ``` !!! info - FastAPI 通过 Pydantic 模型的 `.dict()` 配合 该方法的 `exclude_unset` 参数 来实现此功能。 + FastAPI 通过 Pydantic 模型的 `.dict()` 配合 该方法的 `exclude_unset` 参数 来实现此功能。 !!! info 你还可以使用: @@ -130,7 +168,7 @@ FastAPI 将使用此 `response_model` 来: * `response_model_exclude_defaults=True` * `response_model_exclude_none=True` - 参考 Pydantic 文档 中对 `exclude_defaults` 和 `exclude_none` 的描述。 + 参考 Pydantic 文档 中对 `exclude_defaults` 和 `exclude_none` 的描述。 #### 默认值字段有实际值的数据 diff --git a/docs/zh/docs/tutorial/response-status-code.md b/docs/zh/docs/tutorial/response-status-code.md index 3578319423adc..cc23231b4e9ab 100644 --- a/docs/zh/docs/tutorial/response-status-code.md +++ b/docs/zh/docs/tutorial/response-status-code.md @@ -1,89 +1,95 @@ # 响应状态码 -与指定响应模型的方式相同,你也可以在以下任意的*路径操作*中使用 `status_code` 参数来声明用于响应的 HTTP 状态码: +与指定响应模型的方式相同,在以下任意*路径操作*中,可以使用 `status_code` 参数声明用于响应的 HTTP 状态码: * `@app.get()` * `@app.post()` * `@app.put()` * `@app.delete()` -* 等等。 +* 等…… ```Python hl_lines="6" {!../../../docs_src/response_status_code/tutorial001.py!} ``` -!!! note - 注意,`status_code` 是「装饰器」方法(`get`,`post` 等)的一个参数。不像之前的所有参数和请求体,它不属于*路径操作函数*。 +!!! note "笔记" -`status_code` 参数接收一个表示 HTTP 状态码的数字。 + 注意,`status_code` 是(`get`、`post` 等)**装饰器**方法中的参数。与之前的参数和请求体不同,不是*路径操作函数*的参数。 -!!! info - `status_code` 也能够接收一个 `IntEnum` 类型,比如 Python 的 `http.HTTPStatus`。 +`status_code` 参数接收表示 HTTP 状态码的数字。 -它将会: +!!! info "说明" -* 在响应中返回该状态码。 -* 在 OpenAPI 模式中(以及在用户界面中)将其记录为: + `status_code` 还能接收 `IntEnum` 类型,比如 Python 的 `http.HTTPStatus`。 - +它可以: -!!! note - 一些响应状态码(请参阅下一部分)表示响应没有响应体。 +* 在响应中返回状态码 +* 在 OpenAPI 概图(及用户界面)中存档: - FastAPI 知道这一点,并将生成表明没有响应体的 OpenAPI 文档。 + + +!!! note "笔记" + + 某些响应状态码表示响应没有响应体(参阅下一章)。 + + FastAPI 可以进行识别,并生成表明无响应体的 OpenAPI 文档。 ## 关于 HTTP 状态码 -!!! note - 如果你已经了解什么是 HTTP 状态码,请跳到下一部分。 +!!! note "笔记" -在 HTTP 协议中,你将发送 3 位数的数字状态码作为响应的一部分。 + 如果已经了解 HTTP 状态码,请跳到下一章。 -这些状态码有一个识别它们的关联名称,但是重要的还是数字。 +在 HTTP 协议中,发送 3 位数的数字状态码是响应的一部分。 -简而言之: +这些状态码都具有便于识别的关联名称,但是重要的还是数字。 -* `100` 及以上状态码用于「消息」响应。你很少直接使用它们。具有这些状态代码的响应不能带有响应体。 -* **`200`** 及以上状态码用于「成功」响应。这些是你最常使用的。 - * `200` 是默认状态代码,它表示一切「正常」。 - * 另一个例子会是 `201`,「已创建」。它通常在数据库中创建了一条新记录后使用。 - * 一个特殊的例子是 `204`,「无内容」。此响应在没有内容返回给客户端时使用,因此该响应不能包含响应体。 -* **`300`** 及以上状态码用于「重定向」。具有这些状态码的响应可能有或者可能没有响应体,但 `304`「未修改」是个例外,该响应不得含有响应体。 -* **`400`** 及以上状态码用于「客户端错误」响应。这些可能是你第二常使用的类型。 - * 一个例子是 `404`,用于「未找到」响应。 - * 对于来自客户端的一般错误,你可以只使用 `400`。 -* `500` 及以上状态码用于服务器端错误。你几乎永远不会直接使用它们。当你的应用程序代码或服务器中的某些部分出现问题时,它将自动返回这些状态代码之一。 +简言之: -!!! tip - 要了解有关每个状态代码以及适用场景的更多信息,请查看 MDN 关于 HTTP 状态码的文档。 +* `100` 及以上的状态码用于返回**信息**。这类状态码很少直接使用。具有这些状态码的响应不能包含响应体 +* **`200`** 及以上的状态码用于表示**成功**。这些状态码是最常用的 + * `200` 是默认状态代码,表示一切**正常** + * `201` 表示**已创建**,通常在数据库中创建新记录后使用 + * `204` 是一种特殊的例子,表示**无内容**。该响应在没有为客户端返回内容时使用,因此,该响应不能包含响应体 +* **`300`** 及以上的状态码用于**重定向**。具有这些状态码的响应不一定包含响应体,但 `304`**未修改**是个例外,该响应不得包含响应体 +* **`400`** 及以上的状态码用于表示**客户端错误**。这些可能是第二常用的类型 + * `404`,用于**未找到**响应 + * 对于来自客户端的一般错误,可以只使用 `400` +* `500` 及以上的状态码用于表示服务器端错误。几乎永远不会直接使用这些状态码。应用代码或服务器出现问题时,会自动返回这些状态代码 -## 记住名称的捷径 +!!! tip "提示" -让我们再次看看之前的例子: + 状态码及适用场景的详情,请参阅 MDN 的 HTTP 状态码文档。 + +## 状态码名称快捷方式 + +再看下之前的例子: ```Python hl_lines="6" {!../../../docs_src/response_status_code/tutorial001.py!} ``` -`201` 是表示「已创建」的状态码。 +`201` 表示**已创建**的状态码。 -但是你不必去记住每个代码的含义。 +但我们没有必要记住所有代码的含义。 -你可以使用来自 `fastapi.status` 的便捷变量。 +可以使用 `fastapi.status` 中的快捷变量。 ```Python hl_lines="1 6" {!../../../docs_src/response_status_code/tutorial002.py!} ``` -它们只是一种便捷方式,它们具有同样的数字代码,但是这样使用你就可以使用编辑器的自动补全功能来查找它们: +这只是一种快捷方式,具有相同的数字代码,但它可以使用编辑器的自动补全功能: - + !!! note "技术细节" - 你也可以使用 `from starlette import status`。 - 为了给你(即开发者)提供方便,**FastAPI** 提供了与 `starlette.status` 完全相同的 `fastapi.status`。但它直接来自于 Starlette。 + 也可以使用 `from starlette import status`。 + + 为了让开发者更方便,**FastAPI** 提供了与 `starlette.status` 完全相同的 `fastapi.status`。但它直接来自于 Starlette。 ## 更改默认状态码 -稍后,在[高级用户指南](../advanced/response-change-status-code.md){.internal-link target=_blank}中你将了解如何返回与在此声明的默认状态码不同的状态码。 +[高级用户指南](../advanced/response-change-status-code.md){.internal-link target=_blank}中,将介绍如何返回与在此声明的默认状态码不同的状态码。 diff --git a/docs/zh/docs/tutorial/schema-extra-example.md b/docs/zh/docs/tutorial/schema-extra-example.md index 8f5fbfe70bbb5..ae204dc6107b2 100644 --- a/docs/zh/docs/tutorial/schema-extra-example.md +++ b/docs/zh/docs/tutorial/schema-extra-example.md @@ -8,11 +8,19 @@ ## Pydantic `schema_extra` -您可以使用 `Config` 和 `schema_extra` 为Pydantic模型声明一个示例,如Pydantic 文档:定制 Schema 中所述: +您可以使用 `Config` 和 `schema_extra` 为Pydantic模型声明一个示例,如Pydantic 文档:定制 Schema 中所述: -```Python hl_lines="15-23" -{!../../../docs_src/schema_extra_example/tutorial001.py!} -``` +=== "Python 3.10+" + + ```Python hl_lines="13-21" + {!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="15-23" + {!> ../../../docs_src/schema_extra_example/tutorial001.py!} + ``` 这些额外的信息将按原样添加到输出的JSON模式中。 @@ -20,9 +28,17 @@ 在 `Field`, `Path`, `Query`, `Body` 和其他你之后将会看到的工厂函数,你可以为JSON 模式声明额外信息,你也可以通过给工厂函数传递其他的任意参数来给JSON 模式声明额外信息,比如增加 `example`: -```Python hl_lines="4 10-13" -{!../../../docs_src/schema_extra_example/tutorial002.py!} -``` +=== "Python 3.10+" + + ```Python hl_lines="2 8-11" + {!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="4 10-13" + {!> ../../../docs_src/schema_extra_example/tutorial002.py!} + ``` !!! warning 请记住,传递的那些额外参数不会添加任何验证,只会添加注释,用于文档的目的。 @@ -33,9 +49,41 @@ 比如,你可以将请求体的一个 `example` 传递给 `Body`: -```Python hl_lines="20-25" -{!../../../docs_src/schema_extra_example/tutorial003.py!} -``` +=== "Python 3.10+" + + ```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.8+" + + ```Python hl_lines="23-28" + {!> ../../../docs_src/schema_extra_example/tutorial003_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip + 尽可能选择使用 `Annotated` 的版本。 + + ```Python hl_lines="18-23" + {!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + 尽可能选择使用 `Annotated` 的版本。 + + ```Python hl_lines="20-25" + {!> ../../../docs_src/schema_extra_example/tutorial003.py!} + ``` ## 文档 UI 中的例子 diff --git a/docs/zh/docs/tutorial/security/first-steps.md b/docs/zh/docs/tutorial/security/first-steps.md index 86c3320ce1e9e..f28cc24f8e477 100644 --- a/docs/zh/docs/tutorial/security/first-steps.md +++ b/docs/zh/docs/tutorial/security/first-steps.md @@ -20,15 +20,32 @@ 把下面的示例代码复制到 `main.py`: -```Python -{!../../../docs_src/security/tutorial001.py!} -``` +=== "Python 3.9+" + + ```Python + {!> ../../../docs_src/security/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python + {!> ../../../docs_src/security/tutorial001_an.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + 尽可能选择使用 `Annotated` 的版本。 + + ```Python + {!> ../../../docs_src/security/tutorial001.py!} + ``` ## 运行 !!! info "说明" - 先安装 `python-multipart`。 + 先安装 `python-multipart`。 安装命令: `pip install python-multipart`。 diff --git a/docs/zh/docs/tutorial/security/get-current-user.md b/docs/zh/docs/tutorial/security/get-current-user.md index 477baec3afbf4..1f17f5bd91640 100644 --- a/docs/zh/docs/tutorial/security/get-current-user.md +++ b/docs/zh/docs/tutorial/security/get-current-user.md @@ -1,35 +1,35 @@ # 获取当前用户 -在上一章节中,(基于依赖项注入系统的)安全系统向*路径操作函数*提供了一个 `str` 类型的 `token`: +上一章中,(基于依赖注入系统的)安全系统向*路径操作函数*传递了 `str` 类型的 `token`: ```Python hl_lines="10" {!../../../docs_src/security/tutorial001.py!} ``` -但这还不是很实用。 +但这并不实用。 -让我们来使它返回当前用户给我们。 +接下来,我们学习如何返回当前用户。 -## 创建一个用户模型 +## 创建用户模型 -首先,让我们来创建一个用户 Pydantic 模型。 +首先,创建 Pydantic 用户模型。 -与使用 Pydantic 声明请求体的方式相同,我们可以在其他任何地方使用它: +与使用 Pydantic 声明请求体相同,并且可在任何位置使用: ```Python hl_lines="5 12-16" {!../../../docs_src/security/tutorial002.py!} ``` -## 创建一个 `get_current_user` 依赖项 +## 创建 `get_current_user` 依赖项 -让我们来创建一个 `get_current_user` 依赖项。 +创建 `get_current_user` 依赖项。 -还记得依赖项可以有子依赖项吗? +还记得依赖项支持子依赖项吗? -`get_current_user` 将具有一个我们之前所创建的同一个 `oauth2_scheme` 作为依赖项。 +`get_current_user` 使用 `oauth2_scheme` 作为依赖项。 -与我们之前直接在路径操作中所做的相同,我们新的依赖项 `get_current_user` 将从子依赖项 `oauth2_scheme` 中接收一个 `str` 类型的 `token`: +与之前直接在路径操作中的做法相同,新的 `get_current_user` 依赖项从子依赖项 `oauth2_scheme` 中接收 `str` 类型的 `token`: ```Python hl_lines="25" {!../../../docs_src/security/tutorial002.py!} @@ -37,7 +37,7 @@ ## 获取用户 -`get_current_user` 将使用我们创建的(伪)工具函数,该函数接收 `str` 类型的令牌并返回我们的 Pydantic `User` 模型: +`get_current_user` 使用创建的(伪)工具函数,该函数接收 `str` 类型的令牌,并返回 Pydantic 的 `User` 模型: ```Python hl_lines="19-22 26-27" {!../../../docs_src/security/tutorial002.py!} @@ -45,70 +45,72 @@ ## 注入当前用户 -因此现在我们可以在*路径操作*中使用 `get_current_user` 作为 `Depends` 了: +在*路径操作* 的 `Depends` 中使用 `get_current_user`: ```Python hl_lines="31" {!../../../docs_src/security/tutorial002.py!} ``` -注意我们将 `current_user` 的类型声明为 Pydantic 模型 `User`。 +注意,此处把 `current_user` 的类型声明为 Pydantic 的 `User` 模型。 -这将帮助我们在函数内部使用所有的代码补全和类型检查。 +这有助于在函数内部使用代码补全和类型检查。 -!!! tip - 你可能还记得请求体也是使用 Pydantic 模型来声明的。 +!!! tip "提示" - 在这里 **FastAPI** 不会搞混,因为你正在使用的是 `Depends`。 + 还记得请求体也是使用 Pydantic 模型声明的吧。 -!!! check - 这种依赖系统的设计方式使我们可以拥有不同的依赖项(不同的「可依赖类型」),并且它们都返回一个 `User` 模型。 + 放心,因为使用了 `Depends`,**FastAPI** 不会搞混。 - 我们并未被局限于只能有一个返回该类型数据的依赖项。 +!!! check "检查" + 依赖系统的这种设计方式可以支持不同的依赖项返回同一个 `User` 模型。 -## 其他模型 + 而不是局限于只能有一个返回该类型数据的依赖项。 -现在你可以直接在*路径操作函数*中获取当前用户,并使用 `Depends` 在**依赖注入**级别处理安全性机制。 -你可以使用任何模型或数据来满足安全性要求(在这个示例中,使用的是 Pydantic 模型 `User`)。 +## 其它模型 -但是你并未被限制只能使用某些特定的数据模型,类或类型。 +接下来,直接在*路径操作函数*中获取当前用户,并用 `Depends` 在**依赖注入**系统中处理安全机制。 -你想要在模型中使用 `id` 和 `email` 而不使用任何的 `username`?当然可以。你可以同样地使用这些工具。 +开发者可以使用任何模型或数据满足安全需求(本例中是 Pydantic 的 `User` 模型)。 -你只想要一个 `str`?或者仅仅一个 `dict`?还是直接一个数据库模型类的实例?它们的工作方式都是一样的。 +而且,不局限于只能使用特定的数据模型、类或类型。 -实际上你没有用户登录到你的应用程序,而是只拥有访问令牌的机器人,程序或其他系统?再一次,它们的工作方式也是一样的。 +不想在模型中使用 `username`,而是使用 `id` 和 `email`?当然可以。这些工具也支持。 -尽管去使用你的应用程序所需要的任何模型,任何类,任何数据库。**FastAPI** 通过依赖项注入系统都帮你搞定。 +只想使用字符串?或字典?甚至是数据库类模型的实例?工作方式都一样。 +实际上,就算登录应用的不是用户,而是只拥有访问令牌的机器人、程序或其它系统?工作方式也一样。 -## 代码体积 +尽管使用应用所需的任何模型、类、数据库。**FastAPI** 通过依赖注入系统都能帮您搞定。 -这个示例似乎看起来很冗长。考虑到我们在同一文件中混合了安全性,数据模型工具函数和路径操作等代码。 -但关键的是。 +## 代码大小 -安全性和依赖项注入内容只需要编写一次。 +这个示例看起来有些冗长。毕竟这个文件同时包含了安全、数据模型的工具函数,以及路径操作等代码。 -你可以根据需要使其变得很复杂。而且只需要在一个地方写一次。但仍然具备所有的灵活性。 +但,关键是: -但是,你可以有无数个使用同一安全系统的端点(*路径操作*)。 +**安全和依赖注入的代码只需要写一次。** -所有(或所需的任何部分)的端点,都可以利用对这些或你创建的其他依赖项进行复用所带来的优势。 +就算写得再复杂,也只是在一个位置写一次就够了。所以,要多复杂就可以写多复杂。 -所有的这无数个*路径操作*甚至可以小到只需 3 行代码: +但是,就算有数千个端点(*路径操作*),它们都可以使用同一个安全系统。 + +而且,所有端点(或它们的任何部件)都可以利用这些依赖项或任何其它依赖项。 + +所有*路径操作*只需 3 行代码就可以了: ```Python hl_lines="30-32" {!../../../docs_src/security/tutorial002.py!} ``` -## 总结 +## 小结 -现在你可以直接在*路径操作函数*中获取当前用户。 +现在,我们可以直接在*路径操作函数*中获取当前用户。 -我们已经进行到一半了。 +至此,安全的内容已经讲了一半。 -我们只需要再为用户/客户端添加一个真正发送 `username` 和 `password` 的*路径操作*。 +只要再为用户或客户端的*路径操作*添加真正发送 `username` 和 `password` 的功能就可以了。 -这些内容在下一章节。 +下一章见。 diff --git a/docs/zh/docs/tutorial/security/oauth2-jwt.md b/docs/zh/docs/tutorial/security/oauth2-jwt.md index 054198545ef8e..33a4d7fc76171 100644 --- a/docs/zh/docs/tutorial/security/oauth2-jwt.md +++ b/docs/zh/docs/tutorial/security/oauth2-jwt.md @@ -170,7 +170,7 @@ $ openssl rand -hex 32 创建并返回真正的 JWT 访问令牌。 -```Python hl_lines="115-128" +```Python hl_lines="115-130" {!../../../docs_src/security/tutorial004.py!} ``` diff --git a/docs/zh/docs/tutorial/security/simple-oauth2.md b/docs/zh/docs/tutorial/security/simple-oauth2.md index 276f3d63b69f9..c7f46177f0314 100644 --- a/docs/zh/docs/tutorial/security/simple-oauth2.md +++ b/docs/zh/docs/tutorial/security/simple-oauth2.md @@ -1,94 +1,98 @@ -# 使用密码和 Bearer 的简单 OAuth2 +# OAuth2 实现简单的 Password 和 Bearer 验证 -现在让我们接着上一章继续开发,并添加缺少的部分以实现一个完整的安全性流程。 +本章添加上一章示例中欠缺的部分,实现完整的安全流。 ## 获取 `username` 和 `password` -我们将使用 **FastAPI** 的安全性实用工具来获取 `username` 和 `password`。 +首先,使用 **FastAPI** 安全工具获取 `username` 和 `password`。 -OAuth2 规定在使用(我们打算用的)「password 流程」时,客户端/用户必须将 `username` 和 `password` 字段作为表单数据发送。 +OAuth2 规范要求使用**密码流**时,客户端或用户必须以表单数据形式发送 `username` 和 `password` 字段。 -而且规范明确了字段必须这样命名。因此 `user-name` 或 `email` 是行不通的。 +并且,这两个字段必须命名为 `username` 和 `password` ,不能使用 `user-name` 或 `email` 等其它名称。 -不过不用担心,你可以在前端按照你的想法将它展示给最终用户。 +不过也不用担心,前端仍可以显示终端用户所需的名称。 -而且你的数据库模型也可以使用你想用的任何其他名称。 +数据库模型也可以使用所需的名称。 -但是对于登录*路径操作*,我们需要使用这些名称来与规范兼容(以具备例如使用集成的 API 文档系统的能力)。 +但对于登录*路径操作*,则要使用兼容规范的 `username` 和 `password`,(例如,实现与 API 文档集成)。 -规范还写明了 `username` 和 `password` 必须作为表单数据发送(因此,此处不能使用 JSON)。 +该规范要求必须以表单数据形式发送 `username` 和 `password`,因此,不能使用 JSON 对象。 -### `scope` +### `Scope`(作用域) -规范还提到客户端可以发送另一个表单字段「`scope`」。 +OAuth2 还支持客户端发送**`scope`**表单字段。 -这个表单字段的名称为 `scope`(单数形式),但实际上它是一个由空格分隔的「作用域」组成的长字符串。 +虽然表单字段的名称是 `scope`(单数),但实际上,它是以空格分隔的,由多个**scope**组成的长字符串。 -每个「作用域」只是一个字符串(中间没有空格)。 +**作用域**只是不带空格的字符串。 -它们通常用于声明特定的安全权限,例如: +常用于声明指定安全权限,例如: -* `users:read` 或者 `users:write` 是常见的例子。 -* Facebook / Instagram 使用 `instagram_basic`。 -* Google 使用了 `https://www.googleapis.com/auth/drive` 。 +* 常见用例为,`users:read` 或 `users:write` +* 脸书和 Instagram 使用 `instagram_basic` +* 谷歌使用 `https://www.googleapis.com/auth/drive` -!!! info - 在 OAuth2 中「作用域」只是一个声明所需特定权限的字符串。 +!!! info "说明" - 它有没有 `:` 这样的其他字符或者是不是 URL 都没有关系。 + OAuth2 中,**作用域**只是声明指定权限的字符串。 - 这些细节是具体的实现。 + 是否使用冒号 `:` 等符号,或是不是 URL 并不重要。 - 对 OAuth2 来说它们就只是字符串而已。 + 这些细节只是特定的实现方式。 + + 对 OAuth2 来说,都只是字符串而已。 ## 获取 `username` 和 `password` 的代码 -现在,让我们使用 **FastAPI** 提供的实用工具来处理此问题。 +接下来,使用 **FastAPI** 工具获取用户名与密码。 ### `OAuth2PasswordRequestForm` -首先,导入 `OAuth2PasswordRequestForm`,然后在 `token` 的*路径操作*中通过 `Depends` 将其作为依赖项使用。 +首先,导入 `OAuth2PasswordRequestForm`,然后,在 `/token` *路径操作* 中,用 `Depends` 把该类作为依赖项。 ```Python hl_lines="4 76" {!../../../docs_src/security/tutorial003.py!} ``` -`OAuth2PasswordRequestForm` 是一个类依赖项,声明了如下的请求表单: +`OAuth2PasswordRequestForm` 是用以下几项内容声明表单请求体的类依赖项: + +* `username` +* `password` +* 可选的 `scope` 字段,由多个空格分隔的字符串组成的长字符串 +* 可选的 `grant_type` -* `username`。 -* `password`。 -* 一个可选的 `scope` 字段,是一个由空格分隔的字符串组成的大字符串。 -* 一个可选的 `grant_type`. +!!! tip "提示" -!!! tip - OAuth2 规范实际上*要求* `grant_type` 字段使用一个固定的值 `password`,但是 `OAuth2PasswordRequestForm` 没有作强制约束。 + 实际上,OAuth2 规范*要求* `grant_type` 字段使用固定值 `password`,但 `OAuth2PasswordRequestForm` 没有作强制约束。 - 如果你需要强制要求这一点,请使用 `OAuth2PasswordRequestFormStrict` 而不是 `OAuth2PasswordRequestForm`。 + 如需强制使用固定值 `password`,则不要用 `OAuth2PasswordRequestForm`,而是用 `OAuth2PasswordRequestFormStrict`。 -* 一个可选的 `client_id`(我们的示例不需要它)。 -* 一个可选的 `client_secret`(我们的示例不需要它)。 +* 可选的 `client_id`(本例未使用) +* 可选的 `client_secret`(本例未使用) -!!! info - `OAuth2PasswordRequestForm` 并不像 `OAuth2PasswordBearer` 一样是 FastAPI 的一个特殊的类。 +!!! info "说明" - `OAuth2PasswordBearer` 使得 **FastAPI** 明白它是一个安全方案。所以它得以通过这种方式添加到 OpenAPI 中。 + `OAuth2PasswordRequestForm` 与 `OAuth2PasswordBearer` 一样,都不是 FastAPI 的特殊类。 - 但 `OAuth2PasswordRequestForm` 只是一个你可以自己编写的类依赖项,或者你也可以直接声明 `Form` 参数。 + **FastAPI** 把 `OAuth2PasswordBearer` 识别为安全方案。因此,可以通过这种方式把它添加至 OpenAPI。 - 但是由于这是一种常见的使用场景,因此 FastAPI 出于简便直接提供了它。 + 但 `OAuth2PasswordRequestForm` 只是可以自行编写的类依赖项,也可以直接声明 `Form` 参数。 + + 但由于这种用例很常见,FastAPI 为了简便,就直接提供了对它的支持。 ### 使用表单数据 -!!! tip - 类依赖项 `OAuth2PasswordRequestForm` 的实例不会有用空格分隔的长字符串属性 `scope`,而是具有一个 `scopes` 属性,该属性将包含实际被发送的每个作用域字符串组成的列表。 +!!! tip "提示" + + `OAuth2PasswordRequestForm` 类依赖项的实例没有以空格分隔的长字符串属性 `scope`,但它支持 `scopes` 属性,由已发送的 scope 字符串列表组成。 - 在此示例中我们没有使用 `scopes`,但如果你需要的话可以使用该功能。 + 本例没有使用 `scopes`,但开发者也可以根据需要使用该属性。 -现在,使用表单字段中的 `username` 从(伪)数据库中获取用户数据。 +现在,即可使用表单字段 `username`,从(伪)数据库中获取用户数据。 -如果没有这个用户,我们将返回一个错误消息,提示「用户名或密码错误」。 +如果不存在指定用户,则返回错误消息,提示**用户名或密码错误**。 -对于这个错误,我们使用 `HTTPException` 异常: +本例使用 `HTTPException` 异常显示此错误: ```Python hl_lines="3 77-79" {!../../../docs_src/security/tutorial003.py!} @@ -96,27 +100,27 @@ OAuth2 规定在使用(我们打算用的)「password 流程」时,客户 ### 校验密码 -目前我们已经从数据库中获取了用户数据,但尚未校验密码。 +至此,我们已经从数据库中获取了用户数据,但尚未校验密码。 -让我们首先将这些数据放入 Pydantic `UserInDB` 模型中。 +接下来,首先将数据放入 Pydantic 的 `UserInDB` 模型。 -永远不要保存明文密码,因此,我们将使用(伪)哈希密码系统。 +注意:永远不要保存明文密码,本例暂时先使用(伪)哈希密码系统。 -如果密码不匹配,我们将返回同一个错误。 +如果密码不匹配,则返回与上面相同的错误。 -#### 哈希密码 +#### 密码哈希 -「哈希」的意思是:将某些内容(在本例中为密码)转换为看起来像乱码的字节序列(只是一个字符串)。 +**哈希**是指,将指定内容(本例中为密码)转换为形似乱码的字节序列(其实就是字符串)。 -每次你传入完全相同的内容(完全相同的密码)时,你都会得到完全相同的乱码。 +每次传入完全相同的内容(比如,完全相同的密码)时,得到的都是完全相同的乱码。 -但是你不能从乱码转换回密码。 +但这个乱码无法转换回传入的密码。 -##### 为什么使用哈希密码 +##### 为什么使用密码哈希 -如果你的数据库被盗,小偷将无法获得用户的明文密码,只有哈希值。 +原因很简单,假如数据库被盗,窃贼无法获取用户的明文密码,得到的只是哈希值。 -因此,小偷将无法尝试在另一个系统中使用这些相同的密码(由于许多用户在任何地方都使用相同的密码,因此这很危险)。 +这样一来,窃贼就无法在其它应用中使用窃取的密码,要知道,很多用户在所有系统中都使用相同的密码,风险超大。 ```Python hl_lines="80-83" {!../../../docs_src/security/tutorial003.py!} @@ -124,9 +128,9 @@ OAuth2 规定在使用(我们打算用的)「password 流程」时,客户 #### 关于 `**user_dict` -`UserInDB(**user_dict)` 表示: +`UserInDB(**user_dict)` 是指: -*直接将 `user_dict` 的键和值作为关键字参数传递,等同于:* +*直接把 `user_dict` 的键与值当作关键字参数传递,等效于:* ```Python UserInDB( @@ -138,75 +142,79 @@ UserInDB( ) ``` -!!! info - 有关 `user_dict` 的更完整说明,请参阅[**额外的模型**文档](../extra-models.md#about-user_indict){.internal-link target=_blank}。 +!!! info "说明" -## 返回令牌 + `user_dict` 的说明,详见[**更多模型**一章](../extra-models.md#about-user_indict){.internal-link target=_blank}。 -`token` 端点的响应必须是一个 JSON 对象。 +## 返回 Token -它应该有一个 `token_type`。在我们的例子中,由于我们使用的是「Bearer」令牌,因此令牌类型应为「`bearer`」。 +`token` 端点的响应必须是 JSON 对象。 -并且还应该有一个 `access_token` 字段,它是一个包含我们的访问令牌的字符串。 +响应返回的内容应该包含 `token_type`。本例中用的是**Bearer**Token,因此, Token 类型应为**`bearer`**。 -对于这个简单的示例,我们将极其不安全地返回相同的 `username` 作为令牌。 +返回内容还应包含 `access_token` 字段,它是包含权限 Token 的字符串。 -!!! tip - 在下一章中,你将看到一个真实的安全实现,使用了哈希密码和 JWT 令牌。 +本例只是简单的演示,返回的 Token 就是 `username`,但这种方式极不安全。 - 但现在,让我们仅关注我们需要的特定细节。 +!!! tip "提示" + + 下一章介绍使用哈希密码和 JWT Token 的真正安全机制。 + + 但现在,仅关注所需的特定细节。 ```Python hl_lines="85" {!../../../docs_src/security/tutorial003.py!} ``` -!!! tip - 根据规范,你应该像本示例一样,返回一个带有 `access_token` 和 `token_type` 的 JSON。 +!!! tip "提示" - 这是你必须在代码中自行完成的工作,并且要确保使用了这些 JSON 字段。 + 按规范的要求,应像本示例一样,返回带有 `access_token` 和 `token_type` 的 JSON 对象。 - 这几乎是唯一的你需要自己记住并正确地执行以符合规范的事情。 + 这是开发者必须在代码中自行完成的工作,并且要确保使用这些 JSON 的键。 - 其余的,**FastAPI** 都会为你处理。 + 这几乎是唯一需要开发者牢记在心,并按规范要求正确执行的事。 + + **FastAPI** 则负责处理其它的工作。 ## 更新依赖项 -现在我们将更新我们的依赖项。 +接下来,更新依赖项。 -我们想要仅当此用户处于启用状态时才能获取 `current_user`。 +使之仅在当前用户为激活状态时,才能获取 `current_user`。 -因此,我们创建了一个额外的依赖项 `get_current_active_user`,而该依赖项又以 `get_current_user` 作为依赖项。 +为此,要再创建一个依赖项 `get_current_active_user`,此依赖项以 `get_current_user` 依赖项为基础。 -如果用户不存在或处于未启用状态,则这两个依赖项都将仅返回 HTTP 错误。 +如果用户不存在,或状态为未激活,这两个依赖项都会返回 HTTP 错误。 -因此,在我们的端点中,只有当用户存在,身份认证通过且处于启用状态时,我们才能获得该用户: +因此,在端点中,只有当用户存在、通过身份验证、且状态为激活时,才能获得该用户: ```Python hl_lines="58-67 69-72 90" {!../../../docs_src/security/tutorial003.py!} ``` -!!! info - 我们在此处返回的值为 `Bearer` 的额外响应头 `WWW-Authenticate` 也是规范的一部分。 +!!! info "说明" + + 此处返回值为 `Bearer` 的响应头 `WWW-Authenticate` 也是规范的一部分。 - 任何的 401「未认证」HTTP(错误)状态码都应该返回 `WWW-Authenticate` 响应头。 + 任何 401**UNAUTHORIZED**HTTP(错误)状态码都应返回 `WWW-Authenticate` 响应头。 - 对于 bearer 令牌(我们的例子),该响应头的值应为 `Bearer`。 + 本例中,因为使用的是 Bearer Token,该响应头的值应为 `Bearer`。 - 实际上你可以忽略这个额外的响应头,不会有什么问题。 + 实际上,忽略这个附加响应头,也不会有什么问题。 - 但此处提供了它以符合规范。 + 之所以在此提供这个附加响应头,是为了符合规范的要求。 - 而且,(现在或将来)可能会有工具期望得到并使用它,然后对你或你的用户有用处。 + 说不定什么时候,就有工具用得上它,而且,开发者或用户也可能用得上。 - 这就是遵循标准的好处... + 这就是遵循标准的好处…… ## 实际效果 -打开交互式文档:http://127.0.0.1:8000/docs。 +打开 API 文档:http://127.0.0.1:8000/docs。 -### 身份认证 +### 身份验证 -点击「Authorize」按钮。 +点击**Authorize**按钮。 使用以下凭证: @@ -216,15 +224,15 @@ UserInDB( -在系统中进行身份认证后,你将看到: +通过身份验证后,显示下图所示的内容: -### 获取本人的用户数据 +### 获取当前用户数据 -现在执行 `/users/me` 路径的 `GET` 操作。 +使用 `/users/me` 路径的 `GET` 操作。 -你将获得你的用户数据,如: +可以提取如下当前用户数据: ```JSON { @@ -238,7 +246,7 @@ UserInDB( -如果你点击锁定图标并注销,然后再次尝试同一操作,则会得到 HTTP 401 错误: +点击小锁图标,注销后,再执行同样的操作,则会得到 HTTP 401 错误: ```JSON { @@ -246,17 +254,17 @@ UserInDB( } ``` -### 未启用的用户 +### 未激活用户 -现在尝试使用未启用的用户,并通过以下方式进行身份认证: +测试未激活用户,输入以下信息,进行身份验证: 用户名:`alice` 密码:`secret2` -然后尝试执行 `/users/me` 路径的 `GET` 操作。 +然后,执行 `/users/me` 路径的 `GET` 操作。 -你将得到一个「未启用的用户」错误,如: +显示下列**未激活用户**错误信息: ```JSON { @@ -264,12 +272,12 @@ UserInDB( } ``` -## 总结 +## 小结 -现在你掌握了为你的 API 实现一个基于 `username` 和 `password` 的完整安全系统的工具。 +使用本章的工具实现基于 `username` 和 `password` 的完整 API 安全系统。 -使用这些工具,你可以使安全系统与任何数据库以及任何用户或数据模型兼容。 +这些工具让安全系统兼容任何数据库、用户及数据模型。 -唯一缺少的细节是它实际上还并不「安全」。 +唯一欠缺的是,它仍然不是真的**安全**。 -在下一章中,你将看到如何使用一个安全的哈希密码库和 JWT 令牌。 +下一章,介绍使用密码哈希支持库与 JWT 令牌实现真正的安全机制。 diff --git a/docs/zh/docs/tutorial/sql-databases.md b/docs/zh/docs/tutorial/sql-databases.md index 482588f94d7ec..be0c765935ce8 100644 --- a/docs/zh/docs/tutorial/sql-databases.md +++ b/docs/zh/docs/tutorial/sql-databases.md @@ -78,9 +78,23 @@ ORM 具有在代码和数据库表(“*关系型”)中的**对象**之间 现在让我们看看每个文件/模块的作用。 +## 安装 SQLAlchemy + +先下载`SQLAlchemy`所需要的依赖: + +
+ +```console +$ pip install sqlalchemy + +---> 100% +``` + +
+ ## 创建 SQLAlchemy 部件 -让我们涉及到文件`sql_app/database.py`。 +让我们转到文件`sql_app/database.py`。 ### 导入 SQLAlchemy 部件 @@ -258,7 +272,7 @@ connect_args={"check_same_thread": False} {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="3 6-8 11-12 23-24 27-28" {!> ../../../docs_src/sql_databases/sql_app/schemas.py!} @@ -302,7 +316,7 @@ name: str {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="15-17 31-34" {!> ../../../docs_src/sql_databases/sql_app/schemas.py!} @@ -315,7 +329,7 @@ name: str 现在,在用于查询的 Pydantic*模型*`Item`中`User`,添加一个内部`Config`类。 -此类[`Config`](https://pydantic-docs.helpmanual.io/usage/model_config/)用于为 Pydantic 提供配置。 +此类[`Config`](https://docs.pydantic.dev/latest/api/config/)用于为 Pydantic 提供配置。 在`Config`类中,设置属性`orm_mode = True`。 @@ -331,7 +345,7 @@ name: str {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="15 19-20 31 36-37" {!> ../../../docs_src/sql_databases/sql_app/schemas.py!} @@ -471,7 +485,7 @@ current_user.items {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9" {!> ../../../docs_src/sql_databases/sql_app/main.py!} @@ -485,7 +499,7 @@ current_user.items “迁移”是每当您更改 SQLAlchemy 模型的结构、添加新属性等以在数据库中复制这些更改、添加新列、新表等时所需的一组步骤。 -您可以在[Project Generation - Template](https://fastapi.tiangolo.com/zh/project-generation/)的模板中找到一个 FastAPI 项目中的 Alembic 示例。具体在[`alembic`代码目录中](https://github.com/tiangolo/full-stack-fastapi-postgresql/tree/master/%7B%7Bcookiecutter.project_slug%7D%7D/backend/app/alembic/)。 +您可以在[Project Generation - Template](https://fastapi.tiangolo.com/zh/project-generation/)的模板中找到一个 FastAPI 项目中的 Alembic 示例。具体在[`alembic`代码目录中](https://github.com/tiangolo/full-stack-fastapi-postgresql/tree/master/src/backend/app/alembic/)。 ### 创建依赖项 @@ -505,7 +519,7 @@ current_user.items {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="15-20" {!> ../../../docs_src/sql_databases/sql_app/main.py!} @@ -530,7 +544,7 @@ current_user.items {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="24 32 38 47 53" {!> ../../../docs_src/sql_databases/sql_app/main.py!} @@ -551,7 +565,7 @@ current_user.items {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="23-28 31-34 37-42 45-49 52-55" {!> ../../../docs_src/sql_databases/sql_app/main.py!} @@ -650,7 +664,7 @@ def read_user(user_id: int, db: Session = Depends(get_db)): {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python {!> ../../../docs_src/sql_databases/sql_app/schemas.py!} @@ -670,7 +684,7 @@ def read_user(user_id: int, db: Session = Depends(get_db)): {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python {!> ../../../docs_src/sql_databases/sql_app/main.py!} @@ -729,7 +743,7 @@ $ uvicorn sql_app.main:app --reload {!> ../../../docs_src/sql_databases/sql_app_py39/alt_main.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="14-22" {!> ../../../docs_src/sql_databases/sql_app/alt_main.py!} diff --git a/docs/zh/docs/tutorial/testing.md b/docs/zh/docs/tutorial/testing.md index 41f01f8d84a41..77fff759642f9 100644 --- a/docs/zh/docs/tutorial/testing.md +++ b/docs/zh/docs/tutorial/testing.md @@ -122,7 +122,7 @@ {!> ../../../docs_src/app_testing/app_b_an_py39/main.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python {!> ../../../docs_src/app_testing/app_b_an/main.py!} @@ -137,7 +137,7 @@ {!> ../../../docs_src/app_testing/app_b_py310/main.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. diff --git a/docs_src/app_testing/app_b/main.py b/docs_src/app_testing/app_b/main.py index 11558b8e813f4..45a103378388a 100644 --- a/docs_src/app_testing/app_b/main.py +++ b/docs_src/app_testing/app_b/main.py @@ -33,6 +33,6 @@ async def create_item(item: Item, x_token: str = Header()): if x_token != fake_secret_token: raise HTTPException(status_code=400, detail="Invalid X-Token header") if item.id in fake_db: - raise HTTPException(status_code=400, detail="Item already exists") + raise HTTPException(status_code=409, detail="Item already exists") fake_db[item.id] = item return item diff --git a/docs_src/app_testing/app_b/test_main.py b/docs_src/app_testing/app_b/test_main.py index d186b8ecbacfa..4e1c51ecc861d 100644 --- a/docs_src/app_testing/app_b/test_main.py +++ b/docs_src/app_testing/app_b/test_main.py @@ -21,7 +21,7 @@ def test_read_item_bad_token(): assert response.json() == {"detail": "Invalid X-Token header"} -def test_read_inexistent_item(): +def test_read_nonexistent_item(): response = client.get("/items/baz", headers={"X-Token": "coneofsilence"}) assert response.status_code == 404 assert response.json() == {"detail": "Item not found"} @@ -61,5 +61,5 @@ def test_create_existing_item(): "description": "There goes my stealer", }, ) - assert response.status_code == 400 + assert response.status_code == 409 assert response.json() == {"detail": "Item already exists"} diff --git a/docs_src/app_testing/app_b_an/test_main.py b/docs_src/app_testing/app_b_an/test_main.py index d186b8ecbacfa..e2eda449d459a 100644 --- a/docs_src/app_testing/app_b_an/test_main.py +++ b/docs_src/app_testing/app_b_an/test_main.py @@ -21,7 +21,7 @@ def test_read_item_bad_token(): assert response.json() == {"detail": "Invalid X-Token header"} -def test_read_inexistent_item(): +def test_read_nonexistent_item(): response = client.get("/items/baz", headers={"X-Token": "coneofsilence"}) assert response.status_code == 404 assert response.json() == {"detail": "Item not found"} diff --git a/docs_src/app_testing/app_b_an_py310/test_main.py b/docs_src/app_testing/app_b_an_py310/test_main.py index d186b8ecbacfa..e2eda449d459a 100644 --- a/docs_src/app_testing/app_b_an_py310/test_main.py +++ b/docs_src/app_testing/app_b_an_py310/test_main.py @@ -21,7 +21,7 @@ def test_read_item_bad_token(): assert response.json() == {"detail": "Invalid X-Token header"} -def test_read_inexistent_item(): +def test_read_nonexistent_item(): response = client.get("/items/baz", headers={"X-Token": "coneofsilence"}) assert response.status_code == 404 assert response.json() == {"detail": "Item not found"} diff --git a/docs_src/app_testing/app_b_an_py39/test_main.py b/docs_src/app_testing/app_b_an_py39/test_main.py index d186b8ecbacfa..e2eda449d459a 100644 --- a/docs_src/app_testing/app_b_an_py39/test_main.py +++ b/docs_src/app_testing/app_b_an_py39/test_main.py @@ -21,7 +21,7 @@ def test_read_item_bad_token(): assert response.json() == {"detail": "Invalid X-Token header"} -def test_read_inexistent_item(): +def test_read_nonexistent_item(): response = client.get("/items/baz", headers={"X-Token": "coneofsilence"}) assert response.status_code == 404 assert response.json() == {"detail": "Item not found"} diff --git a/docs_src/app_testing/app_b_py310/main.py b/docs_src/app_testing/app_b_py310/main.py index b4c72de5c9431..eccedcc7ce2ec 100644 --- a/docs_src/app_testing/app_b_py310/main.py +++ b/docs_src/app_testing/app_b_py310/main.py @@ -31,6 +31,6 @@ async def create_item(item: Item, x_token: str = Header()): if x_token != fake_secret_token: raise HTTPException(status_code=400, detail="Invalid X-Token header") if item.id in fake_db: - raise HTTPException(status_code=400, detail="Item already exists") + raise HTTPException(status_code=409, detail="Item already exists") fake_db[item.id] = item return item diff --git a/docs_src/app_testing/app_b_py310/test_main.py b/docs_src/app_testing/app_b_py310/test_main.py index d186b8ecbacfa..4e1c51ecc861d 100644 --- a/docs_src/app_testing/app_b_py310/test_main.py +++ b/docs_src/app_testing/app_b_py310/test_main.py @@ -21,7 +21,7 @@ def test_read_item_bad_token(): assert response.json() == {"detail": "Invalid X-Token header"} -def test_read_inexistent_item(): +def test_read_nonexistent_item(): response = client.get("/items/baz", headers={"X-Token": "coneofsilence"}) assert response.status_code == 404 assert response.json() == {"detail": "Item not found"} @@ -61,5 +61,5 @@ def test_create_existing_item(): "description": "There goes my stealer", }, ) - assert response.status_code == 400 + assert response.status_code == 409 assert response.json() == {"detail": "Item already exists"} diff --git a/docs_src/body/tutorial003.py b/docs_src/body/tutorial003.py index 89a6b833ce237..2f33cc0389694 100644 --- a/docs_src/body/tutorial003.py +++ b/docs_src/body/tutorial003.py @@ -15,5 +15,5 @@ class Item(BaseModel): @app.put("/items/{item_id}") -async def create_item(item_id: int, item: Item): +async def update_item(item_id: int, item: Item): return {"item_id": item_id, **item.dict()} diff --git a/docs_src/body/tutorial003_py310.py b/docs_src/body/tutorial003_py310.py index a936f28fdc65d..440b210e6b47a 100644 --- a/docs_src/body/tutorial003_py310.py +++ b/docs_src/body/tutorial003_py310.py @@ -13,5 +13,5 @@ class Item(BaseModel): @app.put("/items/{item_id}") -async def create_item(item_id: int, item: Item): +async def update_item(item_id: int, item: Item): return {"item_id": item_id, **item.dict()} diff --git a/docs_src/body/tutorial004.py b/docs_src/body/tutorial004.py index e2df0df2baa27..0671e0a278581 100644 --- a/docs_src/body/tutorial004.py +++ b/docs_src/body/tutorial004.py @@ -15,7 +15,7 @@ class Item(BaseModel): @app.put("/items/{item_id}") -async def create_item(item_id: int, item: Item, q: Union[str, None] = None): +async def update_item(item_id: int, item: Item, q: Union[str, None] = None): result = {"item_id": item_id, **item.dict()} if q: result.update({"q": q}) diff --git a/docs_src/body/tutorial004_py310.py b/docs_src/body/tutorial004_py310.py index 60cfd96109b9c..b352b70ab6010 100644 --- a/docs_src/body/tutorial004_py310.py +++ b/docs_src/body/tutorial004_py310.py @@ -13,7 +13,7 @@ class Item(BaseModel): @app.put("/items/{item_id}") -async def create_item(item_id: int, item: Item, q: str | None = None): +async def update_item(item_id: int, item: Item, q: str | None = None): result = {"item_id": item_id, **item.dict()} if q: result.update({"q": q}) diff --git a/docs_src/conditional_openapi/tutorial001.py b/docs_src/conditional_openapi/tutorial001.py index 717e723e83a89..eedb0d2742816 100644 --- a/docs_src/conditional_openapi/tutorial001.py +++ b/docs_src/conditional_openapi/tutorial001.py @@ -1,5 +1,5 @@ from fastapi import FastAPI -from pydantic import BaseSettings +from pydantic_settings import BaseSettings class Settings(BaseSettings): diff --git a/docs_src/extending_openapi/tutorial003.py b/docs_src/configure_swagger_ui/tutorial001.py similarity index 100% rename from docs_src/extending_openapi/tutorial003.py rename to docs_src/configure_swagger_ui/tutorial001.py diff --git a/docs_src/extending_openapi/tutorial004.py b/docs_src/configure_swagger_ui/tutorial002.py similarity index 100% rename from docs_src/extending_openapi/tutorial004.py rename to docs_src/configure_swagger_ui/tutorial002.py diff --git a/docs_src/extending_openapi/tutorial005.py b/docs_src/configure_swagger_ui/tutorial003.py similarity index 100% rename from docs_src/extending_openapi/tutorial005.py rename to docs_src/configure_swagger_ui/tutorial003.py diff --git a/docs_src/custom_docs_ui/tutorial001.py b/docs_src/custom_docs_ui/tutorial001.py new file mode 100644 index 0000000000000..4384433e37c50 --- /dev/null +++ b/docs_src/custom_docs_ui/tutorial001.py @@ -0,0 +1,38 @@ +from fastapi import FastAPI +from fastapi.openapi.docs import ( + get_redoc_html, + get_swagger_ui_html, + get_swagger_ui_oauth2_redirect_html, +) + +app = FastAPI(docs_url=None, redoc_url=None) + + +@app.get("/docs", include_in_schema=False) +async def custom_swagger_ui_html(): + return get_swagger_ui_html( + openapi_url=app.openapi_url, + title=app.title + " - Swagger UI", + oauth2_redirect_url=app.swagger_ui_oauth2_redirect_url, + swagger_js_url="https://unpkg.com/swagger-ui-dist@5.9.0/swagger-ui-bundle.js", + swagger_css_url="https://unpkg.com/swagger-ui-dist@5.9.0/swagger-ui.css", + ) + + +@app.get(app.swagger_ui_oauth2_redirect_url, include_in_schema=False) +async def swagger_ui_redirect(): + return get_swagger_ui_oauth2_redirect_html() + + +@app.get("/redoc", include_in_schema=False) +async def redoc_html(): + return get_redoc_html( + openapi_url=app.openapi_url, + title=app.title + " - ReDoc", + redoc_js_url="https://unpkg.com/redoc@next/bundles/redoc.standalone.js", + ) + + +@app.get("/users/{username}") +async def read_user(username: str): + return {"message": f"Hello {username}"} diff --git a/docs_src/extending_openapi/tutorial002.py b/docs_src/custom_docs_ui/tutorial002.py similarity index 100% rename from docs_src/extending_openapi/tutorial002.py rename to docs_src/custom_docs_ui/tutorial002.py diff --git a/docs_src/custom_response/tutorial006c.py b/docs_src/custom_response/tutorial006c.py index db87a9389d869..87c720364be44 100644 --- a/docs_src/custom_response/tutorial006c.py +++ b/docs_src/custom_response/tutorial006c.py @@ -6,4 +6,4 @@ @app.get("/pydantic", response_class=RedirectResponse, status_code=302) async def redirect_pydantic(): - return "https://pydantic-docs.helpmanual.io/" + return "https://docs.pydantic.dev/" diff --git a/docs_src/dependencies/tutorial005_an.py b/docs_src/dependencies/tutorial005_an.py index 6785099dabe7b..1d78c17a2a09f 100644 --- a/docs_src/dependencies/tutorial005_an.py +++ b/docs_src/dependencies/tutorial005_an.py @@ -21,6 +21,6 @@ def query_or_cookie_extractor( @app.get("/items/") async def read_query( - query_or_default: Annotated[str, Depends(query_or_cookie_extractor)] + query_or_default: Annotated[str, Depends(query_or_cookie_extractor)], ): return {"q_or_cookie": query_or_default} diff --git a/docs_src/dependencies/tutorial005_an_py310.py b/docs_src/dependencies/tutorial005_an_py310.py index 6c0aa0b3686be..5ccfc62bdfb27 100644 --- a/docs_src/dependencies/tutorial005_an_py310.py +++ b/docs_src/dependencies/tutorial005_an_py310.py @@ -20,6 +20,6 @@ def query_or_cookie_extractor( @app.get("/items/") async def read_query( - query_or_default: Annotated[str, Depends(query_or_cookie_extractor)] + query_or_default: Annotated[str, Depends(query_or_cookie_extractor)], ): return {"q_or_cookie": query_or_default} diff --git a/docs_src/dependencies/tutorial005_an_py39.py b/docs_src/dependencies/tutorial005_an_py39.py index e8887e162167c..d5dd8dca9aad2 100644 --- a/docs_src/dependencies/tutorial005_an_py39.py +++ b/docs_src/dependencies/tutorial005_an_py39.py @@ -20,6 +20,6 @@ def query_or_cookie_extractor( @app.get("/items/") async def read_query( - query_or_default: Annotated[str, Depends(query_or_cookie_extractor)] + query_or_default: Annotated[str, Depends(query_or_cookie_extractor)], ): return {"q_or_cookie": query_or_default} diff --git a/docs_src/dependencies/tutorial008b.py b/docs_src/dependencies/tutorial008b.py new file mode 100644 index 0000000000000..163e96600f9b3 --- /dev/null +++ b/docs_src/dependencies/tutorial008b.py @@ -0,0 +1,30 @@ +from fastapi import Depends, FastAPI, HTTPException + +app = FastAPI() + + +data = { + "plumbus": {"description": "Freshly pickled plumbus", "owner": "Morty"}, + "portal-gun": {"description": "Gun to create portals", "owner": "Rick"}, +} + + +class OwnerError(Exception): + pass + + +def get_username(): + try: + yield "Rick" + except OwnerError as e: + raise HTTPException(status_code=400, detail=f"Owner error: {e}") + + +@app.get("/items/{item_id}") +def get_item(item_id: str, username: str = Depends(get_username)): + if item_id not in data: + raise HTTPException(status_code=404, detail="Item not found") + item = data[item_id] + if item["owner"] != username: + raise OwnerError(username) + return item diff --git a/docs_src/dependencies/tutorial008b_an.py b/docs_src/dependencies/tutorial008b_an.py new file mode 100644 index 0000000000000..84d8f12c14887 --- /dev/null +++ b/docs_src/dependencies/tutorial008b_an.py @@ -0,0 +1,31 @@ +from fastapi import Depends, FastAPI, HTTPException +from typing_extensions import Annotated + +app = FastAPI() + + +data = { + "plumbus": {"description": "Freshly pickled plumbus", "owner": "Morty"}, + "portal-gun": {"description": "Gun to create portals", "owner": "Rick"}, +} + + +class OwnerError(Exception): + pass + + +def get_username(): + try: + yield "Rick" + except OwnerError as e: + raise HTTPException(status_code=400, detail=f"Owner error: {e}") + + +@app.get("/items/{item_id}") +def get_item(item_id: str, username: Annotated[str, Depends(get_username)]): + if item_id not in data: + raise HTTPException(status_code=404, detail="Item not found") + item = data[item_id] + if item["owner"] != username: + raise OwnerError(username) + return item diff --git a/docs_src/dependencies/tutorial008b_an_py39.py b/docs_src/dependencies/tutorial008b_an_py39.py new file mode 100644 index 0000000000000..3b8434c816711 --- /dev/null +++ b/docs_src/dependencies/tutorial008b_an_py39.py @@ -0,0 +1,32 @@ +from typing import Annotated + +from fastapi import Depends, FastAPI, HTTPException + +app = FastAPI() + + +data = { + "plumbus": {"description": "Freshly pickled plumbus", "owner": "Morty"}, + "portal-gun": {"description": "Gun to create portals", "owner": "Rick"}, +} + + +class OwnerError(Exception): + pass + + +def get_username(): + try: + yield "Rick" + except OwnerError as e: + raise HTTPException(status_code=400, detail=f"Owner error: {e}") + + +@app.get("/items/{item_id}") +def get_item(item_id: str, username: Annotated[str, Depends(get_username)]): + if item_id not in data: + raise HTTPException(status_code=404, detail="Item not found") + item = data[item_id] + if item["owner"] != username: + raise OwnerError(username) + return item diff --git a/docs_src/dependencies/tutorial008c.py b/docs_src/dependencies/tutorial008c.py new file mode 100644 index 0000000000000..4b99a5a31150b --- /dev/null +++ b/docs_src/dependencies/tutorial008c.py @@ -0,0 +1,27 @@ +from fastapi import Depends, FastAPI, HTTPException + +app = FastAPI() + + +class InternalError(Exception): + pass + + +def get_username(): + try: + yield "Rick" + except InternalError: + print("Oops, we didn't raise again, Britney 😱") + + +@app.get("/items/{item_id}") +def get_item(item_id: str, username: str = Depends(get_username)): + if item_id == "portal-gun": + raise InternalError( + f"The portal gun is too dangerous to be owned by {username}" + ) + if item_id != "plumbus": + raise HTTPException( + status_code=404, detail="Item not found, there's only a plumbus here" + ) + return item_id diff --git a/docs_src/dependencies/tutorial008c_an.py b/docs_src/dependencies/tutorial008c_an.py new file mode 100644 index 0000000000000..94f59f9aa602b --- /dev/null +++ b/docs_src/dependencies/tutorial008c_an.py @@ -0,0 +1,28 @@ +from fastapi import Depends, FastAPI, HTTPException +from typing_extensions import Annotated + +app = FastAPI() + + +class InternalError(Exception): + pass + + +def get_username(): + try: + yield "Rick" + except InternalError: + print("Oops, we didn't raise again, Britney 😱") + + +@app.get("/items/{item_id}") +def get_item(item_id: str, username: Annotated[str, Depends(get_username)]): + if item_id == "portal-gun": + raise InternalError( + f"The portal gun is too dangerous to be owned by {username}" + ) + if item_id != "plumbus": + raise HTTPException( + status_code=404, detail="Item not found, there's only a plumbus here" + ) + return item_id diff --git a/docs_src/dependencies/tutorial008c_an_py39.py b/docs_src/dependencies/tutorial008c_an_py39.py new file mode 100644 index 0000000000000..da92efa9c3ce5 --- /dev/null +++ b/docs_src/dependencies/tutorial008c_an_py39.py @@ -0,0 +1,29 @@ +from typing import Annotated + +from fastapi import Depends, FastAPI, HTTPException + +app = FastAPI() + + +class InternalError(Exception): + pass + + +def get_username(): + try: + yield "Rick" + except InternalError: + print("Oops, we didn't raise again, Britney 😱") + + +@app.get("/items/{item_id}") +def get_item(item_id: str, username: Annotated[str, Depends(get_username)]): + if item_id == "portal-gun": + raise InternalError( + f"The portal gun is too dangerous to be owned by {username}" + ) + if item_id != "plumbus": + raise HTTPException( + status_code=404, detail="Item not found, there's only a plumbus here" + ) + return item_id diff --git a/docs_src/dependencies/tutorial008d.py b/docs_src/dependencies/tutorial008d.py new file mode 100644 index 0000000000000..93039343d1c39 --- /dev/null +++ b/docs_src/dependencies/tutorial008d.py @@ -0,0 +1,28 @@ +from fastapi import Depends, FastAPI, HTTPException + +app = FastAPI() + + +class InternalError(Exception): + pass + + +def get_username(): + try: + yield "Rick" + except InternalError: + print("We don't swallow the internal error here, we raise again 😎") + raise + + +@app.get("/items/{item_id}") +def get_item(item_id: str, username: str = Depends(get_username)): + if item_id == "portal-gun": + raise InternalError( + f"The portal gun is too dangerous to be owned by {username}" + ) + if item_id != "plumbus": + raise HTTPException( + status_code=404, detail="Item not found, there's only a plumbus here" + ) + return item_id diff --git a/docs_src/dependencies/tutorial008d_an.py b/docs_src/dependencies/tutorial008d_an.py new file mode 100644 index 0000000000000..c354245744954 --- /dev/null +++ b/docs_src/dependencies/tutorial008d_an.py @@ -0,0 +1,29 @@ +from fastapi import Depends, FastAPI, HTTPException +from typing_extensions import Annotated + +app = FastAPI() + + +class InternalError(Exception): + pass + + +def get_username(): + try: + yield "Rick" + except InternalError: + print("We don't swallow the internal error here, we raise again 😎") + raise + + +@app.get("/items/{item_id}") +def get_item(item_id: str, username: Annotated[str, Depends(get_username)]): + if item_id == "portal-gun": + raise InternalError( + f"The portal gun is too dangerous to be owned by {username}" + ) + if item_id != "plumbus": + raise HTTPException( + status_code=404, detail="Item not found, there's only a plumbus here" + ) + return item_id diff --git a/docs_src/dependencies/tutorial008d_an_py39.py b/docs_src/dependencies/tutorial008d_an_py39.py new file mode 100644 index 0000000000000..99bd5cb911392 --- /dev/null +++ b/docs_src/dependencies/tutorial008d_an_py39.py @@ -0,0 +1,30 @@ +from typing import Annotated + +from fastapi import Depends, FastAPI, HTTPException + +app = FastAPI() + + +class InternalError(Exception): + pass + + +def get_username(): + try: + yield "Rick" + except InternalError: + print("We don't swallow the internal error here, we raise again 😎") + raise + + +@app.get("/items/{item_id}") +def get_item(item_id: str, username: Annotated[str, Depends(get_username)]): + if item_id == "portal-gun": + raise InternalError( + f"The portal gun is too dangerous to be owned by {username}" + ) + if item_id != "plumbus": + raise HTTPException( + status_code=404, detail="Item not found, there's only a plumbus here" + ) + return item_id diff --git a/docs_src/extending_openapi/tutorial001.py b/docs_src/extending_openapi/tutorial001.py index 561e95898f5f4..35e31c0e0c943 100644 --- a/docs_src/extending_openapi/tutorial001.py +++ b/docs_src/extending_openapi/tutorial001.py @@ -15,7 +15,8 @@ def custom_openapi(): openapi_schema = get_openapi( title="Custom title", version="2.5.0", - description="This is a very custom OpenAPI schema", + summary="This is a very custom OpenAPI schema", + description="Here's a longer description of the custom **OpenAPI** schema", routes=app.routes, ) openapi_schema["info"]["x-logo"] = { diff --git a/docs_src/extra_models/tutorial003.py b/docs_src/extra_models/tutorial003.py index 065439acceb7d..06675cbc09808 100644 --- a/docs_src/extra_models/tutorial003.py +++ b/docs_src/extra_models/tutorial003.py @@ -12,11 +12,11 @@ class BaseItem(BaseModel): class CarItem(BaseItem): - type = "car" + type: str = "car" class PlaneItem(BaseItem): - type = "plane" + type: str = "plane" size: int diff --git a/docs_src/extra_models/tutorial003_py310.py b/docs_src/extra_models/tutorial003_py310.py index 065439acceb7d..06675cbc09808 100644 --- a/docs_src/extra_models/tutorial003_py310.py +++ b/docs_src/extra_models/tutorial003_py310.py @@ -12,11 +12,11 @@ class BaseItem(BaseModel): class CarItem(BaseItem): - type = "car" + type: str = "car" class PlaneItem(BaseItem): - type = "plane" + type: str = "plane" size: int diff --git a/docs_src/generate_clients/tutorial004.js b/docs_src/generate_clients/tutorial004.js new file mode 100644 index 0000000000000..fa222ba6cc884 --- /dev/null +++ b/docs_src/generate_clients/tutorial004.js @@ -0,0 +1,36 @@ +import * as fs from 'fs' + +async function modifyOpenAPIFile(filePath) { + try { + const data = await fs.promises.readFile(filePath) + const openapiContent = JSON.parse(data) + + const paths = openapiContent.paths + for (const pathKey of Object.keys(paths)) { + const pathData = paths[pathKey] + for (const method of Object.keys(pathData)) { + const operation = pathData[method] + if (operation.tags && operation.tags.length > 0) { + const tag = operation.tags[0] + const operationId = operation.operationId + const toRemove = `${tag}-` + if (operationId.startsWith(toRemove)) { + const newOperationId = operationId.substring(toRemove.length) + operation.operationId = newOperationId + } + } + } + } + + await fs.promises.writeFile( + filePath, + JSON.stringify(openapiContent, null, 2), + ) + console.log('File successfully modified') + } catch (err) { + console.error('Error:', err) + } +} + +const filePath = './openapi.json' +modifyOpenAPIFile(filePath) diff --git a/docs_src/header_params/tutorial002.py b/docs_src/header_params/tutorial002.py index 639ab1735d068..0a34f17cc4b59 100644 --- a/docs_src/header_params/tutorial002.py +++ b/docs_src/header_params/tutorial002.py @@ -7,6 +7,6 @@ @app.get("/items/") async def read_items( - strange_header: Union[str, None] = Header(default=None, convert_underscores=False) + strange_header: Union[str, None] = Header(default=None, convert_underscores=False), ): return {"strange_header": strange_header} diff --git a/docs_src/header_params/tutorial002_an.py b/docs_src/header_params/tutorial002_an.py index 65d972d46eec8..82fe49ba2b1b9 100644 --- a/docs_src/header_params/tutorial002_an.py +++ b/docs_src/header_params/tutorial002_an.py @@ -10,6 +10,6 @@ async def read_items( strange_header: Annotated[ Union[str, None], Header(convert_underscores=False) - ] = None + ] = None, ): return {"strange_header": strange_header} diff --git a/docs_src/header_params/tutorial002_an_py310.py b/docs_src/header_params/tutorial002_an_py310.py index b340647b600d0..8a102749f289f 100644 --- a/docs_src/header_params/tutorial002_an_py310.py +++ b/docs_src/header_params/tutorial002_an_py310.py @@ -7,6 +7,6 @@ @app.get("/items/") async def read_items( - strange_header: Annotated[str | None, Header(convert_underscores=False)] = None + strange_header: Annotated[str | None, Header(convert_underscores=False)] = None, ): return {"strange_header": strange_header} diff --git a/docs_src/header_params/tutorial002_an_py39.py b/docs_src/header_params/tutorial002_an_py39.py index 7f6a99f9c3690..008e4b6e1a1a5 100644 --- a/docs_src/header_params/tutorial002_an_py39.py +++ b/docs_src/header_params/tutorial002_an_py39.py @@ -9,6 +9,6 @@ async def read_items( strange_header: Annotated[ Union[str, None], Header(convert_underscores=False) - ] = None + ] = None, ): return {"strange_header": strange_header} diff --git a/docs_src/header_params/tutorial002_py310.py b/docs_src/header_params/tutorial002_py310.py index b7979b542a143..10d6716c649e7 100644 --- a/docs_src/header_params/tutorial002_py310.py +++ b/docs_src/header_params/tutorial002_py310.py @@ -5,6 +5,6 @@ @app.get("/items/") async def read_items( - strange_header: str | None = Header(default=None, convert_underscores=False) + strange_header: str | None = Header(default=None, convert_underscores=False), ): return {"strange_header": strange_header} diff --git a/docs_src/metadata/tutorial001.py b/docs_src/metadata/tutorial001.py index 3fba9e7d1b272..76656e81b4246 100644 --- a/docs_src/metadata/tutorial001.py +++ b/docs_src/metadata/tutorial001.py @@ -18,6 +18,7 @@ app = FastAPI( title="ChimichangApp", description=description, + summary="Deadpool's favorite app. Nuff said.", version="0.0.1", terms_of_service="http://example.com/terms/", contact={ diff --git a/docs_src/metadata/tutorial001_1.py b/docs_src/metadata/tutorial001_1.py new file mode 100644 index 0000000000000..a8f5b94588d9c --- /dev/null +++ b/docs_src/metadata/tutorial001_1.py @@ -0,0 +1,38 @@ +from fastapi import FastAPI + +description = """ +ChimichangApp API helps you do awesome stuff. 🚀 + +## Items + +You can **read items**. + +## Users + +You will be able to: + +* **Create users** (_not implemented_). +* **Read users** (_not implemented_). +""" + +app = FastAPI( + title="ChimichangApp", + description=description, + summary="Deadpool's favorite app. Nuff said.", + version="0.0.1", + terms_of_service="http://example.com/terms/", + contact={ + "name": "Deadpoolio the Amazing", + "url": "http://x-force.example.com/contact/", + "email": "dp@x-force.example.com", + }, + license_info={ + "name": "Apache 2.0", + "identifier": "MIT", + }, +) + + +@app.get("/items/") +async def read_items(): + return [{"name": "Katana"}] diff --git a/docs_src/openapi_webhooks/tutorial001.py b/docs_src/openapi_webhooks/tutorial001.py new file mode 100644 index 0000000000000..55822bb48f2ed --- /dev/null +++ b/docs_src/openapi_webhooks/tutorial001.py @@ -0,0 +1,25 @@ +from datetime import datetime + +from fastapi import FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Subscription(BaseModel): + username: str + monthly_fee: float + start_date: datetime + + +@app.webhooks.post("new-subscription") +def new_subscription(body: Subscription): + """ + When a new user subscribes to your service we'll send you a POST request with this + data to the URL that you register for the event `new-subscription` in the dashboard. + """ + + +@app.get("/users/") +def read_users(): + return ["Rick", "Morty"] diff --git a/docs_src/path_operation_advanced_configuration/tutorial007.py b/docs_src/path_operation_advanced_configuration/tutorial007.py index d51752bb875cc..972ddbd2cc918 100644 --- a/docs_src/path_operation_advanced_configuration/tutorial007.py +++ b/docs_src/path_operation_advanced_configuration/tutorial007.py @@ -16,7 +16,7 @@ class Item(BaseModel): "/items/", openapi_extra={ "requestBody": { - "content": {"application/x-yaml": {"schema": Item.schema()}}, + "content": {"application/x-yaml": {"schema": Item.model_json_schema()}}, "required": True, }, }, @@ -28,7 +28,7 @@ async def create_item(request: Request): except yaml.YAMLError: raise HTTPException(status_code=422, detail="Invalid YAML") try: - item = Item.parse_obj(data) + item = Item.model_validate(data) except ValidationError as e: raise HTTPException(status_code=422, detail=e.errors()) return item diff --git a/docs_src/path_operation_advanced_configuration/tutorial007_pv1.py b/docs_src/path_operation_advanced_configuration/tutorial007_pv1.py new file mode 100644 index 0000000000000..d51752bb875cc --- /dev/null +++ b/docs_src/path_operation_advanced_configuration/tutorial007_pv1.py @@ -0,0 +1,34 @@ +from typing import List + +import yaml +from fastapi import FastAPI, HTTPException, Request +from pydantic import BaseModel, ValidationError + +app = FastAPI() + + +class Item(BaseModel): + name: str + tags: List[str] + + +@app.post( + "/items/", + openapi_extra={ + "requestBody": { + "content": {"application/x-yaml": {"schema": Item.schema()}}, + "required": True, + }, + }, +) +async def create_item(request: Request): + raw_body = await request.body() + try: + data = yaml.safe_load(raw_body) + except yaml.YAMLError: + raise HTTPException(status_code=422, detail="Invalid YAML") + try: + item = Item.parse_obj(data) + except ValidationError as e: + raise HTTPException(status_code=422, detail=e.errors()) + return item diff --git a/docs_src/python_types/tutorial011.py b/docs_src/python_types/tutorial011.py index c8634cbff505a..297a84db68ca0 100644 --- a/docs_src/python_types/tutorial011.py +++ b/docs_src/python_types/tutorial011.py @@ -6,7 +6,7 @@ class User(BaseModel): id: int - name = "John Doe" + name: str = "John Doe" signup_ts: Union[datetime, None] = None friends: List[int] = [] diff --git a/docs_src/python_types/tutorial011_py310.py b/docs_src/python_types/tutorial011_py310.py index 7f173880f5b89..842760c60d24f 100644 --- a/docs_src/python_types/tutorial011_py310.py +++ b/docs_src/python_types/tutorial011_py310.py @@ -5,7 +5,7 @@ class User(BaseModel): id: int - name = "John Doe" + name: str = "John Doe" signup_ts: datetime | None = None friends: list[int] = [] diff --git a/docs_src/python_types/tutorial011_py39.py b/docs_src/python_types/tutorial011_py39.py index 468496f519325..4eb40b405fe50 100644 --- a/docs_src/python_types/tutorial011_py39.py +++ b/docs_src/python_types/tutorial011_py39.py @@ -6,7 +6,7 @@ class User(BaseModel): id: int - name = "John Doe" + name: str = "John Doe" signup_ts: Union[datetime, None] = None friends: list[int] = [] diff --git a/docs_src/query_params_str_validations/tutorial003.py b/docs_src/query_params_str_validations/tutorial003.py index 73d2e08c8ef0d..7d4917373a342 100644 --- a/docs_src/query_params_str_validations/tutorial003.py +++ b/docs_src/query_params_str_validations/tutorial003.py @@ -7,7 +7,7 @@ @app.get("/items/") async def read_items( - q: Union[str, None] = Query(default=None, min_length=3, max_length=50) + q: Union[str, None] = Query(default=None, min_length=3, max_length=50), ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial003_an.py b/docs_src/query_params_str_validations/tutorial003_an.py index a3665f6a85d6c..0dd14086cf245 100644 --- a/docs_src/query_params_str_validations/tutorial003_an.py +++ b/docs_src/query_params_str_validations/tutorial003_an.py @@ -8,7 +8,7 @@ @app.get("/items/") async def read_items( - q: Annotated[Union[str, None], Query(min_length=3, max_length=50)] = None + q: Annotated[Union[str, None], Query(min_length=3, max_length=50)] = None, ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial003_an_py310.py b/docs_src/query_params_str_validations/tutorial003_an_py310.py index 836af04de0bee..79a604b6ce935 100644 --- a/docs_src/query_params_str_validations/tutorial003_an_py310.py +++ b/docs_src/query_params_str_validations/tutorial003_an_py310.py @@ -7,7 +7,7 @@ @app.get("/items/") async def read_items( - q: Annotated[str | None, Query(min_length=3, max_length=50)] = None + q: Annotated[str | None, Query(min_length=3, max_length=50)] = None, ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial003_an_py39.py b/docs_src/query_params_str_validations/tutorial003_an_py39.py index 87a4268394a61..3d6697793fd48 100644 --- a/docs_src/query_params_str_validations/tutorial003_an_py39.py +++ b/docs_src/query_params_str_validations/tutorial003_an_py39.py @@ -7,7 +7,7 @@ @app.get("/items/") async def read_items( - q: Annotated[Union[str, None], Query(min_length=3, max_length=50)] = None + q: Annotated[Union[str, None], Query(min_length=3, max_length=50)] = None, ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial004.py b/docs_src/query_params_str_validations/tutorial004.py index 5a7129816c4a6..64a647a16a566 100644 --- a/docs_src/query_params_str_validations/tutorial004.py +++ b/docs_src/query_params_str_validations/tutorial004.py @@ -8,8 +8,8 @@ @app.get("/items/") async def read_items( q: Union[str, None] = Query( - default=None, min_length=3, max_length=50, regex="^fixedquery$" - ) + default=None, min_length=3, max_length=50, pattern="^fixedquery$" + ), ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial004_an.py b/docs_src/query_params_str_validations/tutorial004_an.py index 5346b997bd09d..c75d45d63e777 100644 --- a/docs_src/query_params_str_validations/tutorial004_an.py +++ b/docs_src/query_params_str_validations/tutorial004_an.py @@ -9,8 +9,8 @@ @app.get("/items/") async def read_items( q: Annotated[ - Union[str, None], Query(min_length=3, max_length=50, regex="^fixedquery$") - ] = None + Union[str, None], Query(min_length=3, max_length=50, pattern="^fixedquery$") + ] = None, ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial004_an_py310.py b/docs_src/query_params_str_validations/tutorial004_an_py310.py index 8fd375b3d549f..20cf1988fdd8a 100644 --- a/docs_src/query_params_str_validations/tutorial004_an_py310.py +++ b/docs_src/query_params_str_validations/tutorial004_an_py310.py @@ -8,8 +8,8 @@ @app.get("/items/") async def read_items( q: Annotated[ - str | None, Query(min_length=3, max_length=50, regex="^fixedquery$") - ] = None + str | None, Query(min_length=3, max_length=50, pattern="^fixedquery$") + ] = None, ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial004_an_py310_regex.py b/docs_src/query_params_str_validations/tutorial004_an_py310_regex.py new file mode 100644 index 0000000000000..21e0d3eb856f8 --- /dev/null +++ b/docs_src/query_params_str_validations/tutorial004_an_py310_regex.py @@ -0,0 +1,17 @@ +from typing import Annotated + +from fastapi import FastAPI, Query + +app = FastAPI() + + +@app.get("/items/") +async def read_items( + q: Annotated[ + str | None, Query(min_length=3, max_length=50, regex="^fixedquery$") + ] = None, +): + results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} + if q: + results.update({"q": q}) + return results diff --git a/docs_src/query_params_str_validations/tutorial004_an_py39.py b/docs_src/query_params_str_validations/tutorial004_an_py39.py index 2fd82db754636..de27097b3860b 100644 --- a/docs_src/query_params_str_validations/tutorial004_an_py39.py +++ b/docs_src/query_params_str_validations/tutorial004_an_py39.py @@ -8,8 +8,8 @@ @app.get("/items/") async def read_items( q: Annotated[ - Union[str, None], Query(min_length=3, max_length=50, regex="^fixedquery$") - ] = None + Union[str, None], Query(min_length=3, max_length=50, pattern="^fixedquery$") + ] = None, ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial004_py310.py b/docs_src/query_params_str_validations/tutorial004_py310.py index 180a2e5112a0b..7801e75000f8d 100644 --- a/docs_src/query_params_str_validations/tutorial004_py310.py +++ b/docs_src/query_params_str_validations/tutorial004_py310.py @@ -5,8 +5,9 @@ @app.get("/items/") async def read_items( - q: str - | None = Query(default=None, min_length=3, max_length=50, regex="^fixedquery$") + q: str | None = Query( + default=None, min_length=3, max_length=50, pattern="^fixedquery$" + ), ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial007.py b/docs_src/query_params_str_validations/tutorial007.py index cb836569e980e..27b649e1455d4 100644 --- a/docs_src/query_params_str_validations/tutorial007.py +++ b/docs_src/query_params_str_validations/tutorial007.py @@ -7,7 +7,7 @@ @app.get("/items/") async def read_items( - q: Union[str, None] = Query(default=None, title="Query string", min_length=3) + q: Union[str, None] = Query(default=None, title="Query string", min_length=3), ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial007_an.py b/docs_src/query_params_str_validations/tutorial007_an.py index 3bc85cc0cf511..4b3c8de4b9257 100644 --- a/docs_src/query_params_str_validations/tutorial007_an.py +++ b/docs_src/query_params_str_validations/tutorial007_an.py @@ -8,7 +8,7 @@ @app.get("/items/") async def read_items( - q: Annotated[Union[str, None], Query(title="Query string", min_length=3)] = None + q: Annotated[Union[str, None], Query(title="Query string", min_length=3)] = None, ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial007_an_py310.py b/docs_src/query_params_str_validations/tutorial007_an_py310.py index 5933911fdfaaf..ef18e500d6cb3 100644 --- a/docs_src/query_params_str_validations/tutorial007_an_py310.py +++ b/docs_src/query_params_str_validations/tutorial007_an_py310.py @@ -7,7 +7,7 @@ @app.get("/items/") async def read_items( - q: Annotated[str | None, Query(title="Query string", min_length=3)] = None + q: Annotated[str | None, Query(title="Query string", min_length=3)] = None, ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial007_an_py39.py b/docs_src/query_params_str_validations/tutorial007_an_py39.py index dafa1c5c94988..8d7a82c4658ad 100644 --- a/docs_src/query_params_str_validations/tutorial007_an_py39.py +++ b/docs_src/query_params_str_validations/tutorial007_an_py39.py @@ -7,7 +7,7 @@ @app.get("/items/") async def read_items( - q: Annotated[Union[str, None], Query(title="Query string", min_length=3)] = None + q: Annotated[Union[str, None], Query(title="Query string", min_length=3)] = None, ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial007_py310.py b/docs_src/query_params_str_validations/tutorial007_py310.py index e3e1ef2e08711..c283576d52b52 100644 --- a/docs_src/query_params_str_validations/tutorial007_py310.py +++ b/docs_src/query_params_str_validations/tutorial007_py310.py @@ -5,7 +5,7 @@ @app.get("/items/") async def read_items( - q: str | None = Query(default=None, title="Query string", min_length=3) + q: str | None = Query(default=None, title="Query string", min_length=3), ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial008.py b/docs_src/query_params_str_validations/tutorial008.py index d112a9ab8aa5a..e3e0b50aa14e8 100644 --- a/docs_src/query_params_str_validations/tutorial008.py +++ b/docs_src/query_params_str_validations/tutorial008.py @@ -12,7 +12,7 @@ async def read_items( title="Query string", description="Query string for the items to search in the database that have a good match", min_length=3, - ) + ), ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial008_an.py b/docs_src/query_params_str_validations/tutorial008_an.py index 5699f1e88d596..01606a9203624 100644 --- a/docs_src/query_params_str_validations/tutorial008_an.py +++ b/docs_src/query_params_str_validations/tutorial008_an.py @@ -15,7 +15,7 @@ async def read_items( description="Query string for the items to search in the database that have a good match", min_length=3, ), - ] = None + ] = None, ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial008_an_py310.py b/docs_src/query_params_str_validations/tutorial008_an_py310.py index 4aaadf8b4785e..44b3082b63bad 100644 --- a/docs_src/query_params_str_validations/tutorial008_an_py310.py +++ b/docs_src/query_params_str_validations/tutorial008_an_py310.py @@ -14,7 +14,7 @@ async def read_items( description="Query string for the items to search in the database that have a good match", min_length=3, ), - ] = None + ] = None, ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial008_an_py39.py b/docs_src/query_params_str_validations/tutorial008_an_py39.py index 1c3b36176517d..f3f2f2c0e7915 100644 --- a/docs_src/query_params_str_validations/tutorial008_an_py39.py +++ b/docs_src/query_params_str_validations/tutorial008_an_py39.py @@ -14,7 +14,7 @@ async def read_items( description="Query string for the items to search in the database that have a good match", min_length=3, ), - ] = None + ] = None, ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial008_py310.py b/docs_src/query_params_str_validations/tutorial008_py310.py index 489f631d5e908..57438527262fd 100644 --- a/docs_src/query_params_str_validations/tutorial008_py310.py +++ b/docs_src/query_params_str_validations/tutorial008_py310.py @@ -5,13 +5,12 @@ @app.get("/items/") async def read_items( - q: str - | None = Query( + q: str | None = Query( default=None, title="Query string", description="Query string for the items to search in the database that have a good match", min_length=3, - ) + ), ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial010.py b/docs_src/query_params_str_validations/tutorial010.py index 35443d1947061..ff29176fe5f28 100644 --- a/docs_src/query_params_str_validations/tutorial010.py +++ b/docs_src/query_params_str_validations/tutorial010.py @@ -14,9 +14,9 @@ async def read_items( description="Query string for the items to search in the database that have a good match", min_length=3, max_length=50, - regex="^fixedquery$", + pattern="^fixedquery$", deprecated=True, - ) + ), ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial010_an.py b/docs_src/query_params_str_validations/tutorial010_an.py index 8995f3f57a345..ed343230f4bda 100644 --- a/docs_src/query_params_str_validations/tutorial010_an.py +++ b/docs_src/query_params_str_validations/tutorial010_an.py @@ -16,10 +16,10 @@ async def read_items( description="Query string for the items to search in the database that have a good match", min_length=3, max_length=50, - regex="^fixedquery$", + pattern="^fixedquery$", deprecated=True, ), - ] = None + ] = None, ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial010_an_py310.py b/docs_src/query_params_str_validations/tutorial010_an_py310.py index cfa81926cf722..775095bda86ae 100644 --- a/docs_src/query_params_str_validations/tutorial010_an_py310.py +++ b/docs_src/query_params_str_validations/tutorial010_an_py310.py @@ -15,10 +15,10 @@ async def read_items( description="Query string for the items to search in the database that have a good match", min_length=3, max_length=50, - regex="^fixedquery$", + pattern="^fixedquery$", deprecated=True, ), - ] = None + ] = None, ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial010_an_py39.py b/docs_src/query_params_str_validations/tutorial010_an_py39.py index 220eaabf477ff..b126c116f0cd3 100644 --- a/docs_src/query_params_str_validations/tutorial010_an_py39.py +++ b/docs_src/query_params_str_validations/tutorial010_an_py39.py @@ -15,10 +15,10 @@ async def read_items( description="Query string for the items to search in the database that have a good match", min_length=3, max_length=50, - regex="^fixedquery$", + pattern="^fixedquery$", deprecated=True, ), - ] = None + ] = None, ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial010_py310.py b/docs_src/query_params_str_validations/tutorial010_py310.py index f2839516e6446..530e6cf5b6c93 100644 --- a/docs_src/query_params_str_validations/tutorial010_py310.py +++ b/docs_src/query_params_str_validations/tutorial010_py310.py @@ -5,17 +5,16 @@ @app.get("/items/") async def read_items( - q: str - | None = Query( + q: str | None = Query( default=None, alias="item-query", title="Query string", description="Query string for the items to search in the database that have a good match", min_length=3, max_length=50, - regex="^fixedquery$", + pattern="^fixedquery$", deprecated=True, - ) + ), ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial014.py b/docs_src/query_params_str_validations/tutorial014.py index 50e0a6c2b18ce..779db1c80ed58 100644 --- a/docs_src/query_params_str_validations/tutorial014.py +++ b/docs_src/query_params_str_validations/tutorial014.py @@ -7,7 +7,7 @@ @app.get("/items/") async def read_items( - hidden_query: Union[str, None] = Query(default=None, include_in_schema=False) + hidden_query: Union[str, None] = Query(default=None, include_in_schema=False), ): if hidden_query: return {"hidden_query": hidden_query} diff --git a/docs_src/query_params_str_validations/tutorial014_an.py b/docs_src/query_params_str_validations/tutorial014_an.py index a9a9c44270c44..2eaa585407db1 100644 --- a/docs_src/query_params_str_validations/tutorial014_an.py +++ b/docs_src/query_params_str_validations/tutorial014_an.py @@ -8,7 +8,7 @@ @app.get("/items/") async def read_items( - hidden_query: Annotated[Union[str, None], Query(include_in_schema=False)] = None + hidden_query: Annotated[Union[str, None], Query(include_in_schema=False)] = None, ): if hidden_query: return {"hidden_query": hidden_query} diff --git a/docs_src/query_params_str_validations/tutorial014_an_py310.py b/docs_src/query_params_str_validations/tutorial014_an_py310.py index 5fba54150be79..e728dbdb597f7 100644 --- a/docs_src/query_params_str_validations/tutorial014_an_py310.py +++ b/docs_src/query_params_str_validations/tutorial014_an_py310.py @@ -7,7 +7,7 @@ @app.get("/items/") async def read_items( - hidden_query: Annotated[str | None, Query(include_in_schema=False)] = None + hidden_query: Annotated[str | None, Query(include_in_schema=False)] = None, ): if hidden_query: return {"hidden_query": hidden_query} diff --git a/docs_src/query_params_str_validations/tutorial014_an_py39.py b/docs_src/query_params_str_validations/tutorial014_an_py39.py index b079852100f64..aaf7703a5786f 100644 --- a/docs_src/query_params_str_validations/tutorial014_an_py39.py +++ b/docs_src/query_params_str_validations/tutorial014_an_py39.py @@ -7,7 +7,7 @@ @app.get("/items/") async def read_items( - hidden_query: Annotated[Union[str, None], Query(include_in_schema=False)] = None + hidden_query: Annotated[Union[str, None], Query(include_in_schema=False)] = None, ): if hidden_query: return {"hidden_query": hidden_query} diff --git a/docs_src/query_params_str_validations/tutorial014_py310.py b/docs_src/query_params_str_validations/tutorial014_py310.py index 1b617efdd128a..97bb3386ee0f9 100644 --- a/docs_src/query_params_str_validations/tutorial014_py310.py +++ b/docs_src/query_params_str_validations/tutorial014_py310.py @@ -5,7 +5,7 @@ @app.get("/items/") async def read_items( - hidden_query: str | None = Query(default=None, include_in_schema=False) + hidden_query: str | None = Query(default=None, include_in_schema=False), ): if hidden_query: return {"hidden_query": hidden_query} diff --git a/docs_src/schema_extra_example/tutorial001.py b/docs_src/schema_extra_example/tutorial001.py index a5ae281274df2..32a66db3a97b8 100644 --- a/docs_src/schema_extra_example/tutorial001.py +++ b/docs_src/schema_extra_example/tutorial001.py @@ -12,15 +12,18 @@ class Item(BaseModel): price: float tax: Union[float, None] = None - class Config: - schema_extra = { - "example": { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - } + model_config = { + "json_schema_extra": { + "examples": [ + { + "name": "Foo", + "description": "A very nice Item", + "price": 35.4, + "tax": 3.2, + } + ] } + } @app.put("/items/{item_id}") diff --git a/docs_src/schema_extra_example/tutorial001_pv1.py b/docs_src/schema_extra_example/tutorial001_pv1.py new file mode 100644 index 0000000000000..6ab96ff859d0d --- /dev/null +++ b/docs_src/schema_extra_example/tutorial001_pv1.py @@ -0,0 +1,31 @@ +from typing import Union + +from fastapi import FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Item(BaseModel): + name: str + description: Union[str, None] = None + price: float + tax: Union[float, None] = None + + class Config: + schema_extra = { + "examples": [ + { + "name": "Foo", + "description": "A very nice Item", + "price": 35.4, + "tax": 3.2, + } + ] + } + + +@app.put("/items/{item_id}") +async def update_item(item_id: int, item: Item): + results = {"item_id": item_id, "item": item} + return results diff --git a/docs_src/schema_extra_example/tutorial001_py310.py b/docs_src/schema_extra_example/tutorial001_py310.py index 77ceedd60d39f..84aa5fc122c4f 100644 --- a/docs_src/schema_extra_example/tutorial001_py310.py +++ b/docs_src/schema_extra_example/tutorial001_py310.py @@ -10,15 +10,18 @@ class Item(BaseModel): price: float tax: float | None = None - class Config: - schema_extra = { - "example": { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - } + model_config = { + "json_schema_extra": { + "examples": [ + { + "name": "Foo", + "description": "A very nice Item", + "price": 35.4, + "tax": 3.2, + } + ] } + } @app.put("/items/{item_id}") diff --git a/docs_src/schema_extra_example/tutorial001_py310_pv1.py b/docs_src/schema_extra_example/tutorial001_py310_pv1.py new file mode 100644 index 0000000000000..ec83f1112f20f --- /dev/null +++ b/docs_src/schema_extra_example/tutorial001_py310_pv1.py @@ -0,0 +1,29 @@ +from fastapi import FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Item(BaseModel): + name: str + description: str | None = None + price: float + tax: float | None = None + + class Config: + schema_extra = { + "examples": [ + { + "name": "Foo", + "description": "A very nice Item", + "price": 35.4, + "tax": 3.2, + } + ] + } + + +@app.put("/items/{item_id}") +async def update_item(item_id: int, item: Item): + results = {"item_id": item_id, "item": item} + return results diff --git a/docs_src/schema_extra_example/tutorial002.py b/docs_src/schema_extra_example/tutorial002.py index 6de434f81d1fd..70f06567c3787 100644 --- a/docs_src/schema_extra_example/tutorial002.py +++ b/docs_src/schema_extra_example/tutorial002.py @@ -7,10 +7,10 @@ class Item(BaseModel): - name: str = Field(example="Foo") - description: Union[str, None] = Field(default=None, example="A very nice Item") - price: float = Field(example=35.4) - tax: Union[float, None] = Field(default=None, example=3.2) + name: str = Field(examples=["Foo"]) + description: Union[str, None] = Field(default=None, examples=["A very nice Item"]) + price: float = Field(examples=[35.4]) + tax: Union[float, None] = Field(default=None, examples=[3.2]) @app.put("/items/{item_id}") diff --git a/docs_src/schema_extra_example/tutorial002_py310.py b/docs_src/schema_extra_example/tutorial002_py310.py index e84928bb11980..27d78686763e5 100644 --- a/docs_src/schema_extra_example/tutorial002_py310.py +++ b/docs_src/schema_extra_example/tutorial002_py310.py @@ -5,10 +5,10 @@ class Item(BaseModel): - name: str = Field(example="Foo") - description: str | None = Field(default=None, example="A very nice Item") - price: float = Field(example=35.4) - tax: float | None = Field(default=None, example=3.2) + name: str = Field(examples=["Foo"]) + description: str | None = Field(default=None, examples=["A very nice Item"]) + price: float = Field(examples=[35.4]) + tax: float | None = Field(default=None, examples=[3.2]) @app.put("/items/{item_id}") diff --git a/docs_src/schema_extra_example/tutorial003.py b/docs_src/schema_extra_example/tutorial003.py index ce1736bbaf191..385f3de8a1c81 100644 --- a/docs_src/schema_extra_example/tutorial003.py +++ b/docs_src/schema_extra_example/tutorial003.py @@ -17,12 +17,14 @@ class Item(BaseModel): async def update_item( item_id: int, item: Item = Body( - example={ - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, + examples=[ + { + "name": "Foo", + "description": "A very nice Item", + "price": 35.4, + "tax": 3.2, + } + ], ), ): results = {"item_id": item_id, "item": item} diff --git a/docs_src/schema_extra_example/tutorial003_an.py b/docs_src/schema_extra_example/tutorial003_an.py index 1dec555a944e5..23675aba14f8f 100644 --- a/docs_src/schema_extra_example/tutorial003_an.py +++ b/docs_src/schema_extra_example/tutorial003_an.py @@ -20,12 +20,14 @@ async def update_item( item: Annotated[ Item, Body( - example={ - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, + examples=[ + { + "name": "Foo", + "description": "A very nice Item", + "price": 35.4, + "tax": 3.2, + } + ], ), ], ): diff --git a/docs_src/schema_extra_example/tutorial003_an_py310.py b/docs_src/schema_extra_example/tutorial003_an_py310.py index 9edaddfb8ea75..bbd2e171ec9dd 100644 --- a/docs_src/schema_extra_example/tutorial003_an_py310.py +++ b/docs_src/schema_extra_example/tutorial003_an_py310.py @@ -19,12 +19,14 @@ async def update_item( item: Annotated[ Item, Body( - example={ - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, + examples=[ + { + "name": "Foo", + "description": "A very nice Item", + "price": 35.4, + "tax": 3.2, + } + ], ), ], ): diff --git a/docs_src/schema_extra_example/tutorial003_an_py39.py b/docs_src/schema_extra_example/tutorial003_an_py39.py index fe08847d9898e..4728085617f6e 100644 --- a/docs_src/schema_extra_example/tutorial003_an_py39.py +++ b/docs_src/schema_extra_example/tutorial003_an_py39.py @@ -19,12 +19,14 @@ async def update_item( item: Annotated[ Item, Body( - example={ - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, + examples=[ + { + "name": "Foo", + "description": "A very nice Item", + "price": 35.4, + "tax": 3.2, + } + ], ), ], ): diff --git a/docs_src/schema_extra_example/tutorial003_py310.py b/docs_src/schema_extra_example/tutorial003_py310.py index 1e137101d9e46..2d31619be2000 100644 --- a/docs_src/schema_extra_example/tutorial003_py310.py +++ b/docs_src/schema_extra_example/tutorial003_py310.py @@ -15,12 +15,14 @@ class Item(BaseModel): async def update_item( item_id: int, item: Item = Body( - example={ - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, + examples=[ + { + "name": "Foo", + "description": "A very nice Item", + "price": 35.4, + "tax": 3.2, + } + ], ), ): results = {"item_id": item_id, "item": item} diff --git a/docs_src/schema_extra_example/tutorial004.py b/docs_src/schema_extra_example/tutorial004.py index b67edf30cd715..75514a3e914ad 100644 --- a/docs_src/schema_extra_example/tutorial004.py +++ b/docs_src/schema_extra_example/tutorial004.py @@ -18,33 +18,22 @@ async def update_item( *, item_id: int, item: Item = Body( - examples={ - "normal": { - "summary": "A normal example", - "description": "A **normal** item works correctly.", - "value": { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, + examples=[ + { + "name": "Foo", + "description": "A very nice Item", + "price": 35.4, + "tax": 3.2, }, - "converted": { - "summary": "An example with converted data", - "description": "FastAPI can convert price `strings` to actual `numbers` automatically", - "value": { - "name": "Bar", - "price": "35.4", - }, + { + "name": "Bar", + "price": "35.4", }, - "invalid": { - "summary": "Invalid data is rejected with an error", - "value": { - "name": "Baz", - "price": "thirty five point four", - }, + { + "name": "Baz", + "price": "thirty five point four", }, - }, + ], ), ): results = {"item_id": item_id, "item": item} diff --git a/docs_src/schema_extra_example/tutorial004_an.py b/docs_src/schema_extra_example/tutorial004_an.py index 82c9a92ac1353..e817302a2240d 100644 --- a/docs_src/schema_extra_example/tutorial004_an.py +++ b/docs_src/schema_extra_example/tutorial004_an.py @@ -21,33 +21,22 @@ async def update_item( item: Annotated[ Item, Body( - examples={ - "normal": { - "summary": "A normal example", - "description": "A **normal** item works correctly.", - "value": { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, + examples=[ + { + "name": "Foo", + "description": "A very nice Item", + "price": 35.4, + "tax": 3.2, }, - "converted": { - "summary": "An example with converted data", - "description": "FastAPI can convert price `strings` to actual `numbers` automatically", - "value": { - "name": "Bar", - "price": "35.4", - }, + { + "name": "Bar", + "price": "35.4", }, - "invalid": { - "summary": "Invalid data is rejected with an error", - "value": { - "name": "Baz", - "price": "thirty five point four", - }, + { + "name": "Baz", + "price": "thirty five point four", }, - }, + ], ), ], ): diff --git a/docs_src/schema_extra_example/tutorial004_an_py310.py b/docs_src/schema_extra_example/tutorial004_an_py310.py index 01f1a486cb775..650da3187e8ae 100644 --- a/docs_src/schema_extra_example/tutorial004_an_py310.py +++ b/docs_src/schema_extra_example/tutorial004_an_py310.py @@ -20,33 +20,22 @@ async def update_item( item: Annotated[ Item, Body( - examples={ - "normal": { - "summary": "A normal example", - "description": "A **normal** item works correctly.", - "value": { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, + examples=[ + { + "name": "Foo", + "description": "A very nice Item", + "price": 35.4, + "tax": 3.2, }, - "converted": { - "summary": "An example with converted data", - "description": "FastAPI can convert price `strings` to actual `numbers` automatically", - "value": { - "name": "Bar", - "price": "35.4", - }, + { + "name": "Bar", + "price": "35.4", }, - "invalid": { - "summary": "Invalid data is rejected with an error", - "value": { - "name": "Baz", - "price": "thirty five point four", - }, + { + "name": "Baz", + "price": "thirty five point four", }, - }, + ], ), ], ): diff --git a/docs_src/schema_extra_example/tutorial004_an_py39.py b/docs_src/schema_extra_example/tutorial004_an_py39.py index d50e8aa5f8785..dc5a8fe49c6f9 100644 --- a/docs_src/schema_extra_example/tutorial004_an_py39.py +++ b/docs_src/schema_extra_example/tutorial004_an_py39.py @@ -20,33 +20,22 @@ async def update_item( item: Annotated[ Item, Body( - examples={ - "normal": { - "summary": "A normal example", - "description": "A **normal** item works correctly.", - "value": { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, + examples=[ + { + "name": "Foo", + "description": "A very nice Item", + "price": 35.4, + "tax": 3.2, }, - "converted": { - "summary": "An example with converted data", - "description": "FastAPI can convert price `strings` to actual `numbers` automatically", - "value": { - "name": "Bar", - "price": "35.4", - }, + { + "name": "Bar", + "price": "35.4", }, - "invalid": { - "summary": "Invalid data is rejected with an error", - "value": { - "name": "Baz", - "price": "thirty five point four", - }, + { + "name": "Baz", + "price": "thirty five point four", }, - }, + ], ), ], ): diff --git a/docs_src/schema_extra_example/tutorial004_py310.py b/docs_src/schema_extra_example/tutorial004_py310.py index 100a30860b01a..05996ac2a2225 100644 --- a/docs_src/schema_extra_example/tutorial004_py310.py +++ b/docs_src/schema_extra_example/tutorial004_py310.py @@ -16,33 +16,22 @@ async def update_item( *, item_id: int, item: Item = Body( - examples={ - "normal": { - "summary": "A normal example", - "description": "A **normal** item works correctly.", - "value": { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, + examples=[ + { + "name": "Foo", + "description": "A very nice Item", + "price": 35.4, + "tax": 3.2, }, - "converted": { - "summary": "An example with converted data", - "description": "FastAPI can convert price `strings` to actual `numbers` automatically", - "value": { - "name": "Bar", - "price": "35.4", - }, + { + "name": "Bar", + "price": "35.4", }, - "invalid": { - "summary": "Invalid data is rejected with an error", - "value": { - "name": "Baz", - "price": "thirty five point four", - }, + { + "name": "Baz", + "price": "thirty five point four", }, - }, + ], ), ): results = {"item_id": item_id, "item": item} diff --git a/docs_src/schema_extra_example/tutorial005.py b/docs_src/schema_extra_example/tutorial005.py new file mode 100644 index 0000000000000..b8217c27e9971 --- /dev/null +++ b/docs_src/schema_extra_example/tutorial005.py @@ -0,0 +1,51 @@ +from typing import Union + +from fastapi import Body, FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Item(BaseModel): + name: str + description: Union[str, None] = None + price: float + tax: Union[float, None] = None + + +@app.put("/items/{item_id}") +async def update_item( + *, + item_id: int, + item: Item = Body( + openapi_examples={ + "normal": { + "summary": "A normal example", + "description": "A **normal** item works correctly.", + "value": { + "name": "Foo", + "description": "A very nice Item", + "price": 35.4, + "tax": 3.2, + }, + }, + "converted": { + "summary": "An example with converted data", + "description": "FastAPI can convert price `strings` to actual `numbers` automatically", + "value": { + "name": "Bar", + "price": "35.4", + }, + }, + "invalid": { + "summary": "Invalid data is rejected with an error", + "value": { + "name": "Baz", + "price": "thirty five point four", + }, + }, + }, + ), +): + results = {"item_id": item_id, "item": item} + return results diff --git a/docs_src/schema_extra_example/tutorial005_an.py b/docs_src/schema_extra_example/tutorial005_an.py new file mode 100644 index 0000000000000..4b2d9c662b7d6 --- /dev/null +++ b/docs_src/schema_extra_example/tutorial005_an.py @@ -0,0 +1,55 @@ +from typing import Union + +from fastapi import Body, FastAPI +from pydantic import BaseModel +from typing_extensions import Annotated + +app = FastAPI() + + +class Item(BaseModel): + name: str + description: Union[str, None] = None + price: float + tax: Union[float, None] = None + + +@app.put("/items/{item_id}") +async def update_item( + *, + item_id: int, + item: Annotated[ + Item, + Body( + openapi_examples={ + "normal": { + "summary": "A normal example", + "description": "A **normal** item works correctly.", + "value": { + "name": "Foo", + "description": "A very nice Item", + "price": 35.4, + "tax": 3.2, + }, + }, + "converted": { + "summary": "An example with converted data", + "description": "FastAPI can convert price `strings` to actual `numbers` automatically", + "value": { + "name": "Bar", + "price": "35.4", + }, + }, + "invalid": { + "summary": "Invalid data is rejected with an error", + "value": { + "name": "Baz", + "price": "thirty five point four", + }, + }, + }, + ), + ], +): + results = {"item_id": item_id, "item": item} + return results diff --git a/docs_src/schema_extra_example/tutorial005_an_py310.py b/docs_src/schema_extra_example/tutorial005_an_py310.py new file mode 100644 index 0000000000000..64dc2cf90a723 --- /dev/null +++ b/docs_src/schema_extra_example/tutorial005_an_py310.py @@ -0,0 +1,54 @@ +from typing import Annotated + +from fastapi import Body, FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Item(BaseModel): + name: str + description: str | None = None + price: float + tax: float | None = None + + +@app.put("/items/{item_id}") +async def update_item( + *, + item_id: int, + item: Annotated[ + Item, + Body( + openapi_examples={ + "normal": { + "summary": "A normal example", + "description": "A **normal** item works correctly.", + "value": { + "name": "Foo", + "description": "A very nice Item", + "price": 35.4, + "tax": 3.2, + }, + }, + "converted": { + "summary": "An example with converted data", + "description": "FastAPI can convert price `strings` to actual `numbers` automatically", + "value": { + "name": "Bar", + "price": "35.4", + }, + }, + "invalid": { + "summary": "Invalid data is rejected with an error", + "value": { + "name": "Baz", + "price": "thirty five point four", + }, + }, + }, + ), + ], +): + results = {"item_id": item_id, "item": item} + return results diff --git a/docs_src/schema_extra_example/tutorial005_an_py39.py b/docs_src/schema_extra_example/tutorial005_an_py39.py new file mode 100644 index 0000000000000..edeb1affce572 --- /dev/null +++ b/docs_src/schema_extra_example/tutorial005_an_py39.py @@ -0,0 +1,54 @@ +from typing import Annotated, Union + +from fastapi import Body, FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Item(BaseModel): + name: str + description: Union[str, None] = None + price: float + tax: Union[float, None] = None + + +@app.put("/items/{item_id}") +async def update_item( + *, + item_id: int, + item: Annotated[ + Item, + Body( + openapi_examples={ + "normal": { + "summary": "A normal example", + "description": "A **normal** item works correctly.", + "value": { + "name": "Foo", + "description": "A very nice Item", + "price": 35.4, + "tax": 3.2, + }, + }, + "converted": { + "summary": "An example with converted data", + "description": "FastAPI can convert price `strings` to actual `numbers` automatically", + "value": { + "name": "Bar", + "price": "35.4", + }, + }, + "invalid": { + "summary": "Invalid data is rejected with an error", + "value": { + "name": "Baz", + "price": "thirty five point four", + }, + }, + }, + ), + ], +): + results = {"item_id": item_id, "item": item} + return results diff --git a/docs_src/schema_extra_example/tutorial005_py310.py b/docs_src/schema_extra_example/tutorial005_py310.py new file mode 100644 index 0000000000000..eef973343dffe --- /dev/null +++ b/docs_src/schema_extra_example/tutorial005_py310.py @@ -0,0 +1,49 @@ +from fastapi import Body, FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Item(BaseModel): + name: str + description: str | None = None + price: float + tax: float | None = None + + +@app.put("/items/{item_id}") +async def update_item( + *, + item_id: int, + item: Item = Body( + openapi_examples={ + "normal": { + "summary": "A normal example", + "description": "A **normal** item works correctly.", + "value": { + "name": "Foo", + "description": "A very nice Item", + "price": 35.4, + "tax": 3.2, + }, + }, + "converted": { + "summary": "An example with converted data", + "description": "FastAPI can convert price `strings` to actual `numbers` automatically", + "value": { + "name": "Bar", + "price": "35.4", + }, + }, + "invalid": { + "summary": "Invalid data is rejected with an error", + "value": { + "name": "Baz", + "price": "thirty five point four", + }, + }, + }, + ), +): + results = {"item_id": item_id, "item": item} + return results diff --git a/docs_src/security/tutorial003_an.py b/docs_src/security/tutorial003_an.py index 261cb4857d2f1..8fb40dd4aa8d0 100644 --- a/docs_src/security/tutorial003_an.py +++ b/docs_src/security/tutorial003_an.py @@ -68,7 +68,7 @@ async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): async def get_current_active_user( - current_user: Annotated[User, Depends(get_current_user)] + current_user: Annotated[User, Depends(get_current_user)], ): if current_user.disabled: raise HTTPException(status_code=400, detail="Inactive user") @@ -90,6 +90,6 @@ async def login(form_data: Annotated[OAuth2PasswordRequestForm, Depends()]): @app.get("/users/me") async def read_users_me( - current_user: Annotated[User, Depends(get_current_active_user)] + current_user: Annotated[User, Depends(get_current_active_user)], ): return current_user diff --git a/docs_src/security/tutorial003_an_py310.py b/docs_src/security/tutorial003_an_py310.py index a03f4f8bf5fb0..ced4a2fbc18b7 100644 --- a/docs_src/security/tutorial003_an_py310.py +++ b/docs_src/security/tutorial003_an_py310.py @@ -67,7 +67,7 @@ async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): async def get_current_active_user( - current_user: Annotated[User, Depends(get_current_user)] + current_user: Annotated[User, Depends(get_current_user)], ): if current_user.disabled: raise HTTPException(status_code=400, detail="Inactive user") @@ -89,6 +89,6 @@ async def login(form_data: Annotated[OAuth2PasswordRequestForm, Depends()]): @app.get("/users/me") async def read_users_me( - current_user: Annotated[User, Depends(get_current_active_user)] + current_user: Annotated[User, Depends(get_current_active_user)], ): return current_user diff --git a/docs_src/security/tutorial003_an_py39.py b/docs_src/security/tutorial003_an_py39.py index 308dbe798fa17..068a3933e1a05 100644 --- a/docs_src/security/tutorial003_an_py39.py +++ b/docs_src/security/tutorial003_an_py39.py @@ -67,7 +67,7 @@ async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): async def get_current_active_user( - current_user: Annotated[User, Depends(get_current_user)] + current_user: Annotated[User, Depends(get_current_user)], ): if current_user.disabled: raise HTTPException(status_code=400, detail="Inactive user") @@ -89,6 +89,6 @@ async def login(form_data: Annotated[OAuth2PasswordRequestForm, Depends()]): @app.get("/users/me") async def read_users_me( - current_user: Annotated[User, Depends(get_current_active_user)] + current_user: Annotated[User, Depends(get_current_active_user)], ): return current_user diff --git a/docs_src/security/tutorial004.py b/docs_src/security/tutorial004.py index 64099abe9cffe..d0fbaa5722081 100644 --- a/docs_src/security/tutorial004.py +++ b/docs_src/security/tutorial004.py @@ -1,4 +1,4 @@ -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone from typing import Union from fastapi import Depends, FastAPI, HTTPException, status @@ -78,9 +78,9 @@ def authenticate_user(fake_db, username: str, password: str): def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None): to_encode = data.copy() if expires_delta: - expire = datetime.utcnow() + expires_delta + expire = datetime.now(timezone.utc) + expires_delta else: - expire = datetime.utcnow() + timedelta(minutes=15) + expire = datetime.now(timezone.utc) + timedelta(minutes=15) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt @@ -112,8 +112,10 @@ async def get_current_active_user(current_user: User = Depends(get_current_user) return current_user -@app.post("/token", response_model=Token) -async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()): +@app.post("/token") +async def login_for_access_token( + form_data: OAuth2PasswordRequestForm = Depends(), +) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: raise HTTPException( @@ -125,7 +127,7 @@ async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends( access_token = create_access_token( data={"sub": user.username}, expires_delta=access_token_expires ) - return {"access_token": access_token, "token_type": "bearer"} + return Token(access_token=access_token, token_type="bearer") @app.get("/users/me/", response_model=User) diff --git a/docs_src/security/tutorial004_an.py b/docs_src/security/tutorial004_an.py index ca350343d2082..eebd36d64c254 100644 --- a/docs_src/security/tutorial004_an.py +++ b/docs_src/security/tutorial004_an.py @@ -1,4 +1,4 @@ -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone from typing import Union from fastapi import Depends, FastAPI, HTTPException, status @@ -79,9 +79,9 @@ def authenticate_user(fake_db, username: str, password: str): def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None): to_encode = data.copy() if expires_delta: - expire = datetime.utcnow() + expires_delta + expire = datetime.now(timezone.utc) + expires_delta else: - expire = datetime.utcnow() + timedelta(minutes=15) + expire = datetime.now(timezone.utc) + timedelta(minutes=15) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt @@ -108,17 +108,17 @@ async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): async def get_current_active_user( - current_user: Annotated[User, Depends(get_current_user)] + current_user: Annotated[User, Depends(get_current_user)], ): if current_user.disabled: raise HTTPException(status_code=400, detail="Inactive user") return current_user -@app.post("/token", response_model=Token) +@app.post("/token") async def login_for_access_token( - form_data: Annotated[OAuth2PasswordRequestForm, Depends()] -): + form_data: Annotated[OAuth2PasswordRequestForm, Depends()], +) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: raise HTTPException( @@ -130,18 +130,18 @@ async def login_for_access_token( access_token = create_access_token( data={"sub": user.username}, expires_delta=access_token_expires ) - return {"access_token": access_token, "token_type": "bearer"} + return Token(access_token=access_token, token_type="bearer") @app.get("/users/me/", response_model=User) async def read_users_me( - current_user: Annotated[User, Depends(get_current_active_user)] + current_user: Annotated[User, Depends(get_current_active_user)], ): return current_user @app.get("/users/me/items/") async def read_own_items( - current_user: Annotated[User, Depends(get_current_active_user)] + current_user: Annotated[User, Depends(get_current_active_user)], ): return [{"item_id": "Foo", "owner": current_user.username}] diff --git a/docs_src/security/tutorial004_an_py310.py b/docs_src/security/tutorial004_an_py310.py index 8bf5f3b7185cd..4e50ada7c3c98 100644 --- a/docs_src/security/tutorial004_an_py310.py +++ b/docs_src/security/tutorial004_an_py310.py @@ -1,4 +1,4 @@ -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone from typing import Annotated from fastapi import Depends, FastAPI, HTTPException, status @@ -78,9 +78,9 @@ def authenticate_user(fake_db, username: str, password: str): def create_access_token(data: dict, expires_delta: timedelta | None = None): to_encode = data.copy() if expires_delta: - expire = datetime.utcnow() + expires_delta + expire = datetime.now(timezone.utc) + expires_delta else: - expire = datetime.utcnow() + timedelta(minutes=15) + expire = datetime.now(timezone.utc) + timedelta(minutes=15) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt @@ -107,17 +107,17 @@ async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): async def get_current_active_user( - current_user: Annotated[User, Depends(get_current_user)] + current_user: Annotated[User, Depends(get_current_user)], ): if current_user.disabled: raise HTTPException(status_code=400, detail="Inactive user") return current_user -@app.post("/token", response_model=Token) +@app.post("/token") async def login_for_access_token( - form_data: Annotated[OAuth2PasswordRequestForm, Depends()] -): + form_data: Annotated[OAuth2PasswordRequestForm, Depends()], +) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: raise HTTPException( @@ -129,18 +129,18 @@ async def login_for_access_token( access_token = create_access_token( data={"sub": user.username}, expires_delta=access_token_expires ) - return {"access_token": access_token, "token_type": "bearer"} + return Token(access_token=access_token, token_type="bearer") @app.get("/users/me/", response_model=User) async def read_users_me( - current_user: Annotated[User, Depends(get_current_active_user)] + current_user: Annotated[User, Depends(get_current_active_user)], ): return current_user @app.get("/users/me/items/") async def read_own_items( - current_user: Annotated[User, Depends(get_current_active_user)] + current_user: Annotated[User, Depends(get_current_active_user)], ): return [{"item_id": "Foo", "owner": current_user.username}] diff --git a/docs_src/security/tutorial004_an_py39.py b/docs_src/security/tutorial004_an_py39.py index a634e23de9843..eb49aaa67cdfa 100644 --- a/docs_src/security/tutorial004_an_py39.py +++ b/docs_src/security/tutorial004_an_py39.py @@ -1,4 +1,4 @@ -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone from typing import Annotated, Union from fastapi import Depends, FastAPI, HTTPException, status @@ -78,9 +78,9 @@ def authenticate_user(fake_db, username: str, password: str): def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None): to_encode = data.copy() if expires_delta: - expire = datetime.utcnow() + expires_delta + expire = datetime.now(timezone.utc) + expires_delta else: - expire = datetime.utcnow() + timedelta(minutes=15) + expire = datetime.now(timezone.utc) + timedelta(minutes=15) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt @@ -107,17 +107,17 @@ async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): async def get_current_active_user( - current_user: Annotated[User, Depends(get_current_user)] + current_user: Annotated[User, Depends(get_current_user)], ): if current_user.disabled: raise HTTPException(status_code=400, detail="Inactive user") return current_user -@app.post("/token", response_model=Token) +@app.post("/token") async def login_for_access_token( - form_data: Annotated[OAuth2PasswordRequestForm, Depends()] -): + form_data: Annotated[OAuth2PasswordRequestForm, Depends()], +) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: raise HTTPException( @@ -129,18 +129,18 @@ async def login_for_access_token( access_token = create_access_token( data={"sub": user.username}, expires_delta=access_token_expires ) - return {"access_token": access_token, "token_type": "bearer"} + return Token(access_token=access_token, token_type="bearer") @app.get("/users/me/", response_model=User) async def read_users_me( - current_user: Annotated[User, Depends(get_current_active_user)] + current_user: Annotated[User, Depends(get_current_active_user)], ): return current_user @app.get("/users/me/items/") async def read_own_items( - current_user: Annotated[User, Depends(get_current_active_user)] + current_user: Annotated[User, Depends(get_current_active_user)], ): return [{"item_id": "Foo", "owner": current_user.username}] diff --git a/docs_src/security/tutorial004_py310.py b/docs_src/security/tutorial004_py310.py index 797d56d0431ab..5a905783d6137 100644 --- a/docs_src/security/tutorial004_py310.py +++ b/docs_src/security/tutorial004_py310.py @@ -1,4 +1,4 @@ -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone from fastapi import Depends, FastAPI, HTTPException, status from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm @@ -77,9 +77,9 @@ def authenticate_user(fake_db, username: str, password: str): def create_access_token(data: dict, expires_delta: timedelta | None = None): to_encode = data.copy() if expires_delta: - expire = datetime.utcnow() + expires_delta + expire = datetime.now(timezone.utc) + expires_delta else: - expire = datetime.utcnow() + timedelta(minutes=15) + expire = datetime.now(timezone.utc) + timedelta(minutes=15) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt @@ -111,8 +111,10 @@ async def get_current_active_user(current_user: User = Depends(get_current_user) return current_user -@app.post("/token", response_model=Token) -async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()): +@app.post("/token") +async def login_for_access_token( + form_data: OAuth2PasswordRequestForm = Depends(), +) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: raise HTTPException( @@ -124,7 +126,7 @@ async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends( access_token = create_access_token( data={"sub": user.username}, expires_delta=access_token_expires ) - return {"access_token": access_token, "token_type": "bearer"} + return Token(access_token=access_token, token_type="bearer") @app.get("/users/me/", response_model=User) diff --git a/docs_src/security/tutorial005.py b/docs_src/security/tutorial005.py index bd0a33581c21c..d4a6975da6d36 100644 --- a/docs_src/security/tutorial005.py +++ b/docs_src/security/tutorial005.py @@ -1,4 +1,4 @@ -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone from typing import List, Union from fastapi import Depends, FastAPI, HTTPException, Security, status @@ -93,9 +93,9 @@ def authenticate_user(fake_db, username: str, password: str): def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None): to_encode = data.copy() if expires_delta: - expire = datetime.utcnow() + expires_delta + expire = datetime.now(timezone.utc) + expires_delta else: - expire = datetime.utcnow() + timedelta(minutes=15) + expire = datetime.now(timezone.utc) + timedelta(minutes=15) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt @@ -136,15 +136,17 @@ async def get_current_user( async def get_current_active_user( - current_user: User = Security(get_current_user, scopes=["me"]) + current_user: User = Security(get_current_user, scopes=["me"]), ): if current_user.disabled: raise HTTPException(status_code=400, detail="Inactive user") return current_user -@app.post("/token", response_model=Token) -async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()): +@app.post("/token") +async def login_for_access_token( + form_data: OAuth2PasswordRequestForm = Depends(), +) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: raise HTTPException(status_code=400, detail="Incorrect username or password") @@ -153,7 +155,7 @@ async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends( data={"sub": user.username, "scopes": form_data.scopes}, expires_delta=access_token_expires, ) - return {"access_token": access_token, "token_type": "bearer"} + return Token(access_token=access_token, token_type="bearer") @app.get("/users/me/", response_model=User) @@ -163,7 +165,7 @@ async def read_users_me(current_user: User = Depends(get_current_active_user)): @app.get("/users/me/items/") async def read_own_items( - current_user: User = Security(get_current_active_user, scopes=["items"]) + current_user: User = Security(get_current_active_user, scopes=["items"]), ): return [{"item_id": "Foo", "owner": current_user.username}] diff --git a/docs_src/security/tutorial005_an.py b/docs_src/security/tutorial005_an.py index ec4fa1a07e2cd..982daed2f5462 100644 --- a/docs_src/security/tutorial005_an.py +++ b/docs_src/security/tutorial005_an.py @@ -1,4 +1,4 @@ -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone from typing import List, Union from fastapi import Depends, FastAPI, HTTPException, Security, status @@ -94,9 +94,9 @@ def authenticate_user(fake_db, username: str, password: str): def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None): to_encode = data.copy() if expires_delta: - expire = datetime.utcnow() + expires_delta + expire = datetime.now(timezone.utc) + expires_delta else: - expire = datetime.utcnow() + timedelta(minutes=15) + expire = datetime.now(timezone.utc) + timedelta(minutes=15) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt @@ -137,17 +137,17 @@ async def get_current_user( async def get_current_active_user( - current_user: Annotated[User, Security(get_current_user, scopes=["me"])] + current_user: Annotated[User, Security(get_current_user, scopes=["me"])], ): if current_user.disabled: raise HTTPException(status_code=400, detail="Inactive user") return current_user -@app.post("/token", response_model=Token) +@app.post("/token") async def login_for_access_token( - form_data: Annotated[OAuth2PasswordRequestForm, Depends()] -): + form_data: Annotated[OAuth2PasswordRequestForm, Depends()], +) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: raise HTTPException(status_code=400, detail="Incorrect username or password") @@ -156,19 +156,19 @@ async def login_for_access_token( data={"sub": user.username, "scopes": form_data.scopes}, expires_delta=access_token_expires, ) - return {"access_token": access_token, "token_type": "bearer"} + return Token(access_token=access_token, token_type="bearer") @app.get("/users/me/", response_model=User) async def read_users_me( - current_user: Annotated[User, Depends(get_current_active_user)] + current_user: Annotated[User, Depends(get_current_active_user)], ): return current_user @app.get("/users/me/items/") async def read_own_items( - current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])] + current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])], ): return [{"item_id": "Foo", "owner": current_user.username}] diff --git a/docs_src/security/tutorial005_an_py310.py b/docs_src/security/tutorial005_an_py310.py index 45f3fc0bd6de1..79aafbff1b100 100644 --- a/docs_src/security/tutorial005_an_py310.py +++ b/docs_src/security/tutorial005_an_py310.py @@ -1,4 +1,4 @@ -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone from typing import Annotated from fastapi import Depends, FastAPI, HTTPException, Security, status @@ -93,9 +93,9 @@ def authenticate_user(fake_db, username: str, password: str): def create_access_token(data: dict, expires_delta: timedelta | None = None): to_encode = data.copy() if expires_delta: - expire = datetime.utcnow() + expires_delta + expire = datetime.now(timezone.utc) + expires_delta else: - expire = datetime.utcnow() + timedelta(minutes=15) + expire = datetime.now(timezone.utc) + timedelta(minutes=15) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt @@ -136,17 +136,17 @@ async def get_current_user( async def get_current_active_user( - current_user: Annotated[User, Security(get_current_user, scopes=["me"])] + current_user: Annotated[User, Security(get_current_user, scopes=["me"])], ): if current_user.disabled: raise HTTPException(status_code=400, detail="Inactive user") return current_user -@app.post("/token", response_model=Token) +@app.post("/token") async def login_for_access_token( - form_data: Annotated[OAuth2PasswordRequestForm, Depends()] -): + form_data: Annotated[OAuth2PasswordRequestForm, Depends()], +) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: raise HTTPException(status_code=400, detail="Incorrect username or password") @@ -155,19 +155,19 @@ async def login_for_access_token( data={"sub": user.username, "scopes": form_data.scopes}, expires_delta=access_token_expires, ) - return {"access_token": access_token, "token_type": "bearer"} + return Token(access_token=access_token, token_type="bearer") @app.get("/users/me/", response_model=User) async def read_users_me( - current_user: Annotated[User, Depends(get_current_active_user)] + current_user: Annotated[User, Depends(get_current_active_user)], ): return current_user @app.get("/users/me/items/") async def read_own_items( - current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])] + current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])], ): return [{"item_id": "Foo", "owner": current_user.username}] diff --git a/docs_src/security/tutorial005_an_py39.py b/docs_src/security/tutorial005_an_py39.py index ecb5ed5160d86..3bdab5507fcda 100644 --- a/docs_src/security/tutorial005_an_py39.py +++ b/docs_src/security/tutorial005_an_py39.py @@ -1,4 +1,4 @@ -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone from typing import Annotated, List, Union from fastapi import Depends, FastAPI, HTTPException, Security, status @@ -93,9 +93,9 @@ def authenticate_user(fake_db, username: str, password: str): def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None): to_encode = data.copy() if expires_delta: - expire = datetime.utcnow() + expires_delta + expire = datetime.now(timezone.utc) + expires_delta else: - expire = datetime.utcnow() + timedelta(minutes=15) + expire = datetime.now(timezone.utc) + timedelta(minutes=15) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt @@ -136,17 +136,17 @@ async def get_current_user( async def get_current_active_user( - current_user: Annotated[User, Security(get_current_user, scopes=["me"])] + current_user: Annotated[User, Security(get_current_user, scopes=["me"])], ): if current_user.disabled: raise HTTPException(status_code=400, detail="Inactive user") return current_user -@app.post("/token", response_model=Token) +@app.post("/token") async def login_for_access_token( - form_data: Annotated[OAuth2PasswordRequestForm, Depends()] -): + form_data: Annotated[OAuth2PasswordRequestForm, Depends()], +) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: raise HTTPException(status_code=400, detail="Incorrect username or password") @@ -155,19 +155,19 @@ async def login_for_access_token( data={"sub": user.username, "scopes": form_data.scopes}, expires_delta=access_token_expires, ) - return {"access_token": access_token, "token_type": "bearer"} + return Token(access_token=access_token, token_type="bearer") @app.get("/users/me/", response_model=User) async def read_users_me( - current_user: Annotated[User, Depends(get_current_active_user)] + current_user: Annotated[User, Depends(get_current_active_user)], ): return current_user @app.get("/users/me/items/") async def read_own_items( - current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])] + current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])], ): return [{"item_id": "Foo", "owner": current_user.username}] diff --git a/docs_src/security/tutorial005_py310.py b/docs_src/security/tutorial005_py310.py index ba756ef4f4d67..9f75aa0beb4b9 100644 --- a/docs_src/security/tutorial005_py310.py +++ b/docs_src/security/tutorial005_py310.py @@ -1,4 +1,4 @@ -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone from fastapi import Depends, FastAPI, HTTPException, Security, status from fastapi.security import ( @@ -92,9 +92,9 @@ def authenticate_user(fake_db, username: str, password: str): def create_access_token(data: dict, expires_delta: timedelta | None = None): to_encode = data.copy() if expires_delta: - expire = datetime.utcnow() + expires_delta + expire = datetime.now(timezone.utc) + expires_delta else: - expire = datetime.utcnow() + timedelta(minutes=15) + expire = datetime.now(timezone.utc) + timedelta(minutes=15) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt @@ -135,15 +135,17 @@ async def get_current_user( async def get_current_active_user( - current_user: User = Security(get_current_user, scopes=["me"]) + current_user: User = Security(get_current_user, scopes=["me"]), ): if current_user.disabled: raise HTTPException(status_code=400, detail="Inactive user") return current_user -@app.post("/token", response_model=Token) -async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()): +@app.post("/token") +async def login_for_access_token( + form_data: OAuth2PasswordRequestForm = Depends(), +) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: raise HTTPException(status_code=400, detail="Incorrect username or password") @@ -152,7 +154,7 @@ async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends( data={"sub": user.username, "scopes": form_data.scopes}, expires_delta=access_token_expires, ) - return {"access_token": access_token, "token_type": "bearer"} + return Token(access_token=access_token, token_type="bearer") @app.get("/users/me/", response_model=User) @@ -162,7 +164,7 @@ async def read_users_me(current_user: User = Depends(get_current_active_user)): @app.get("/users/me/items/") async def read_own_items( - current_user: User = Security(get_current_active_user, scopes=["items"]) + current_user: User = Security(get_current_active_user, scopes=["items"]), ): return [{"item_id": "Foo", "owner": current_user.username}] diff --git a/docs_src/security/tutorial005_py39.py b/docs_src/security/tutorial005_py39.py index 9e4dbcffba38d..bac2489320e1f 100644 --- a/docs_src/security/tutorial005_py39.py +++ b/docs_src/security/tutorial005_py39.py @@ -1,4 +1,4 @@ -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone from typing import Union from fastapi import Depends, FastAPI, HTTPException, Security, status @@ -93,9 +93,9 @@ def authenticate_user(fake_db, username: str, password: str): def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None): to_encode = data.copy() if expires_delta: - expire = datetime.utcnow() + expires_delta + expire = datetime.now(timezone.utc) + expires_delta else: - expire = datetime.utcnow() + timedelta(minutes=15) + expire = datetime.now(timezone.utc) + timedelta(minutes=15) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt @@ -136,15 +136,17 @@ async def get_current_user( async def get_current_active_user( - current_user: User = Security(get_current_user, scopes=["me"]) + current_user: User = Security(get_current_user, scopes=["me"]), ): if current_user.disabled: raise HTTPException(status_code=400, detail="Inactive user") return current_user -@app.post("/token", response_model=Token) -async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()): +@app.post("/token") +async def login_for_access_token( + form_data: OAuth2PasswordRequestForm = Depends(), +) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: raise HTTPException(status_code=400, detail="Incorrect username or password") @@ -153,7 +155,7 @@ async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends( data={"sub": user.username, "scopes": form_data.scopes}, expires_delta=access_token_expires, ) - return {"access_token": access_token, "token_type": "bearer"} + return Token(access_token=access_token, token_type="bearer") @app.get("/users/me/", response_model=User) @@ -163,7 +165,7 @@ async def read_users_me(current_user: User = Depends(get_current_active_user)): @app.get("/users/me/items/") async def read_own_items( - current_user: User = Security(get_current_active_user, scopes=["items"]) + current_user: User = Security(get_current_active_user, scopes=["items"]), ): return [{"item_id": "Foo", "owner": current_user.username}] diff --git a/docs_src/security/tutorial007.py b/docs_src/security/tutorial007.py index 790ee10bc6b1d..ac816eb0c19d2 100644 --- a/docs_src/security/tutorial007.py +++ b/docs_src/security/tutorial007.py @@ -22,7 +22,7 @@ def get_current_username(credentials: HTTPBasicCredentials = Depends(security)): if not (is_correct_username and is_correct_password): raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, - detail="Incorrect email or password", + detail="Incorrect username or password", headers={"WWW-Authenticate": "Basic"}, ) return credentials.username diff --git a/docs_src/security/tutorial007_an.py b/docs_src/security/tutorial007_an.py index 5fb7c8e57560c..0d211dfde5586 100644 --- a/docs_src/security/tutorial007_an.py +++ b/docs_src/security/tutorial007_an.py @@ -10,7 +10,7 @@ def get_current_username( - credentials: Annotated[HTTPBasicCredentials, Depends(security)] + credentials: Annotated[HTTPBasicCredentials, Depends(security)], ): current_username_bytes = credentials.username.encode("utf8") correct_username_bytes = b"stanleyjobson" @@ -25,7 +25,7 @@ def get_current_username( if not (is_correct_username and is_correct_password): raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, - detail="Incorrect email or password", + detail="Incorrect username or password", headers={"WWW-Authenticate": "Basic"}, ) return credentials.username diff --git a/docs_src/security/tutorial007_an_py39.py b/docs_src/security/tutorial007_an_py39.py index 17177dabf9e47..87ef986574354 100644 --- a/docs_src/security/tutorial007_an_py39.py +++ b/docs_src/security/tutorial007_an_py39.py @@ -10,7 +10,7 @@ def get_current_username( - credentials: Annotated[HTTPBasicCredentials, Depends(security)] + credentials: Annotated[HTTPBasicCredentials, Depends(security)], ): current_username_bytes = credentials.username.encode("utf8") correct_username_bytes = b"stanleyjobson" @@ -25,7 +25,7 @@ def get_current_username( if not (is_correct_username and is_correct_password): raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, - detail="Incorrect email or password", + detail="Incorrect username or password", headers={"WWW-Authenticate": "Basic"}, ) return credentials.username diff --git a/docs_src/separate_openapi_schemas/tutorial001.py b/docs_src/separate_openapi_schemas/tutorial001.py new file mode 100644 index 0000000000000..415eef8e2824f --- /dev/null +++ b/docs_src/separate_openapi_schemas/tutorial001.py @@ -0,0 +1,28 @@ +from typing import List, Union + +from fastapi import FastAPI +from pydantic import BaseModel + + +class Item(BaseModel): + name: str + description: Union[str, None] = None + + +app = FastAPI() + + +@app.post("/items/") +def create_item(item: Item): + return item + + +@app.get("/items/") +def read_items() -> List[Item]: + return [ + Item( + name="Portal Gun", + description="Device to travel through the multi-rick-verse", + ), + Item(name="Plumbus"), + ] diff --git a/docs_src/separate_openapi_schemas/tutorial001_py310.py b/docs_src/separate_openapi_schemas/tutorial001_py310.py new file mode 100644 index 0000000000000..289cb54eda2a2 --- /dev/null +++ b/docs_src/separate_openapi_schemas/tutorial001_py310.py @@ -0,0 +1,26 @@ +from fastapi import FastAPI +from pydantic import BaseModel + + +class Item(BaseModel): + name: str + description: str | None = None + + +app = FastAPI() + + +@app.post("/items/") +def create_item(item: Item): + return item + + +@app.get("/items/") +def read_items() -> list[Item]: + return [ + Item( + name="Portal Gun", + description="Device to travel through the multi-rick-verse", + ), + Item(name="Plumbus"), + ] diff --git a/docs_src/separate_openapi_schemas/tutorial001_py39.py b/docs_src/separate_openapi_schemas/tutorial001_py39.py new file mode 100644 index 0000000000000..63cffd1e307fb --- /dev/null +++ b/docs_src/separate_openapi_schemas/tutorial001_py39.py @@ -0,0 +1,28 @@ +from typing import Optional + +from fastapi import FastAPI +from pydantic import BaseModel + + +class Item(BaseModel): + name: str + description: Optional[str] = None + + +app = FastAPI() + + +@app.post("/items/") +def create_item(item: Item): + return item + + +@app.get("/items/") +def read_items() -> list[Item]: + return [ + Item( + name="Portal Gun", + description="Device to travel through the multi-rick-verse", + ), + Item(name="Plumbus"), + ] diff --git a/docs_src/separate_openapi_schemas/tutorial002.py b/docs_src/separate_openapi_schemas/tutorial002.py new file mode 100644 index 0000000000000..7df93783b9585 --- /dev/null +++ b/docs_src/separate_openapi_schemas/tutorial002.py @@ -0,0 +1,28 @@ +from typing import List, Union + +from fastapi import FastAPI +from pydantic import BaseModel + + +class Item(BaseModel): + name: str + description: Union[str, None] = None + + +app = FastAPI(separate_input_output_schemas=False) + + +@app.post("/items/") +def create_item(item: Item): + return item + + +@app.get("/items/") +def read_items() -> List[Item]: + return [ + Item( + name="Portal Gun", + description="Device to travel through the multi-rick-verse", + ), + Item(name="Plumbus"), + ] diff --git a/docs_src/separate_openapi_schemas/tutorial002_py310.py b/docs_src/separate_openapi_schemas/tutorial002_py310.py new file mode 100644 index 0000000000000..5db21087293f1 --- /dev/null +++ b/docs_src/separate_openapi_schemas/tutorial002_py310.py @@ -0,0 +1,26 @@ +from fastapi import FastAPI +from pydantic import BaseModel + + +class Item(BaseModel): + name: str + description: str | None = None + + +app = FastAPI(separate_input_output_schemas=False) + + +@app.post("/items/") +def create_item(item: Item): + return item + + +@app.get("/items/") +def read_items() -> list[Item]: + return [ + Item( + name="Portal Gun", + description="Device to travel through the multi-rick-verse", + ), + Item(name="Plumbus"), + ] diff --git a/docs_src/separate_openapi_schemas/tutorial002_py39.py b/docs_src/separate_openapi_schemas/tutorial002_py39.py new file mode 100644 index 0000000000000..50d997d92aa43 --- /dev/null +++ b/docs_src/separate_openapi_schemas/tutorial002_py39.py @@ -0,0 +1,28 @@ +from typing import Optional + +from fastapi import FastAPI +from pydantic import BaseModel + + +class Item(BaseModel): + name: str + description: Optional[str] = None + + +app = FastAPI(separate_input_output_schemas=False) + + +@app.post("/items/") +def create_item(item: Item): + return item + + +@app.get("/items/") +def read_items() -> list[Item]: + return [ + Item( + name="Portal Gun", + description="Device to travel through the multi-rick-verse", + ), + Item(name="Plumbus"), + ] diff --git a/docs_src/settings/app01/config.py b/docs_src/settings/app01/config.py index defede9db401e..b31b8811d6539 100644 --- a/docs_src/settings/app01/config.py +++ b/docs_src/settings/app01/config.py @@ -1,4 +1,4 @@ -from pydantic import BaseSettings +from pydantic_settings import BaseSettings class Settings(BaseSettings): diff --git a/docs_src/settings/app02/config.py b/docs_src/settings/app02/config.py index 9a7829135690d..e17b5035dcc77 100644 --- a/docs_src/settings/app02/config.py +++ b/docs_src/settings/app02/config.py @@ -1,4 +1,4 @@ -from pydantic import BaseSettings +from pydantic_settings import BaseSettings class Settings(BaseSettings): diff --git a/docs_src/settings/app02/main.py b/docs_src/settings/app02/main.py index 163aa26142464..941f82e6b39b6 100644 --- a/docs_src/settings/app02/main.py +++ b/docs_src/settings/app02/main.py @@ -7,7 +7,7 @@ app = FastAPI() -@lru_cache() +@lru_cache def get_settings(): return Settings() diff --git a/docs_src/settings/app02_an/config.py b/docs_src/settings/app02_an/config.py index 9a7829135690d..e17b5035dcc77 100644 --- a/docs_src/settings/app02_an/config.py +++ b/docs_src/settings/app02_an/config.py @@ -1,4 +1,4 @@ -from pydantic import BaseSettings +from pydantic_settings import BaseSettings class Settings(BaseSettings): diff --git a/docs_src/settings/app02_an/main.py b/docs_src/settings/app02_an/main.py index cb679202d6ed5..3a578cc338898 100644 --- a/docs_src/settings/app02_an/main.py +++ b/docs_src/settings/app02_an/main.py @@ -8,7 +8,7 @@ app = FastAPI() -@lru_cache() +@lru_cache def get_settings(): return Settings() diff --git a/docs_src/settings/app02_an_py39/config.py b/docs_src/settings/app02_an_py39/config.py index 9a7829135690d..e17b5035dcc77 100644 --- a/docs_src/settings/app02_an_py39/config.py +++ b/docs_src/settings/app02_an_py39/config.py @@ -1,4 +1,4 @@ -from pydantic import BaseSettings +from pydantic_settings import BaseSettings class Settings(BaseSettings): diff --git a/docs_src/settings/app02_an_py39/main.py b/docs_src/settings/app02_an_py39/main.py index 61be74fcb9a17..6d5db12a87941 100644 --- a/docs_src/settings/app02_an_py39/main.py +++ b/docs_src/settings/app02_an_py39/main.py @@ -8,7 +8,7 @@ app = FastAPI() -@lru_cache() +@lru_cache def get_settings(): return Settings() diff --git a/docs_src/settings/app03/config.py b/docs_src/settings/app03/config.py index e1c3ee30063b7..942aea3e58b70 100644 --- a/docs_src/settings/app03/config.py +++ b/docs_src/settings/app03/config.py @@ -1,4 +1,4 @@ -from pydantic import BaseSettings +from pydantic_settings import BaseSettings class Settings(BaseSettings): diff --git a/docs_src/settings/app03/main.py b/docs_src/settings/app03/main.py index 69bc8c6e0eb6b..ea64a5709cb49 100644 --- a/docs_src/settings/app03/main.py +++ b/docs_src/settings/app03/main.py @@ -7,7 +7,7 @@ app = FastAPI() -@lru_cache() +@lru_cache def get_settings(): return config.Settings() diff --git a/docs_src/settings/app03_an/config.py b/docs_src/settings/app03_an/config.py index e1c3ee30063b7..08f8f88c280ac 100644 --- a/docs_src/settings/app03_an/config.py +++ b/docs_src/settings/app03_an/config.py @@ -1,4 +1,4 @@ -from pydantic import BaseSettings +from pydantic_settings import BaseSettings, SettingsConfigDict class Settings(BaseSettings): @@ -6,5 +6,4 @@ class Settings(BaseSettings): admin_email: str items_per_user: int = 50 - class Config: - env_file = ".env" + model_config = SettingsConfigDict(env_file=".env") diff --git a/docs_src/settings/app03_an/config_pv1.py b/docs_src/settings/app03_an/config_pv1.py new file mode 100644 index 0000000000000..e1c3ee30063b7 --- /dev/null +++ b/docs_src/settings/app03_an/config_pv1.py @@ -0,0 +1,10 @@ +from pydantic import BaseSettings + + +class Settings(BaseSettings): + app_name: str = "Awesome API" + admin_email: str + items_per_user: int = 50 + + class Config: + env_file = ".env" diff --git a/docs_src/settings/app03_an/main.py b/docs_src/settings/app03_an/main.py index c33b98f474880..2f64b9cd175d8 100644 --- a/docs_src/settings/app03_an/main.py +++ b/docs_src/settings/app03_an/main.py @@ -8,7 +8,7 @@ app = FastAPI() -@lru_cache() +@lru_cache def get_settings(): return config.Settings() diff --git a/docs_src/settings/app03_an_py39/config.py b/docs_src/settings/app03_an_py39/config.py index e1c3ee30063b7..942aea3e58b70 100644 --- a/docs_src/settings/app03_an_py39/config.py +++ b/docs_src/settings/app03_an_py39/config.py @@ -1,4 +1,4 @@ -from pydantic import BaseSettings +from pydantic_settings import BaseSettings class Settings(BaseSettings): diff --git a/docs_src/settings/app03_an_py39/main.py b/docs_src/settings/app03_an_py39/main.py index b89c6b6cf44fb..62f3476396ff0 100644 --- a/docs_src/settings/app03_an_py39/main.py +++ b/docs_src/settings/app03_an_py39/main.py @@ -8,7 +8,7 @@ app = FastAPI() -@lru_cache() +@lru_cache def get_settings(): return config.Settings() diff --git a/docs_src/settings/tutorial001.py b/docs_src/settings/tutorial001.py index 0cfd1b6632f0b..d48c4c060cfd1 100644 --- a/docs_src/settings/tutorial001.py +++ b/docs_src/settings/tutorial001.py @@ -1,5 +1,5 @@ from fastapi import FastAPI -from pydantic import BaseSettings +from pydantic_settings import BaseSettings class Settings(BaseSettings): diff --git a/docs_src/settings/tutorial001_pv1.py b/docs_src/settings/tutorial001_pv1.py new file mode 100644 index 0000000000000..0cfd1b6632f0b --- /dev/null +++ b/docs_src/settings/tutorial001_pv1.py @@ -0,0 +1,21 @@ +from fastapi import FastAPI +from pydantic import BaseSettings + + +class Settings(BaseSettings): + app_name: str = "Awesome API" + admin_email: str + items_per_user: int = 50 + + +settings = Settings() +app = FastAPI() + + +@app.get("/info") +async def info(): + return { + "app_name": settings.app_name, + "admin_email": settings.admin_email, + "items_per_user": settings.items_per_user, + } diff --git a/docs_src/sql_databases/sql_app/models.py b/docs_src/sql_databases/sql_app/models.py index 62d8ab4aaac16..09ae2a8077f68 100644 --- a/docs_src/sql_databases/sql_app/models.py +++ b/docs_src/sql_databases/sql_app/models.py @@ -7,7 +7,7 @@ class User(Base): __tablename__ = "users" - id = Column(Integer, primary_key=True, index=True) + id = Column(Integer, primary_key=True) email = Column(String, unique=True, index=True) hashed_password = Column(String) is_active = Column(Boolean, default=True) @@ -18,7 +18,7 @@ class User(Base): class Item(Base): __tablename__ = "items" - id = Column(Integer, primary_key=True, index=True) + id = Column(Integer, primary_key=True) title = Column(String, index=True) description = Column(String, index=True) owner_id = Column(Integer, ForeignKey("users.id")) diff --git a/docs_src/sql_databases/sql_app_py310/models.py b/docs_src/sql_databases/sql_app_py310/models.py index 62d8ab4aaac16..09ae2a8077f68 100644 --- a/docs_src/sql_databases/sql_app_py310/models.py +++ b/docs_src/sql_databases/sql_app_py310/models.py @@ -7,7 +7,7 @@ class User(Base): __tablename__ = "users" - id = Column(Integer, primary_key=True, index=True) + id = Column(Integer, primary_key=True) email = Column(String, unique=True, index=True) hashed_password = Column(String) is_active = Column(Boolean, default=True) @@ -18,7 +18,7 @@ class User(Base): class Item(Base): __tablename__ = "items" - id = Column(Integer, primary_key=True, index=True) + id = Column(Integer, primary_key=True) title = Column(String, index=True) description = Column(String, index=True) owner_id = Column(Integer, ForeignKey("users.id")) diff --git a/docs_src/sql_databases/sql_app_py39/models.py b/docs_src/sql_databases/sql_app_py39/models.py index 62d8ab4aaac16..09ae2a8077f68 100644 --- a/docs_src/sql_databases/sql_app_py39/models.py +++ b/docs_src/sql_databases/sql_app_py39/models.py @@ -7,7 +7,7 @@ class User(Base): __tablename__ = "users" - id = Column(Integer, primary_key=True, index=True) + id = Column(Integer, primary_key=True) email = Column(String, unique=True, index=True) hashed_password = Column(String) is_active = Column(Boolean, default=True) @@ -18,7 +18,7 @@ class User(Base): class Item(Base): __tablename__ = "items" - id = Column(Integer, primary_key=True, index=True) + id = Column(Integer, primary_key=True) title = Column(String, index=True) description = Column(String, index=True) owner_id = Column(Integer, ForeignKey("users.id")) diff --git a/docs_src/templates/templates/item.html b/docs_src/templates/templates/item.html index a70287e77d345..27994ca994b00 100644 --- a/docs_src/templates/templates/item.html +++ b/docs_src/templates/templates/item.html @@ -4,6 +4,6 @@ -

Item ID: {{ id }}

+

Item ID: {{ id }}

diff --git a/docs_src/templates/tutorial001.py b/docs_src/templates/tutorial001.py index 245e7110b195d..81ccc8d4d0b3f 100644 --- a/docs_src/templates/tutorial001.py +++ b/docs_src/templates/tutorial001.py @@ -13,4 +13,6 @@ @app.get("/items/{id}", response_class=HTMLResponse) async def read_item(request: Request, id: str): - return templates.TemplateResponse("item.html", {"request": request, "id": id}) + return templates.TemplateResponse( + request=request, name="item.html", context={"id": id} + ) diff --git a/fastapi/__init__.py b/fastapi/__init__.py index 038e1ba86451b..234969256620d 100644 --- a/fastapi/__init__.py +++ b/fastapi/__init__.py @@ -1,6 +1,6 @@ """FastAPI framework, high performance, easy to learn, fast to code, ready for production""" -__version__ = "0.98.0" +__version__ = "0.110.0" from starlette import status as status diff --git a/fastapi/_compat.py b/fastapi/_compat.py new file mode 100644 index 0000000000000..35d4a87231139 --- /dev/null +++ b/fastapi/_compat.py @@ -0,0 +1,634 @@ +from collections import deque +from copy import copy +from dataclasses import dataclass, is_dataclass +from enum import Enum +from typing import ( + Any, + Callable, + Deque, + Dict, + FrozenSet, + List, + Mapping, + Sequence, + Set, + Tuple, + Type, + Union, +) + +from fastapi.exceptions import RequestErrorModel +from fastapi.types import IncEx, ModelNameMap, UnionType +from pydantic import BaseModel, create_model +from pydantic.version import VERSION as PYDANTIC_VERSION +from starlette.datastructures import UploadFile +from typing_extensions import Annotated, Literal, get_args, get_origin + +PYDANTIC_V2 = PYDANTIC_VERSION.startswith("2.") + + +sequence_annotation_to_type = { + Sequence: list, + List: list, + list: list, + Tuple: tuple, + tuple: tuple, + Set: set, + set: set, + FrozenSet: frozenset, + frozenset: frozenset, + Deque: deque, + deque: deque, +} + +sequence_types = tuple(sequence_annotation_to_type.keys()) + +if PYDANTIC_V2: + from pydantic import PydanticSchemaGenerationError as PydanticSchemaGenerationError + from pydantic import TypeAdapter + from pydantic import ValidationError as ValidationError + from pydantic._internal._schema_generation_shared import ( # type: ignore[attr-defined] + GetJsonSchemaHandler as GetJsonSchemaHandler, + ) + from pydantic._internal._typing_extra import eval_type_lenient + from pydantic._internal._utils import lenient_issubclass as lenient_issubclass + from pydantic.fields import FieldInfo + from pydantic.json_schema import GenerateJsonSchema as GenerateJsonSchema + from pydantic.json_schema import JsonSchemaValue as JsonSchemaValue + from pydantic_core import CoreSchema as CoreSchema + from pydantic_core import PydanticUndefined, PydanticUndefinedType + from pydantic_core import Url as Url + + try: + from pydantic_core.core_schema import ( + with_info_plain_validator_function as with_info_plain_validator_function, + ) + except ImportError: # pragma: no cover + from pydantic_core.core_schema import ( + general_plain_validator_function as with_info_plain_validator_function, # noqa: F401 + ) + + Required = PydanticUndefined + Undefined = PydanticUndefined + UndefinedType = PydanticUndefinedType + evaluate_forwardref = eval_type_lenient + Validator = Any + + class BaseConfig: + pass + + class ErrorWrapper(Exception): + pass + + @dataclass + class ModelField: + field_info: FieldInfo + name: str + mode: Literal["validation", "serialization"] = "validation" + + @property + def alias(self) -> str: + a = self.field_info.alias + return a if a is not None else self.name + + @property + def required(self) -> bool: + return self.field_info.is_required() + + @property + def default(self) -> Any: + return self.get_default() + + @property + def type_(self) -> Any: + return self.field_info.annotation + + def __post_init__(self) -> None: + self._type_adapter: TypeAdapter[Any] = TypeAdapter( + Annotated[self.field_info.annotation, self.field_info] + ) + + def get_default(self) -> Any: + if self.field_info.is_required(): + return Undefined + return self.field_info.get_default(call_default_factory=True) + + def validate( + self, + value: Any, + values: Dict[str, Any] = {}, # noqa: B006 + *, + loc: Tuple[Union[int, str], ...] = (), + ) -> Tuple[Any, Union[List[Dict[str, Any]], None]]: + try: + return ( + self._type_adapter.validate_python(value, from_attributes=True), + None, + ) + except ValidationError as exc: + return None, _regenerate_error_with_loc( + errors=exc.errors(), loc_prefix=loc + ) + + def serialize( + self, + value: Any, + *, + mode: Literal["json", "python"] = "json", + include: Union[IncEx, None] = None, + exclude: Union[IncEx, None] = None, + by_alias: bool = True, + exclude_unset: bool = False, + exclude_defaults: bool = False, + exclude_none: bool = False, + ) -> Any: + # What calls this code passes a value that already called + # self._type_adapter.validate_python(value) + return self._type_adapter.dump_python( + value, + mode=mode, + include=include, + exclude=exclude, + by_alias=by_alias, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + ) + + def __hash__(self) -> int: + # Each ModelField is unique for our purposes, to allow making a dict from + # ModelField to its JSON Schema. + return id(self) + + def get_annotation_from_field_info( + annotation: Any, field_info: FieldInfo, field_name: str + ) -> Any: + return annotation + + def _normalize_errors(errors: Sequence[Any]) -> List[Dict[str, Any]]: + return errors # type: ignore[return-value] + + def _model_rebuild(model: Type[BaseModel]) -> None: + model.model_rebuild() + + def _model_dump( + model: BaseModel, mode: Literal["json", "python"] = "json", **kwargs: Any + ) -> Any: + return model.model_dump(mode=mode, **kwargs) + + def _get_model_config(model: BaseModel) -> Any: + return model.model_config + + def get_schema_from_model_field( + *, + field: ModelField, + schema_generator: GenerateJsonSchema, + model_name_map: ModelNameMap, + field_mapping: Dict[ + Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue + ], + separate_input_output_schemas: bool = True, + ) -> Dict[str, Any]: + override_mode: Union[Literal["validation"], None] = ( + None if separate_input_output_schemas else "validation" + ) + # This expects that GenerateJsonSchema was already used to generate the definitions + json_schema = field_mapping[(field, override_mode or field.mode)] + if "$ref" not in json_schema: + # TODO remove when deprecating Pydantic v1 + # Ref: https://github.com/pydantic/pydantic/blob/d61792cc42c80b13b23e3ffa74bc37ec7c77f7d1/pydantic/schema.py#L207 + json_schema["title"] = ( + field.field_info.title or field.alias.title().replace("_", " ") + ) + return json_schema + + def get_compat_model_name_map(fields: List[ModelField]) -> ModelNameMap: + return {} + + def get_definitions( + *, + fields: List[ModelField], + schema_generator: GenerateJsonSchema, + model_name_map: ModelNameMap, + separate_input_output_schemas: bool = True, + ) -> Tuple[ + Dict[ + Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue + ], + Dict[str, Dict[str, Any]], + ]: + override_mode: Union[Literal["validation"], None] = ( + None if separate_input_output_schemas else "validation" + ) + inputs = [ + (field, override_mode or field.mode, field._type_adapter.core_schema) + for field in fields + ] + field_mapping, definitions = schema_generator.generate_definitions( + inputs=inputs + ) + return field_mapping, definitions # type: ignore[return-value] + + def is_scalar_field(field: ModelField) -> bool: + from fastapi import params + + return field_annotation_is_scalar( + field.field_info.annotation + ) and not isinstance(field.field_info, params.Body) + + def is_sequence_field(field: ModelField) -> bool: + return field_annotation_is_sequence(field.field_info.annotation) + + def is_scalar_sequence_field(field: ModelField) -> bool: + return field_annotation_is_scalar_sequence(field.field_info.annotation) + + def is_bytes_field(field: ModelField) -> bool: + return is_bytes_or_nonable_bytes_annotation(field.type_) + + def is_bytes_sequence_field(field: ModelField) -> bool: + return is_bytes_sequence_annotation(field.type_) + + def copy_field_info(*, field_info: FieldInfo, annotation: Any) -> FieldInfo: + cls = type(field_info) + merged_field_info = cls.from_annotation(annotation) + new_field_info = copy(field_info) + new_field_info.metadata = merged_field_info.metadata + new_field_info.annotation = merged_field_info.annotation + return new_field_info + + def serialize_sequence_value(*, field: ModelField, value: Any) -> Sequence[Any]: + origin_type = ( + get_origin(field.field_info.annotation) or field.field_info.annotation + ) + assert issubclass(origin_type, sequence_types) # type: ignore[arg-type] + return sequence_annotation_to_type[origin_type](value) # type: ignore[no-any-return] + + def get_missing_field_error(loc: Tuple[str, ...]) -> Dict[str, Any]: + error = ValidationError.from_exception_data( + "Field required", [{"type": "missing", "loc": loc, "input": {}}] + ).errors()[0] + error["input"] = None + return error # type: ignore[return-value] + + def create_body_model( + *, fields: Sequence[ModelField], model_name: str + ) -> Type[BaseModel]: + field_params = {f.name: (f.field_info.annotation, f.field_info) for f in fields} + BodyModel: Type[BaseModel] = create_model(model_name, **field_params) # type: ignore[call-overload] + return BodyModel + +else: + from fastapi.openapi.constants import REF_PREFIX as REF_PREFIX + from pydantic import AnyUrl as Url # noqa: F401 + from pydantic import ( # type: ignore[assignment] + BaseConfig as BaseConfig, # noqa: F401 + ) + from pydantic import ValidationError as ValidationError # noqa: F401 + from pydantic.class_validators import ( # type: ignore[no-redef] + Validator as Validator, # noqa: F401 + ) + from pydantic.error_wrappers import ( # type: ignore[no-redef] + ErrorWrapper as ErrorWrapper, # noqa: F401 + ) + from pydantic.errors import MissingError + from pydantic.fields import ( # type: ignore[attr-defined] + SHAPE_FROZENSET, + SHAPE_LIST, + SHAPE_SEQUENCE, + SHAPE_SET, + SHAPE_SINGLETON, + SHAPE_TUPLE, + SHAPE_TUPLE_ELLIPSIS, + ) + from pydantic.fields import FieldInfo as FieldInfo + from pydantic.fields import ( # type: ignore[no-redef,attr-defined] + ModelField as ModelField, # noqa: F401 + ) + from pydantic.fields import ( # type: ignore[no-redef,attr-defined] + Required as Required, # noqa: F401 + ) + from pydantic.fields import ( # type: ignore[no-redef,attr-defined] + Undefined as Undefined, + ) + from pydantic.fields import ( # type: ignore[no-redef, attr-defined] + UndefinedType as UndefinedType, # noqa: F401 + ) + from pydantic.schema import ( + field_schema, + get_flat_models_from_fields, + get_model_name_map, + model_process_schema, + ) + from pydantic.schema import ( # type: ignore[no-redef] # noqa: F401 + get_annotation_from_field_info as get_annotation_from_field_info, + ) + from pydantic.typing import ( # type: ignore[no-redef] + evaluate_forwardref as evaluate_forwardref, # noqa: F401 + ) + from pydantic.utils import ( # type: ignore[no-redef] + lenient_issubclass as lenient_issubclass, # noqa: F401 + ) + + GetJsonSchemaHandler = Any # type: ignore[assignment,misc] + JsonSchemaValue = Dict[str, Any] # type: ignore[misc] + CoreSchema = Any # type: ignore[assignment,misc] + + sequence_shapes = { + SHAPE_LIST, + SHAPE_SET, + SHAPE_FROZENSET, + SHAPE_TUPLE, + SHAPE_SEQUENCE, + SHAPE_TUPLE_ELLIPSIS, + } + sequence_shape_to_type = { + SHAPE_LIST: list, + SHAPE_SET: set, + SHAPE_TUPLE: tuple, + SHAPE_SEQUENCE: list, + SHAPE_TUPLE_ELLIPSIS: list, + } + + @dataclass + class GenerateJsonSchema: # type: ignore[no-redef] + ref_template: str + + class PydanticSchemaGenerationError(Exception): # type: ignore[no-redef] + pass + + def with_info_plain_validator_function( # type: ignore[misc] + function: Callable[..., Any], + *, + ref: Union[str, None] = None, + metadata: Any = None, + serialization: Any = None, + ) -> Any: + return {} + + def get_model_definitions( + *, + flat_models: Set[Union[Type[BaseModel], Type[Enum]]], + model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], + ) -> Dict[str, Any]: + definitions: Dict[str, Dict[str, Any]] = {} + for model in flat_models: + m_schema, m_definitions, m_nested_models = model_process_schema( + model, model_name_map=model_name_map, ref_prefix=REF_PREFIX + ) + definitions.update(m_definitions) + model_name = model_name_map[model] + if "description" in m_schema: + m_schema["description"] = m_schema["description"].split("\f")[0] + definitions[model_name] = m_schema + return definitions + + def is_pv1_scalar_field(field: ModelField) -> bool: + from fastapi import params + + field_info = field.field_info + if not ( + field.shape == SHAPE_SINGLETON # type: ignore[attr-defined] + and not lenient_issubclass(field.type_, BaseModel) + and not lenient_issubclass(field.type_, dict) + and not field_annotation_is_sequence(field.type_) + and not is_dataclass(field.type_) + and not isinstance(field_info, params.Body) + ): + return False + if field.sub_fields: # type: ignore[attr-defined] + if not all( + is_pv1_scalar_field(f) + for f in field.sub_fields # type: ignore[attr-defined] + ): + return False + return True + + def is_pv1_scalar_sequence_field(field: ModelField) -> bool: + if (field.shape in sequence_shapes) and not lenient_issubclass( # type: ignore[attr-defined] + field.type_, BaseModel + ): + if field.sub_fields is not None: # type: ignore[attr-defined] + for sub_field in field.sub_fields: # type: ignore[attr-defined] + if not is_pv1_scalar_field(sub_field): + return False + return True + if _annotation_is_sequence(field.type_): + return True + return False + + def _normalize_errors(errors: Sequence[Any]) -> List[Dict[str, Any]]: + use_errors: List[Any] = [] + for error in errors: + if isinstance(error, ErrorWrapper): + new_errors = ValidationError( # type: ignore[call-arg] + errors=[error], model=RequestErrorModel + ).errors() + use_errors.extend(new_errors) + elif isinstance(error, list): + use_errors.extend(_normalize_errors(error)) + else: + use_errors.append(error) + return use_errors + + def _model_rebuild(model: Type[BaseModel]) -> None: + model.update_forward_refs() + + def _model_dump( + model: BaseModel, mode: Literal["json", "python"] = "json", **kwargs: Any + ) -> Any: + return model.dict(**kwargs) + + def _get_model_config(model: BaseModel) -> Any: + return model.__config__ # type: ignore[attr-defined] + + def get_schema_from_model_field( + *, + field: ModelField, + schema_generator: GenerateJsonSchema, + model_name_map: ModelNameMap, + field_mapping: Dict[ + Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue + ], + separate_input_output_schemas: bool = True, + ) -> Dict[str, Any]: + # This expects that GenerateJsonSchema was already used to generate the definitions + return field_schema( # type: ignore[no-any-return] + field, model_name_map=model_name_map, ref_prefix=REF_PREFIX + )[0] + + def get_compat_model_name_map(fields: List[ModelField]) -> ModelNameMap: + models = get_flat_models_from_fields(fields, known_models=set()) + return get_model_name_map(models) # type: ignore[no-any-return] + + def get_definitions( + *, + fields: List[ModelField], + schema_generator: GenerateJsonSchema, + model_name_map: ModelNameMap, + separate_input_output_schemas: bool = True, + ) -> Tuple[ + Dict[ + Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue + ], + Dict[str, Dict[str, Any]], + ]: + models = get_flat_models_from_fields(fields, known_models=set()) + return {}, get_model_definitions( + flat_models=models, model_name_map=model_name_map + ) + + def is_scalar_field(field: ModelField) -> bool: + return is_pv1_scalar_field(field) + + def is_sequence_field(field: ModelField) -> bool: + return field.shape in sequence_shapes or _annotation_is_sequence(field.type_) # type: ignore[attr-defined] + + def is_scalar_sequence_field(field: ModelField) -> bool: + return is_pv1_scalar_sequence_field(field) + + def is_bytes_field(field: ModelField) -> bool: + return lenient_issubclass(field.type_, bytes) + + def is_bytes_sequence_field(field: ModelField) -> bool: + return field.shape in sequence_shapes and lenient_issubclass(field.type_, bytes) # type: ignore[attr-defined] + + def copy_field_info(*, field_info: FieldInfo, annotation: Any) -> FieldInfo: + return copy(field_info) + + def serialize_sequence_value(*, field: ModelField, value: Any) -> Sequence[Any]: + return sequence_shape_to_type[field.shape](value) # type: ignore[no-any-return,attr-defined] + + def get_missing_field_error(loc: Tuple[str, ...]) -> Dict[str, Any]: + missing_field_error = ErrorWrapper(MissingError(), loc=loc) # type: ignore[call-arg] + new_error = ValidationError([missing_field_error], RequestErrorModel) + return new_error.errors()[0] # type: ignore[return-value] + + def create_body_model( + *, fields: Sequence[ModelField], model_name: str + ) -> Type[BaseModel]: + BodyModel = create_model(model_name) + for f in fields: + BodyModel.__fields__[f.name] = f # type: ignore[index] + return BodyModel + + +def _regenerate_error_with_loc( + *, errors: Sequence[Any], loc_prefix: Tuple[Union[str, int], ...] +) -> List[Dict[str, Any]]: + updated_loc_errors: List[Any] = [ + {**err, "loc": loc_prefix + err.get("loc", ())} + for err in _normalize_errors(errors) + ] + + return updated_loc_errors + + +def _annotation_is_sequence(annotation: Union[Type[Any], None]) -> bool: + if lenient_issubclass(annotation, (str, bytes)): + return False + return lenient_issubclass(annotation, sequence_types) + + +def field_annotation_is_sequence(annotation: Union[Type[Any], None]) -> bool: + return _annotation_is_sequence(annotation) or _annotation_is_sequence( + get_origin(annotation) + ) + + +def value_is_sequence(value: Any) -> bool: + return isinstance(value, sequence_types) and not isinstance(value, (str, bytes)) # type: ignore[arg-type] + + +def _annotation_is_complex(annotation: Union[Type[Any], None]) -> bool: + return ( + lenient_issubclass(annotation, (BaseModel, Mapping, UploadFile)) + or _annotation_is_sequence(annotation) + or is_dataclass(annotation) + ) + + +def field_annotation_is_complex(annotation: Union[Type[Any], None]) -> bool: + origin = get_origin(annotation) + if origin is Union or origin is UnionType: + return any(field_annotation_is_complex(arg) for arg in get_args(annotation)) + + return ( + _annotation_is_complex(annotation) + or _annotation_is_complex(origin) + or hasattr(origin, "__pydantic_core_schema__") + or hasattr(origin, "__get_pydantic_core_schema__") + ) + + +def field_annotation_is_scalar(annotation: Any) -> bool: + # handle Ellipsis here to make tuple[int, ...] work nicely + return annotation is Ellipsis or not field_annotation_is_complex(annotation) + + +def field_annotation_is_scalar_sequence(annotation: Union[Type[Any], None]) -> bool: + origin = get_origin(annotation) + if origin is Union or origin is UnionType: + at_least_one_scalar_sequence = False + for arg in get_args(annotation): + if field_annotation_is_scalar_sequence(arg): + at_least_one_scalar_sequence = True + continue + elif not field_annotation_is_scalar(arg): + return False + return at_least_one_scalar_sequence + return field_annotation_is_sequence(annotation) and all( + field_annotation_is_scalar(sub_annotation) + for sub_annotation in get_args(annotation) + ) + + +def is_bytes_or_nonable_bytes_annotation(annotation: Any) -> bool: + if lenient_issubclass(annotation, bytes): + return True + origin = get_origin(annotation) + if origin is Union or origin is UnionType: + for arg in get_args(annotation): + if lenient_issubclass(arg, bytes): + return True + return False + + +def is_uploadfile_or_nonable_uploadfile_annotation(annotation: Any) -> bool: + if lenient_issubclass(annotation, UploadFile): + return True + origin = get_origin(annotation) + if origin is Union or origin is UnionType: + for arg in get_args(annotation): + if lenient_issubclass(arg, UploadFile): + return True + return False + + +def is_bytes_sequence_annotation(annotation: Any) -> bool: + origin = get_origin(annotation) + if origin is Union or origin is UnionType: + at_least_one = False + for arg in get_args(annotation): + if is_bytes_sequence_annotation(arg): + at_least_one = True + continue + return at_least_one + return field_annotation_is_sequence(annotation) and all( + is_bytes_or_nonable_bytes_annotation(sub_annotation) + for sub_annotation in get_args(annotation) + ) + + +def is_uploadfile_sequence_annotation(annotation: Any) -> bool: + origin = get_origin(annotation) + if origin is Union or origin is UnionType: + at_least_one = False + for arg in get_args(annotation): + if is_uploadfile_sequence_annotation(arg): + at_least_one = True + continue + return at_least_one + return field_annotation_is_sequence(annotation) and all( + is_uploadfile_or_nonable_uploadfile_annotation(sub_annotation) + for sub_annotation in get_args(annotation) + ) diff --git a/fastapi/applications.py b/fastapi/applications.py index 9b161c5ec832f..ffe9da35892d2 100644 --- a/fastapi/applications.py +++ b/fastapi/applications.py @@ -15,7 +15,6 @@ from fastapi import routing from fastapi.datastructures import Default, DefaultPlaceholder -from fastapi.encoders import DictIntStrAny, SetIntStr from fastapi.exception_handlers import ( http_exception_handler, request_validation_exception_handler, @@ -23,7 +22,6 @@ ) from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError from fastapi.logger import logger -from fastapi.middleware.asyncexitstack import AsyncExitStackMiddleware from fastapi.openapi.docs import ( get_redoc_html, get_swagger_ui_html, @@ -31,70 +29,800 @@ ) from fastapi.openapi.utils import get_openapi from fastapi.params import Depends -from fastapi.types import DecoratedCallable +from fastapi.types import DecoratedCallable, IncEx from fastapi.utils import generate_unique_id from starlette.applications import Starlette from starlette.datastructures import State from starlette.exceptions import HTTPException from starlette.middleware import Middleware from starlette.middleware.base import BaseHTTPMiddleware -from starlette.middleware.errors import ServerErrorMiddleware -from starlette.middleware.exceptions import ExceptionMiddleware from starlette.requests import Request from starlette.responses import HTMLResponse, JSONResponse, Response from starlette.routing import BaseRoute from starlette.types import ASGIApp, Lifespan, Receive, Scope, Send +from typing_extensions import Annotated, Doc, deprecated # type: ignore [attr-defined] AppType = TypeVar("AppType", bound="FastAPI") class FastAPI(Starlette): + """ + `FastAPI` app class, the main entrypoint to use FastAPI. + + Read more in the + [FastAPI docs for First Steps](https://fastapi.tiangolo.com/tutorial/first-steps/). + + ## Example + + ```python + from fastapi import FastAPI + + app = FastAPI() + ``` + """ + def __init__( self: AppType, *, - debug: bool = False, - routes: Optional[List[BaseRoute]] = None, - title: str = "FastAPI", - description: str = "", - version: str = "0.1.0", - openapi_url: Optional[str] = "/openapi.json", - openapi_tags: Optional[List[Dict[str, Any]]] = None, - servers: Optional[List[Dict[str, Union[str, Any]]]] = None, - dependencies: Optional[Sequence[Depends]] = None, - default_response_class: Type[Response] = Default(JSONResponse), - redirect_slashes: bool = True, - docs_url: Optional[str] = "/docs", - redoc_url: Optional[str] = "/redoc", - swagger_ui_oauth2_redirect_url: Optional[str] = "/docs/oauth2-redirect", - swagger_ui_init_oauth: Optional[Dict[str, Any]] = None, - middleware: Optional[Sequence[Middleware]] = None, - exception_handlers: Optional[ - Dict[ - Union[int, Type[Exception]], - Callable[[Request, Any], Coroutine[Any, Any, Response]], - ] - ] = None, - on_startup: Optional[Sequence[Callable[[], Any]]] = None, - on_shutdown: Optional[Sequence[Callable[[], Any]]] = None, - lifespan: Optional[Lifespan[AppType]] = None, - terms_of_service: Optional[str] = None, - contact: Optional[Dict[str, Union[str, Any]]] = None, - license_info: Optional[Dict[str, Union[str, Any]]] = None, - openapi_prefix: str = "", - root_path: str = "", - root_path_in_servers: bool = True, - responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, - callbacks: Optional[List[BaseRoute]] = None, - deprecated: Optional[bool] = None, - include_in_schema: bool = True, - swagger_ui_parameters: Optional[Dict[str, Any]] = None, - generate_unique_id_function: Callable[[routing.APIRoute], str] = Default( - generate_unique_id - ), - **extra: Any, + debug: Annotated[ + bool, + Doc( + """ + Boolean indicating if debug tracebacks should be returned on server + errors. + + Read more in the + [Starlette docs for Applications](https://www.starlette.io/applications/#instantiating-the-application). + """ + ), + ] = False, + routes: Annotated[ + Optional[List[BaseRoute]], + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited + from Starlette and supported for compatibility. + + --- + + A list of routes to serve incoming HTTP and WebSocket requests. + """ + ), + deprecated( + """ + You normally wouldn't use this parameter with FastAPI, it is inherited + from Starlette and supported for compatibility. + + In FastAPI, you normally would use the *path operation methods*, + like `app.get()`, `app.post()`, etc. + """ + ), + ] = None, + title: Annotated[ + str, + Doc( + """ + The title of the API. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more in the + [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api). + + **Example** + + ```python + from fastapi import FastAPI + + app = FastAPI(title="ChimichangApp") + ``` + """ + ), + ] = "FastAPI", + summary: Annotated[ + Optional[str], + Doc( + """ + A short summary of the API. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more in the + [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api). + + **Example** + + ```python + from fastapi import FastAPI + + app = FastAPI(summary="Deadpond's favorite app. Nuff said.") + ``` + """ + ), + ] = None, + description: Annotated[ + str, + Doc( + ''' + A description of the API. Supports Markdown (using + [CommonMark syntax](https://commonmark.org/)). + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more in the + [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api). + + **Example** + + ```python + from fastapi import FastAPI + + app = FastAPI( + description=""" + ChimichangApp API helps you do awesome stuff. 🚀 + + ## Items + + You can **read items**. + + ## Users + + You will be able to: + + * **Create users** (_not implemented_). + * **Read users** (_not implemented_). + + """ + ) + ``` + ''' + ), + ] = "", + version: Annotated[ + str, + Doc( + """ + The version of the API. + + **Note** This is the version of your application, not the version of + the OpenAPI specification nor the version of FastAPI being used. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more in the + [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api). + + **Example** + + ```python + from fastapi import FastAPI + + app = FastAPI(version="0.0.1") + ``` + """ + ), + ] = "0.1.0", + openapi_url: Annotated[ + Optional[str], + Doc( + """ + The URL where the OpenAPI schema will be served from. + + If you set it to `None`, no OpenAPI schema will be served publicly, and + the default automatic endpoints `/docs` and `/redoc` will also be + disabled. + + Read more in the + [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#openapi-url). + + **Example** + + ```python + from fastapi import FastAPI + + app = FastAPI(openapi_url="/api/v1/openapi.json") + ``` + """ + ), + ] = "/openapi.json", + openapi_tags: Annotated[ + Optional[List[Dict[str, Any]]], + Doc( + """ + A list of tags used by OpenAPI, these are the same `tags` you can set + in the *path operations*, like: + + * `@app.get("/users/", tags=["users"])` + * `@app.get("/items/", tags=["items"])` + + The order of the tags can be used to specify the order shown in + tools like Swagger UI, used in the automatic path `/docs`. + + It's not required to specify all the tags used. + + The tags that are not declared MAY be organized randomly or based + on the tools' logic. Each tag name in the list MUST be unique. + + The value of each item is a `dict` containing: + + * `name`: The name of the tag. + * `description`: A short description of the tag. + [CommonMark syntax](https://commonmark.org/) MAY be used for rich + text representation. + * `externalDocs`: Additional external documentation for this tag. If + provided, it would contain a `dict` with: + * `description`: A short description of the target documentation. + [CommonMark syntax](https://commonmark.org/) MAY be used for + rich text representation. + * `url`: The URL for the target documentation. Value MUST be in + the form of a URL. + + Read more in the + [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-tags). + + **Example** + + ```python + from fastapi import FastAPI + + tags_metadata = [ + { + "name": "users", + "description": "Operations with users. The **login** logic is also here.", + }, + { + "name": "items", + "description": "Manage items. So _fancy_ they have their own docs.", + "externalDocs": { + "description": "Items external docs", + "url": "https://fastapi.tiangolo.com/", + }, + }, + ] + + app = FastAPI(openapi_tags=tags_metadata) + ``` + """ + ), + ] = None, + servers: Annotated[ + Optional[List[Dict[str, Union[str, Any]]]], + Doc( + """ + A `list` of `dict`s with connectivity information to a target server. + + You would use it, for example, if your application is served from + different domains and you want to use the same Swagger UI in the + browser to interact with each of them (instead of having multiple + browser tabs open). Or if you want to leave fixed the possible URLs. + + If the servers `list` is not provided, or is an empty `list`, the + default value would be a `dict` with a `url` value of `/`. + + Each item in the `list` is a `dict` containing: + + * `url`: A URL to the target host. This URL supports Server Variables + and MAY be relative, to indicate that the host location is relative + to the location where the OpenAPI document is being served. Variable + substitutions will be made when a variable is named in `{`brackets`}`. + * `description`: An optional string describing the host designated by + the URL. [CommonMark syntax](https://commonmark.org/) MAY be used for + rich text representation. + * `variables`: A `dict` between a variable name and its value. The value + is used for substitution in the server's URL template. + + Read more in the + [FastAPI docs for Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/#additional-servers). + + **Example** + + ```python + from fastapi import FastAPI + + app = FastAPI( + servers=[ + {"url": "https://stag.example.com", "description": "Staging environment"}, + {"url": "https://prod.example.com", "description": "Production environment"}, + ] + ) + ``` + """ + ), + ] = None, + dependencies: Annotated[ + Optional[Sequence[Depends]], + Doc( + """ + A list of global dependencies, they will be applied to each + *path operation*, including in sub-routers. + + Read more about it in the + [FastAPI docs for Global Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/global-dependencies/). + + **Example** + + ```python + from fastapi import Depends, FastAPI + + from .dependencies import func_dep_1, func_dep_2 + + app = FastAPI(dependencies=[Depends(func_dep_1), Depends(func_dep_2)]) + ``` + """ + ), + ] = None, + default_response_class: Annotated[ + Type[Response], + Doc( + """ + The default response class to be used. + + Read more in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class). + + **Example** + + ```python + from fastapi import FastAPI + from fastapi.responses import ORJSONResponse + + app = FastAPI(default_response_class=ORJSONResponse) + ``` + """ + ), + ] = Default(JSONResponse), + redirect_slashes: Annotated[ + bool, + Doc( + """ + Whether to detect and redirect slashes in URLs when the client doesn't + use the same format. + + **Example** + + ```python + from fastapi import FastAPI + + app = FastAPI(redirect_slashes=True) # the default + + @app.get("/items/") + async def read_items(): + return [{"item_id": "Foo"}] + ``` + + With this app, if a client goes to `/items` (without a trailing slash), + they will be automatically redirected with an HTTP status code of 307 + to `/items/`. + """ + ), + ] = True, + docs_url: Annotated[ + Optional[str], + Doc( + """ + The path to the automatic interactive API documentation. + It is handled in the browser by Swagger UI. + + The default URL is `/docs`. You can disable it by setting it to `None`. + + If `openapi_url` is set to `None`, this will be automatically disabled. + + Read more in the + [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#docs-urls). + + **Example** + + ```python + from fastapi import FastAPI + + app = FastAPI(docs_url="/documentation", redoc_url=None) + ``` + """ + ), + ] = "/docs", + redoc_url: Annotated[ + Optional[str], + Doc( + """ + The path to the alternative automatic interactive API documentation + provided by ReDoc. + + The default URL is `/redoc`. You can disable it by setting it to `None`. + + If `openapi_url` is set to `None`, this will be automatically disabled. + + Read more in the + [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#docs-urls). + + **Example** + + ```python + from fastapi import FastAPI + + app = FastAPI(docs_url="/documentation", redoc_url="redocumentation") + ``` + """ + ), + ] = "/redoc", + swagger_ui_oauth2_redirect_url: Annotated[ + Optional[str], + Doc( + """ + The OAuth2 redirect endpoint for the Swagger UI. + + By default it is `/docs/oauth2-redirect`. + + This is only used if you use OAuth2 (with the "Authorize" button) + with Swagger UI. + """ + ), + ] = "/docs/oauth2-redirect", + swagger_ui_init_oauth: Annotated[ + Optional[Dict[str, Any]], + Doc( + """ + OAuth2 configuration for the Swagger UI, by default shown at `/docs`. + + Read more about the available configuration options in the + [Swagger UI docs](https://swagger.io/docs/open-source-tools/swagger-ui/usage/oauth2/). + """ + ), + ] = None, + middleware: Annotated[ + Optional[Sequence[Middleware]], + Doc( + """ + List of middleware to be added when creating the application. + + In FastAPI you would normally do this with `app.add_middleware()` + instead. + + Read more in the + [FastAPI docs for Middleware](https://fastapi.tiangolo.com/tutorial/middleware/). + """ + ), + ] = None, + exception_handlers: Annotated[ + Optional[ + Dict[ + Union[int, Type[Exception]], + Callable[[Request, Any], Coroutine[Any, Any, Response]], + ] + ], + Doc( + """ + A dictionary with handlers for exceptions. + + In FastAPI, you would normally use the decorator + `@app.exception_handler()`. + + Read more in the + [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/). + """ + ), + ] = None, + on_startup: Annotated[ + Optional[Sequence[Callable[[], Any]]], + Doc( + """ + A list of startup event handler functions. + + You should instead use the `lifespan` handlers. + + Read more in the [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/). + """ + ), + ] = None, + on_shutdown: Annotated[ + Optional[Sequence[Callable[[], Any]]], + Doc( + """ + A list of shutdown event handler functions. + + You should instead use the `lifespan` handlers. + + Read more in the + [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/). + """ + ), + ] = None, + lifespan: Annotated[ + Optional[Lifespan[AppType]], + Doc( + """ + A `Lifespan` context manager handler. This replaces `startup` and + `shutdown` functions with a single context manager. + + Read more in the + [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/). + """ + ), + ] = None, + terms_of_service: Annotated[ + Optional[str], + Doc( + """ + A URL to the Terms of Service for your API. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more at the + [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api). + + **Example** + + ```python + app = FastAPI(terms_of_service="http://example.com/terms/") + ``` + """ + ), + ] = None, + contact: Annotated[ + Optional[Dict[str, Union[str, Any]]], + Doc( + """ + A dictionary with the contact information for the exposed API. + + It can contain several fields. + + * `name`: (`str`) The name of the contact person/organization. + * `url`: (`str`) A URL pointing to the contact information. MUST be in + the format of a URL. + * `email`: (`str`) The email address of the contact person/organization. + MUST be in the format of an email address. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more at the + [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api). + + **Example** + + ```python + app = FastAPI( + contact={ + "name": "Deadpoolio the Amazing", + "url": "http://x-force.example.com/contact/", + "email": "dp@x-force.example.com", + } + ) + ``` + """ + ), + ] = None, + license_info: Annotated[ + Optional[Dict[str, Union[str, Any]]], + Doc( + """ + A dictionary with the license information for the exposed API. + + It can contain several fields. + + * `name`: (`str`) **REQUIRED** (if a `license_info` is set). The + license name used for the API. + * `identifier`: (`str`) An [SPDX](https://spdx.dev/) license expression + for the API. The `identifier` field is mutually exclusive of the `url` + field. Available since OpenAPI 3.1.0, FastAPI 0.99.0. + * `url`: (`str`) A URL to the license used for the API. This MUST be + the format of a URL. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more at the + [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api). + + **Example** + + ```python + app = FastAPI( + license_info={ + "name": "Apache 2.0", + "url": "https://www.apache.org/licenses/LICENSE-2.0.html", + } + ) + ``` + """ + ), + ] = None, + openapi_prefix: Annotated[ + str, + Doc( + """ + A URL prefix for the OpenAPI URL. + """ + ), + deprecated( + """ + "openapi_prefix" has been deprecated in favor of "root_path", which + follows more closely the ASGI standard, is simpler, and more + automatic. + """ + ), + ] = "", + root_path: Annotated[ + str, + Doc( + """ + A path prefix handled by a proxy that is not seen by the application + but is seen by external clients, which affects things like Swagger UI. + + Read more about it at the + [FastAPI docs for Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/). + + **Example** + + ```python + from fastapi import FastAPI + + app = FastAPI(root_path="/api/v1") + ``` + """ + ), + ] = "", + root_path_in_servers: Annotated[ + bool, + Doc( + """ + To disable automatically generating the URLs in the `servers` field + in the autogenerated OpenAPI using the `root_path`. + + Read more about it in the + [FastAPI docs for Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/#disable-automatic-server-from-root_path). + + **Example** + + ```python + from fastapi import FastAPI + + app = FastAPI(root_path_in_servers=False) + ``` + """ + ), + ] = True, + responses: Annotated[ + Optional[Dict[Union[int, str], Dict[str, Any]]], + Doc( + """ + Additional responses to be shown in OpenAPI. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/). + + And in the + [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies). + """ + ), + ] = None, + callbacks: Annotated[ + Optional[List[BaseRoute]], + Doc( + """ + OpenAPI callbacks that should apply to all *path operations*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + webhooks: Annotated[ + Optional[routing.APIRouter], + Doc( + """ + Add OpenAPI webhooks. This is similar to `callbacks` but it doesn't + depend on specific *path operations*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + **Note**: This is available since OpenAPI 3.1.0, FastAPI 0.99.0. + + Read more about it in the + [FastAPI docs for OpenAPI Webhooks](https://fastapi.tiangolo.com/advanced/openapi-webhooks/). + """ + ), + ] = None, + deprecated: Annotated[ + Optional[bool], + Doc( + """ + Mark all *path operations* as deprecated. You probably don't need it, + but it's available. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + include_in_schema: Annotated[ + bool, + Doc( + """ + To include (or not) all the *path operations* in the generated OpenAPI. + You probably don't need it, but it's available. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi). + """ + ), + ] = True, + swagger_ui_parameters: Annotated[ + Optional[Dict[str, Any]], + Doc( + """ + Parameters to configure Swagger UI, the autogenerated interactive API + documentation (by default at `/docs`). + + Read more about it in the + [FastAPI docs about how to Configure Swagger UI](https://fastapi.tiangolo.com/how-to/configure-swagger-ui/). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[routing.APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), + separate_input_output_schemas: Annotated[ + bool, + Doc( + """ + Whether to generate separate OpenAPI schemas for request body and + response body when the results would be more precise. + + This is particularly useful when automatically generating clients. + + For example, if you have a model like: + + ```python + from pydantic import BaseModel + + class Item(BaseModel): + name: str + tags: list[str] = [] + ``` + + When `Item` is used for input, a request body, `tags` is not required, + the client doesn't have to provide it. + + But when using `Item` for output, for a response body, `tags` is always + available because it has a default value, even if it's just an empty + list. So, the client should be able to always expect it. + + In this case, there would be two different schemas, one for input and + another one for output. + """ + ), + ] = True, + **extra: Annotated[ + Any, + Doc( + """ + Extra keyword arguments to be stored in the app, not used by FastAPI + anywhere. + """ + ), + ], ) -> None: self.debug = debug self.title = title + self.summary = summary self.description = description self.version = version self.terms_of_service = terms_of_service @@ -109,8 +837,39 @@ def __init__( self.swagger_ui_init_oauth = swagger_ui_init_oauth self.swagger_ui_parameters = swagger_ui_parameters self.servers = servers or [] + self.separate_input_output_schemas = separate_input_output_schemas self.extra = extra - self.openapi_version = "3.0.2" + self.openapi_version: Annotated[ + str, + Doc( + """ + The version string of OpenAPI. + + FastAPI will generate OpenAPI version 3.1.0, and will output that as + the OpenAPI version. But some tools, even though they might be + compatible with OpenAPI 3.1.0, might not recognize it as a valid. + + So you could override this value to trick those tools into using + the generated OpenAPI. Have in mind that this is a hack. But if you + avoid using features added in OpenAPI 3.1.0, it might work for your + use case. + + This is not passed as a parameter to the `FastAPI` class to avoid + giving the false idea that FastAPI would generate a different OpenAPI + schema. It is only available as an attribute. + + **Example** + + ```python + from fastapi import FastAPI + + app = FastAPI() + + app.openapi_version = "3.0.2" + ``` + """ + ), + ] = "3.1.0" self.openapi_schema: Optional[Dict[str, Any]] = None if self.openapi_url: assert self.title, "A title must be provided for OpenAPI, e.g.: 'My API'" @@ -123,9 +882,53 @@ def __init__( "automatic. Check the docs at " "https://fastapi.tiangolo.com/advanced/sub-applications/" ) + self.webhooks: Annotated[ + routing.APIRouter, + Doc( + """ + The `app.webhooks` attribute is an `APIRouter` with the *path + operations* that will be used just for documentation of webhooks. + + Read more about it in the + [FastAPI docs for OpenAPI Webhooks](https://fastapi.tiangolo.com/advanced/openapi-webhooks/). + """ + ), + ] = webhooks or routing.APIRouter() self.root_path = root_path or openapi_prefix - self.state: State = State() - self.dependency_overrides: Dict[Callable[..., Any], Callable[..., Any]] = {} + self.state: Annotated[ + State, + Doc( + """ + A state object for the application. This is the same object for the + entire application, it doesn't change from request to request. + + You normally woudln't use this in FastAPI, for most of the cases you + would instead use FastAPI dependencies. + + This is simply inherited from Starlette. + + Read more about it in the + [Starlette docs for Applications](https://www.starlette.io/applications/#storing-state-on-the-app-instance). + """ + ), + ] = State() + self.dependency_overrides: Annotated[ + Dict[Callable[..., Any], Callable[..., Any]], + Doc( + """ + A dictionary with overrides for the dependencies. + + Each key is the original dependency callable, and the value is the + actual dependency that should be called. + + This is for testing, to replace expensive dependencies with testing + versions. + + Read more about it in the + [FastAPI docs for Testing Dependencies with Overrides](https://fastapi.tiangolo.com/advanced/testing-dependencies/). + """ + ), + ] = {} self.router: routing.APIRouter = routing.APIRouter( routes=routes, redirect_slashes=redirect_slashes, @@ -143,7 +946,7 @@ def __init__( ) self.exception_handlers: Dict[ Any, Callable[[Request, Any], Union[Response, Awaitable[Response]]] - ] = ({} if exception_handlers is None else dict(exception_handlers)) + ] = {} if exception_handlers is None else dict(exception_handlers) self.exception_handlers.setdefault(HTTPException, http_exception_handler) self.exception_handlers.setdefault( RequestValidationError, request_validation_exception_handler @@ -160,68 +963,35 @@ def __init__( self.middleware_stack: Union[ASGIApp, None] = None self.setup() - def build_middleware_stack(self) -> ASGIApp: - # Duplicate/override from Starlette to add AsyncExitStackMiddleware - # inside of ExceptionMiddleware, inside of custom user middlewares - debug = self.debug - error_handler = None - exception_handlers = {} - - for key, value in self.exception_handlers.items(): - if key in (500, Exception): - error_handler = value - else: - exception_handlers[key] = value - - middleware = ( - [Middleware(ServerErrorMiddleware, handler=error_handler, debug=debug)] - + self.user_middleware - + [ - Middleware( - ExceptionMiddleware, handlers=exception_handlers, debug=debug - ), - # Add FastAPI-specific AsyncExitStackMiddleware for dependencies with - # contextvars. - # This needs to happen after user middlewares because those create a - # new contextvars context copy by using a new AnyIO task group. - # The initial part of dependencies with yield is executed in the - # FastAPI code, inside all the middlewares, but the teardown part - # (after yield) is executed in the AsyncExitStack in this middleware, - # if the AsyncExitStack lived outside of the custom middlewares and - # contextvars were set in a dependency with yield in that internal - # contextvars context, the values would not be available in the - # outside context of the AsyncExitStack. - # By putting the middleware and the AsyncExitStack here, inside all - # user middlewares, the code before and after yield in dependencies - # with yield is executed in the same contextvars context, so all values - # set in contextvars before yield is still available after yield as - # would be expected. - # Additionally, by having this AsyncExitStack here, after the - # ExceptionMiddleware, now dependencies can catch handled exceptions, - # e.g. HTTPException, to customize the teardown code (e.g. DB session - # rollback). - Middleware(AsyncExitStackMiddleware), - ] - ) + def openapi(self) -> Dict[str, Any]: + """ + Generate the OpenAPI schema of the application. This is called by FastAPI + internally. - app = self.router - for cls, options in reversed(middleware): - app = cls(app=app, **options) - return app + The first time it is called it stores the result in the attribute + `app.openapi_schema`, and next times it is called, it just returns that same + result. To avoid the cost of generating the schema every time. - def openapi(self) -> Dict[str, Any]: + If you need to modify the generated OpenAPI schema, you could modify it. + + Read more in the + [FastAPI docs for OpenAPI](https://fastapi.tiangolo.com/how-to/extending-openapi/). + """ if not self.openapi_schema: self.openapi_schema = get_openapi( title=self.title, version=self.version, openapi_version=self.openapi_version, + summary=self.summary, description=self.description, terms_of_service=self.terms_of_service, contact=self.contact, license_info=self.license_info, routes=self.routes, + webhooks=self.webhooks.routes, tags=self.openapi_tags, servers=self.servers, + separate_input_output_schemas=self.separate_input_output_schemas, ) return self.openapi_schema @@ -299,8 +1069,8 @@ def add_api_route( deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, - response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, - response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, + response_model_include: Optional[IncEx] = None, + response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, @@ -357,8 +1127,8 @@ def api_route( deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, - response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, - response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, + response_model_include: Optional[IncEx] = None, + response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, @@ -419,11 +1189,58 @@ def add_api_websocket_route( def websocket( self, - path: str, - name: Optional[str] = None, + path: Annotated[ + str, + Doc( + """ + WebSocket path. + """ + ), + ], + name: Annotated[ + Optional[str], + Doc( + """ + A name for the WebSocket. Only used internally. + """ + ), + ] = None, *, - dependencies: Optional[Sequence[Depends]] = None, + dependencies: Annotated[ + Optional[Sequence[Depends]], + Doc( + """ + A list of dependencies (using `Depends()`) to be used for this + WebSocket. + + Read more about it in the + [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). + """ + ), + ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Decorate a WebSocket function. + + Read more about it in the + [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). + + **Example** + + ```python + from fastapi import FastAPI, WebSocket + + app = FastAPI() + + @app.websocket("/ws") + async def websocket_endpoint(websocket: WebSocket): + await websocket.accept() + while True: + data = await websocket.receive_text() + await websocket.send_text(f"Message text was: {data}") + ``` + """ + def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, @@ -437,67 +1254,561 @@ def decorator(func: DecoratedCallable) -> DecoratedCallable: def include_router( self, - router: routing.APIRouter, + router: Annotated[routing.APIRouter, Doc("The `APIRouter` to include.")], *, - prefix: str = "", - tags: Optional[List[Union[str, Enum]]] = None, - dependencies: Optional[Sequence[Depends]] = None, - responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, - deprecated: Optional[bool] = None, - include_in_schema: bool = True, - default_response_class: Type[Response] = Default(JSONResponse), - callbacks: Optional[List[BaseRoute]] = None, - generate_unique_id_function: Callable[[routing.APIRoute], str] = Default( - generate_unique_id - ), - ) -> None: - self.router.include_router( - router, - prefix=prefix, - tags=tags, - dependencies=dependencies, - responses=responses, - deprecated=deprecated, - include_in_schema=include_in_schema, - default_response_class=default_response_class, - callbacks=callbacks, - generate_unique_id_function=generate_unique_id_function, - ) + prefix: Annotated[str, Doc("An optional path prefix for the router.")] = "", + tags: Annotated[ + Optional[List[Union[str, Enum]]], + Doc( + """ + A list of tags to be applied to all the *path operations* in this + router. - def get( - self, - path: str, - *, - response_model: Any = Default(None), - status_code: Optional[int] = None, - tags: Optional[List[Union[str, Enum]]] = None, - dependencies: Optional[Sequence[Depends]] = None, - summary: Optional[str] = None, - description: Optional[str] = None, - response_description: str = "Successful Response", - responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, - deprecated: Optional[bool] = None, - operation_id: Optional[str] = None, - response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, - response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, - response_model_by_alias: bool = True, - response_model_exclude_unset: bool = False, - response_model_exclude_defaults: bool = False, - response_model_exclude_none: bool = False, - include_in_schema: bool = True, - response_class: Type[Response] = Default(JSONResponse), - name: Optional[str] = None, - callbacks: Optional[List[BaseRoute]] = None, - openapi_extra: Optional[Dict[str, Any]] = None, - generate_unique_id_function: Callable[[routing.APIRoute], str] = Default( - generate_unique_id - ), - ) -> Callable[[DecoratedCallable], DecoratedCallable]: - return self.router.get( - path, - response_model=response_model, - status_code=status_code, - tags=tags, + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + dependencies: Annotated[ + Optional[Sequence[Depends]], + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to all the + *path operations* in this router. + + Read more about it in the + [FastAPI docs for Bigger Applications - Multiple Files](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies). + + **Example** + + ```python + from fastapi import Depends, FastAPI + + from .dependencies import get_token_header + from .internal import admin + + app = FastAPI() + + app.include_router( + admin.router, + dependencies=[Depends(get_token_header)], + ) + ``` + """ + ), + ] = None, + responses: Annotated[ + Optional[Dict[Union[int, str], Dict[str, Any]]], + Doc( + """ + Additional responses to be shown in OpenAPI. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/). + + And in the + [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies). + """ + ), + ] = None, + deprecated: Annotated[ + Optional[bool], + Doc( + """ + Mark all the *path operations* in this router as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + **Example** + + ```python + from fastapi import FastAPI + + from .internal import old_api + + app = FastAPI() + + app.include_router( + old_api.router, + deprecated=True, + ) + ``` + """ + ), + ] = None, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include (or not) all the *path operations* in this router in the + generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + **Example** + + ```python + from fastapi import FastAPI + + from .internal import old_api + + app = FastAPI() + + app.include_router( + old_api.router, + include_in_schema=False, + ) + ``` + """ + ), + ] = True, + default_response_class: Annotated[ + Type[Response], + Doc( + """ + Default response class to be used for the *path operations* in this + router. + + Read more in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class). + + **Example** + + ```python + from fastapi import FastAPI + from fastapi.responses import ORJSONResponse + + from .internal import old_api + + app = FastAPI() + + app.include_router( + old_api.router, + default_response_class=ORJSONResponse, + ) + ``` + """ + ), + ] = Default(JSONResponse), + callbacks: Annotated[ + Optional[List[BaseRoute]], + Doc( + """ + List of *path operations* that will be used as OpenAPI callbacks. + + This is only for OpenAPI documentation, the callbacks won't be used + directly. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[routing.APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), + ) -> None: + """ + Include an `APIRouter` in the same app. + + Read more about it in the + [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). + + ## Example + + ```python + from fastapi import FastAPI + + from .users import users_router + + app = FastAPI() + + app.include_router(users_router) + ``` + """ + self.router.include_router( + router, + prefix=prefix, + tags=tags, + dependencies=dependencies, + responses=responses, + deprecated=deprecated, + include_in_schema=include_in_schema, + default_response_class=default_response_class, + callbacks=callbacks, + generate_unique_id_function=generate_unique_id_function, + ) + + def get( + self, + path: Annotated[ + str, + Doc( + """ + The URL path to be used for this *path operation*. + + For example, in `http://example.com/items`, the path is `/items`. + """ + ), + ], + *, + response_model: Annotated[ + Any, + Doc( + """ + The type to use for the response. + + It could be any valid Pydantic *field* type. So, it doesn't have to + be a Pydantic model, it could be other things, like a `list`, `dict`, + etc. + + It will be used for: + + * Documentation: the generated OpenAPI (and the UI at `/docs`) will + show it as the response (JSON Schema). + * Serialization: you could return an arbitrary object and the + `response_model` would be used to serialize that object into the + corresponding JSON. + * Filtering: the JSON sent to the client will only contain the data + (fields) defined in the `response_model`. If you returned an object + that contains an attribute `password` but the `response_model` does + not include that field, the JSON sent to the client would not have + that `password`. + * Validation: whatever you return will be serialized with the + `response_model`, converting any data as necessary to generate the + corresponding JSON. But if the data in the object returned is not + valid, that would mean a violation of the contract with the client, + so it's an error from the API developer. So, FastAPI will raise an + error and return a 500 error code (Internal Server Error). + + Read more about it in the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + """ + ), + ] = Default(None), + status_code: Annotated[ + Optional[int], + Doc( + """ + The default status code to be used for the response. + + You could override the status code by returning a response directly. + + Read more about it in the + [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). + """ + ), + ] = None, + tags: Annotated[ + Optional[List[Union[str, Enum]]], + Doc( + """ + A list of tags to be applied to the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). + """ + ), + ] = None, + dependencies: Annotated[ + Optional[Sequence[Depends]], + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to the + *path operation*. + + Read more about it in the + [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). + """ + ), + ] = None, + summary: Annotated[ + Optional[str], + Doc( + """ + A summary for the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + A description for the *path operation*. + + If not provided, it will be extracted automatically from the docstring + of the *path operation function*. + + It can contain Markdown. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + response_description: Annotated[ + str, + Doc( + """ + The description for the default response. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = "Successful Response", + responses: Annotated[ + Optional[Dict[Union[int, str], Dict[str, Any]]], + Doc( + """ + Additional responses that could be returned by this *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + deprecated: Annotated[ + Optional[bool], + Doc( + """ + Mark this *path operation* as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + operation_id: Annotated[ + Optional[str], + Doc( + """ + Custom operation ID to be used by this *path operation*. + + By default, it is generated automatically. + + If you provide a custom operation ID, you need to make sure it is + unique for the whole API. + + You can customize the + operation ID generation with the parameter + `generate_unique_id_function` in the `FastAPI` class. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = None, + response_model_include: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to include only certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_exclude: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to exclude certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_by_alias: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response model + should be serialized by alias when an alias is used. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = True, + response_model_exclude_unset: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that were not set and + have their default values. This is different from + `response_model_exclude_defaults` in that if the fields are set, + they will be included in the response, even if the value is the same + as the default. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_defaults: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that have the same value + as the default. This is different from `response_model_exclude_unset` + in that if the fields are set but contain the same default values, + they will be excluded from the response. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_none: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data should + exclude fields set to `None`. + + This is much simpler (less smart) than `response_model_exclude_unset` + and `response_model_exclude_defaults`. You probably want to use one of + those two instead of this one, as those allow returning `None` values + when it makes sense. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). + """ + ), + ] = False, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include this *path operation* in the generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi). + """ + ), + ] = True, + response_class: Annotated[ + Type[Response], + Doc( + """ + Response class to be used for this *path operation*. + + This will not be used if you return a response directly. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). + """ + ), + ] = Default(JSONResponse), + name: Annotated[ + Optional[str], + Doc( + """ + Name for this *path operation*. Only used internally. + """ + ), + ] = None, + callbacks: Annotated[ + Optional[List[BaseRoute]], + Doc( + """ + List of *path operations* that will be used as OpenAPI callbacks. + + This is only for OpenAPI documentation, the callbacks won't be used + directly. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + openapi_extra: Annotated[ + Optional[Dict[str, Any]], + Doc( + """ + Extra metadata to be included in the OpenAPI schema for this *path + operation*. + + Read more about it in the + [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[routing.APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP GET operation. + + ## Example + + ```python + from fastapi import FastAPI + + app = FastAPI() + + @app.get("/items/") + def read_items(): + return [{"name": "Empanada"}, {"name": "Arepa"}] + ``` + """ + return self.router.get( + path, + response_model=response_model, + status_code=status_code, + tags=tags, dependencies=dependencies, summary=summary, description=description, @@ -521,33 +1832,356 @@ def get( def put( self, - path: str, + path: Annotated[ + str, + Doc( + """ + The URL path to be used for this *path operation*. + + For example, in `http://example.com/items`, the path is `/items`. + """ + ), + ], *, - response_model: Any = Default(None), - status_code: Optional[int] = None, - tags: Optional[List[Union[str, Enum]]] = None, - dependencies: Optional[Sequence[Depends]] = None, - summary: Optional[str] = None, - description: Optional[str] = None, - response_description: str = "Successful Response", - responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, - deprecated: Optional[bool] = None, - operation_id: Optional[str] = None, - response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, - response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, - response_model_by_alias: bool = True, - response_model_exclude_unset: bool = False, - response_model_exclude_defaults: bool = False, - response_model_exclude_none: bool = False, - include_in_schema: bool = True, - response_class: Type[Response] = Default(JSONResponse), - name: Optional[str] = None, - callbacks: Optional[List[BaseRoute]] = None, - openapi_extra: Optional[Dict[str, Any]] = None, - generate_unique_id_function: Callable[[routing.APIRoute], str] = Default( - generate_unique_id - ), + response_model: Annotated[ + Any, + Doc( + """ + The type to use for the response. + + It could be any valid Pydantic *field* type. So, it doesn't have to + be a Pydantic model, it could be other things, like a `list`, `dict`, + etc. + + It will be used for: + + * Documentation: the generated OpenAPI (and the UI at `/docs`) will + show it as the response (JSON Schema). + * Serialization: you could return an arbitrary object and the + `response_model` would be used to serialize that object into the + corresponding JSON. + * Filtering: the JSON sent to the client will only contain the data + (fields) defined in the `response_model`. If you returned an object + that contains an attribute `password` but the `response_model` does + not include that field, the JSON sent to the client would not have + that `password`. + * Validation: whatever you return will be serialized with the + `response_model`, converting any data as necessary to generate the + corresponding JSON. But if the data in the object returned is not + valid, that would mean a violation of the contract with the client, + so it's an error from the API developer. So, FastAPI will raise an + error and return a 500 error code (Internal Server Error). + + Read more about it in the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + """ + ), + ] = Default(None), + status_code: Annotated[ + Optional[int], + Doc( + """ + The default status code to be used for the response. + + You could override the status code by returning a response directly. + + Read more about it in the + [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). + """ + ), + ] = None, + tags: Annotated[ + Optional[List[Union[str, Enum]]], + Doc( + """ + A list of tags to be applied to the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). + """ + ), + ] = None, + dependencies: Annotated[ + Optional[Sequence[Depends]], + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to the + *path operation*. + + Read more about it in the + [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). + """ + ), + ] = None, + summary: Annotated[ + Optional[str], + Doc( + """ + A summary for the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + A description for the *path operation*. + + If not provided, it will be extracted automatically from the docstring + of the *path operation function*. + + It can contain Markdown. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + response_description: Annotated[ + str, + Doc( + """ + The description for the default response. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = "Successful Response", + responses: Annotated[ + Optional[Dict[Union[int, str], Dict[str, Any]]], + Doc( + """ + Additional responses that could be returned by this *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + deprecated: Annotated[ + Optional[bool], + Doc( + """ + Mark this *path operation* as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + operation_id: Annotated[ + Optional[str], + Doc( + """ + Custom operation ID to be used by this *path operation*. + + By default, it is generated automatically. + + If you provide a custom operation ID, you need to make sure it is + unique for the whole API. + + You can customize the + operation ID generation with the parameter + `generate_unique_id_function` in the `FastAPI` class. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = None, + response_model_include: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to include only certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_exclude: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to exclude certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_by_alias: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response model + should be serialized by alias when an alias is used. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = True, + response_model_exclude_unset: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that were not set and + have their default values. This is different from + `response_model_exclude_defaults` in that if the fields are set, + they will be included in the response, even if the value is the same + as the default. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_defaults: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that have the same value + as the default. This is different from `response_model_exclude_unset` + in that if the fields are set but contain the same default values, + they will be excluded from the response. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_none: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data should + exclude fields set to `None`. + + This is much simpler (less smart) than `response_model_exclude_unset` + and `response_model_exclude_defaults`. You probably want to use one of + those two instead of this one, as those allow returning `None` values + when it makes sense. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). + """ + ), + ] = False, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include this *path operation* in the generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi). + """ + ), + ] = True, + response_class: Annotated[ + Type[Response], + Doc( + """ + Response class to be used for this *path operation*. + + This will not be used if you return a response directly. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). + """ + ), + ] = Default(JSONResponse), + name: Annotated[ + Optional[str], + Doc( + """ + Name for this *path operation*. Only used internally. + """ + ), + ] = None, + callbacks: Annotated[ + Optional[List[BaseRoute]], + Doc( + """ + List of *path operations* that will be used as OpenAPI callbacks. + + This is only for OpenAPI documentation, the callbacks won't be used + directly. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + openapi_extra: Annotated[ + Optional[Dict[str, Any]], + Doc( + """ + Extra metadata to be included in the OpenAPI schema for this *path + operation*. + + Read more about it in the + [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[routing.APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP PUT operation. + + ## Example + + ```python + from fastapi import FastAPI + from pydantic import BaseModel + + class Item(BaseModel): + name: str + description: str | None = None + + app = FastAPI() + + @app.put("/items/{item_id}") + def replace_item(item_id: str, item: Item): + return {"message": "Item replaced", "id": item_id} + ``` + """ return self.router.put( path, response_model=response_model, @@ -576,33 +2210,356 @@ def put( def post( self, - path: str, + path: Annotated[ + str, + Doc( + """ + The URL path to be used for this *path operation*. + + For example, in `http://example.com/items`, the path is `/items`. + """ + ), + ], *, - response_model: Any = Default(None), - status_code: Optional[int] = None, - tags: Optional[List[Union[str, Enum]]] = None, - dependencies: Optional[Sequence[Depends]] = None, - summary: Optional[str] = None, - description: Optional[str] = None, - response_description: str = "Successful Response", - responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, - deprecated: Optional[bool] = None, - operation_id: Optional[str] = None, - response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, - response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, - response_model_by_alias: bool = True, - response_model_exclude_unset: bool = False, - response_model_exclude_defaults: bool = False, - response_model_exclude_none: bool = False, - include_in_schema: bool = True, - response_class: Type[Response] = Default(JSONResponse), - name: Optional[str] = None, - callbacks: Optional[List[BaseRoute]] = None, - openapi_extra: Optional[Dict[str, Any]] = None, - generate_unique_id_function: Callable[[routing.APIRoute], str] = Default( - generate_unique_id - ), + response_model: Annotated[ + Any, + Doc( + """ + The type to use for the response. + + It could be any valid Pydantic *field* type. So, it doesn't have to + be a Pydantic model, it could be other things, like a `list`, `dict`, + etc. + + It will be used for: + + * Documentation: the generated OpenAPI (and the UI at `/docs`) will + show it as the response (JSON Schema). + * Serialization: you could return an arbitrary object and the + `response_model` would be used to serialize that object into the + corresponding JSON. + * Filtering: the JSON sent to the client will only contain the data + (fields) defined in the `response_model`. If you returned an object + that contains an attribute `password` but the `response_model` does + not include that field, the JSON sent to the client would not have + that `password`. + * Validation: whatever you return will be serialized with the + `response_model`, converting any data as necessary to generate the + corresponding JSON. But if the data in the object returned is not + valid, that would mean a violation of the contract with the client, + so it's an error from the API developer. So, FastAPI will raise an + error and return a 500 error code (Internal Server Error). + + Read more about it in the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + """ + ), + ] = Default(None), + status_code: Annotated[ + Optional[int], + Doc( + """ + The default status code to be used for the response. + + You could override the status code by returning a response directly. + + Read more about it in the + [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). + """ + ), + ] = None, + tags: Annotated[ + Optional[List[Union[str, Enum]]], + Doc( + """ + A list of tags to be applied to the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). + """ + ), + ] = None, + dependencies: Annotated[ + Optional[Sequence[Depends]], + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to the + *path operation*. + + Read more about it in the + [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). + """ + ), + ] = None, + summary: Annotated[ + Optional[str], + Doc( + """ + A summary for the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + A description for the *path operation*. + + If not provided, it will be extracted automatically from the docstring + of the *path operation function*. + + It can contain Markdown. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + response_description: Annotated[ + str, + Doc( + """ + The description for the default response. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = "Successful Response", + responses: Annotated[ + Optional[Dict[Union[int, str], Dict[str, Any]]], + Doc( + """ + Additional responses that could be returned by this *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + deprecated: Annotated[ + Optional[bool], + Doc( + """ + Mark this *path operation* as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + operation_id: Annotated[ + Optional[str], + Doc( + """ + Custom operation ID to be used by this *path operation*. + + By default, it is generated automatically. + + If you provide a custom operation ID, you need to make sure it is + unique for the whole API. + + You can customize the + operation ID generation with the parameter + `generate_unique_id_function` in the `FastAPI` class. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = None, + response_model_include: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to include only certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_exclude: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to exclude certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_by_alias: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response model + should be serialized by alias when an alias is used. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = True, + response_model_exclude_unset: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that were not set and + have their default values. This is different from + `response_model_exclude_defaults` in that if the fields are set, + they will be included in the response, even if the value is the same + as the default. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_defaults: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that have the same value + as the default. This is different from `response_model_exclude_unset` + in that if the fields are set but contain the same default values, + they will be excluded from the response. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_none: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data should + exclude fields set to `None`. + + This is much simpler (less smart) than `response_model_exclude_unset` + and `response_model_exclude_defaults`. You probably want to use one of + those two instead of this one, as those allow returning `None` values + when it makes sense. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). + """ + ), + ] = False, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include this *path operation* in the generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi). + """ + ), + ] = True, + response_class: Annotated[ + Type[Response], + Doc( + """ + Response class to be used for this *path operation*. + + This will not be used if you return a response directly. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). + """ + ), + ] = Default(JSONResponse), + name: Annotated[ + Optional[str], + Doc( + """ + Name for this *path operation*. Only used internally. + """ + ), + ] = None, + callbacks: Annotated[ + Optional[List[BaseRoute]], + Doc( + """ + List of *path operations* that will be used as OpenAPI callbacks. + + This is only for OpenAPI documentation, the callbacks won't be used + directly. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + openapi_extra: Annotated[ + Optional[Dict[str, Any]], + Doc( + """ + Extra metadata to be included in the OpenAPI schema for this *path + operation*. + + Read more about it in the + [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[routing.APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP POST operation. + + ## Example + + ```python + from fastapi import FastAPI + from pydantic import BaseModel + + class Item(BaseModel): + name: str + description: str | None = None + + app = FastAPI() + + @app.post("/items/") + def create_item(item: Item): + return {"message": "Item created"} + ``` + """ return self.router.post( path, response_model=response_model, @@ -631,33 +2588,351 @@ def post( def delete( self, - path: str, + path: Annotated[ + str, + Doc( + """ + The URL path to be used for this *path operation*. + + For example, in `http://example.com/items`, the path is `/items`. + """ + ), + ], *, - response_model: Any = Default(None), - status_code: Optional[int] = None, - tags: Optional[List[Union[str, Enum]]] = None, - dependencies: Optional[Sequence[Depends]] = None, - summary: Optional[str] = None, - description: Optional[str] = None, - response_description: str = "Successful Response", - responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, - deprecated: Optional[bool] = None, - operation_id: Optional[str] = None, - response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, - response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, - response_model_by_alias: bool = True, - response_model_exclude_unset: bool = False, - response_model_exclude_defaults: bool = False, - response_model_exclude_none: bool = False, - include_in_schema: bool = True, - response_class: Type[Response] = Default(JSONResponse), - name: Optional[str] = None, - callbacks: Optional[List[BaseRoute]] = None, - openapi_extra: Optional[Dict[str, Any]] = None, - generate_unique_id_function: Callable[[routing.APIRoute], str] = Default( - generate_unique_id - ), + response_model: Annotated[ + Any, + Doc( + """ + The type to use for the response. + + It could be any valid Pydantic *field* type. So, it doesn't have to + be a Pydantic model, it could be other things, like a `list`, `dict`, + etc. + + It will be used for: + + * Documentation: the generated OpenAPI (and the UI at `/docs`) will + show it as the response (JSON Schema). + * Serialization: you could return an arbitrary object and the + `response_model` would be used to serialize that object into the + corresponding JSON. + * Filtering: the JSON sent to the client will only contain the data + (fields) defined in the `response_model`. If you returned an object + that contains an attribute `password` but the `response_model` does + not include that field, the JSON sent to the client would not have + that `password`. + * Validation: whatever you return will be serialized with the + `response_model`, converting any data as necessary to generate the + corresponding JSON. But if the data in the object returned is not + valid, that would mean a violation of the contract with the client, + so it's an error from the API developer. So, FastAPI will raise an + error and return a 500 error code (Internal Server Error). + + Read more about it in the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + """ + ), + ] = Default(None), + status_code: Annotated[ + Optional[int], + Doc( + """ + The default status code to be used for the response. + + You could override the status code by returning a response directly. + + Read more about it in the + [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). + """ + ), + ] = None, + tags: Annotated[ + Optional[List[Union[str, Enum]]], + Doc( + """ + A list of tags to be applied to the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). + """ + ), + ] = None, + dependencies: Annotated[ + Optional[Sequence[Depends]], + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to the + *path operation*. + + Read more about it in the + [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). + """ + ), + ] = None, + summary: Annotated[ + Optional[str], + Doc( + """ + A summary for the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + A description for the *path operation*. + + If not provided, it will be extracted automatically from the docstring + of the *path operation function*. + + It can contain Markdown. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + response_description: Annotated[ + str, + Doc( + """ + The description for the default response. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = "Successful Response", + responses: Annotated[ + Optional[Dict[Union[int, str], Dict[str, Any]]], + Doc( + """ + Additional responses that could be returned by this *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + deprecated: Annotated[ + Optional[bool], + Doc( + """ + Mark this *path operation* as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + operation_id: Annotated[ + Optional[str], + Doc( + """ + Custom operation ID to be used by this *path operation*. + + By default, it is generated automatically. + + If you provide a custom operation ID, you need to make sure it is + unique for the whole API. + + You can customize the + operation ID generation with the parameter + `generate_unique_id_function` in the `FastAPI` class. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = None, + response_model_include: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to include only certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_exclude: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to exclude certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_by_alias: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response model + should be serialized by alias when an alias is used. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = True, + response_model_exclude_unset: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that were not set and + have their default values. This is different from + `response_model_exclude_defaults` in that if the fields are set, + they will be included in the response, even if the value is the same + as the default. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_defaults: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that have the same value + as the default. This is different from `response_model_exclude_unset` + in that if the fields are set but contain the same default values, + they will be excluded from the response. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_none: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data should + exclude fields set to `None`. + + This is much simpler (less smart) than `response_model_exclude_unset` + and `response_model_exclude_defaults`. You probably want to use one of + those two instead of this one, as those allow returning `None` values + when it makes sense. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). + """ + ), + ] = False, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include this *path operation* in the generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi). + """ + ), + ] = True, + response_class: Annotated[ + Type[Response], + Doc( + """ + Response class to be used for this *path operation*. + + This will not be used if you return a response directly. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). + """ + ), + ] = Default(JSONResponse), + name: Annotated[ + Optional[str], + Doc( + """ + Name for this *path operation*. Only used internally. + """ + ), + ] = None, + callbacks: Annotated[ + Optional[List[BaseRoute]], + Doc( + """ + List of *path operations* that will be used as OpenAPI callbacks. + + This is only for OpenAPI documentation, the callbacks won't be used + directly. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + openapi_extra: Annotated[ + Optional[Dict[str, Any]], + Doc( + """ + Extra metadata to be included in the OpenAPI schema for this *path + operation*. + + Read more about it in the + [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[routing.APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP DELETE operation. + + ## Example + + ```python + from fastapi import FastAPI + + app = FastAPI() + + @app.delete("/items/{item_id}") + def delete_item(item_id: str): + return {"message": "Item deleted"} + ``` + """ return self.router.delete( path, response_model=response_model, @@ -686,33 +2961,351 @@ def delete( def options( self, - path: str, + path: Annotated[ + str, + Doc( + """ + The URL path to be used for this *path operation*. + + For example, in `http://example.com/items`, the path is `/items`. + """ + ), + ], *, - response_model: Any = Default(None), - status_code: Optional[int] = None, - tags: Optional[List[Union[str, Enum]]] = None, - dependencies: Optional[Sequence[Depends]] = None, - summary: Optional[str] = None, - description: Optional[str] = None, - response_description: str = "Successful Response", - responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, - deprecated: Optional[bool] = None, - operation_id: Optional[str] = None, - response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, - response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, - response_model_by_alias: bool = True, - response_model_exclude_unset: bool = False, - response_model_exclude_defaults: bool = False, - response_model_exclude_none: bool = False, - include_in_schema: bool = True, - response_class: Type[Response] = Default(JSONResponse), - name: Optional[str] = None, - callbacks: Optional[List[BaseRoute]] = None, - openapi_extra: Optional[Dict[str, Any]] = None, - generate_unique_id_function: Callable[[routing.APIRoute], str] = Default( - generate_unique_id - ), + response_model: Annotated[ + Any, + Doc( + """ + The type to use for the response. + + It could be any valid Pydantic *field* type. So, it doesn't have to + be a Pydantic model, it could be other things, like a `list`, `dict`, + etc. + + It will be used for: + + * Documentation: the generated OpenAPI (and the UI at `/docs`) will + show it as the response (JSON Schema). + * Serialization: you could return an arbitrary object and the + `response_model` would be used to serialize that object into the + corresponding JSON. + * Filtering: the JSON sent to the client will only contain the data + (fields) defined in the `response_model`. If you returned an object + that contains an attribute `password` but the `response_model` does + not include that field, the JSON sent to the client would not have + that `password`. + * Validation: whatever you return will be serialized with the + `response_model`, converting any data as necessary to generate the + corresponding JSON. But if the data in the object returned is not + valid, that would mean a violation of the contract with the client, + so it's an error from the API developer. So, FastAPI will raise an + error and return a 500 error code (Internal Server Error). + + Read more about it in the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + """ + ), + ] = Default(None), + status_code: Annotated[ + Optional[int], + Doc( + """ + The default status code to be used for the response. + + You could override the status code by returning a response directly. + + Read more about it in the + [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). + """ + ), + ] = None, + tags: Annotated[ + Optional[List[Union[str, Enum]]], + Doc( + """ + A list of tags to be applied to the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). + """ + ), + ] = None, + dependencies: Annotated[ + Optional[Sequence[Depends]], + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to the + *path operation*. + + Read more about it in the + [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). + """ + ), + ] = None, + summary: Annotated[ + Optional[str], + Doc( + """ + A summary for the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + A description for the *path operation*. + + If not provided, it will be extracted automatically from the docstring + of the *path operation function*. + + It can contain Markdown. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + response_description: Annotated[ + str, + Doc( + """ + The description for the default response. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = "Successful Response", + responses: Annotated[ + Optional[Dict[Union[int, str], Dict[str, Any]]], + Doc( + """ + Additional responses that could be returned by this *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + deprecated: Annotated[ + Optional[bool], + Doc( + """ + Mark this *path operation* as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + operation_id: Annotated[ + Optional[str], + Doc( + """ + Custom operation ID to be used by this *path operation*. + + By default, it is generated automatically. + + If you provide a custom operation ID, you need to make sure it is + unique for the whole API. + + You can customize the + operation ID generation with the parameter + `generate_unique_id_function` in the `FastAPI` class. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = None, + response_model_include: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to include only certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_exclude: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to exclude certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_by_alias: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response model + should be serialized by alias when an alias is used. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = True, + response_model_exclude_unset: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that were not set and + have their default values. This is different from + `response_model_exclude_defaults` in that if the fields are set, + they will be included in the response, even if the value is the same + as the default. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_defaults: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that have the same value + as the default. This is different from `response_model_exclude_unset` + in that if the fields are set but contain the same default values, + they will be excluded from the response. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_none: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data should + exclude fields set to `None`. + + This is much simpler (less smart) than `response_model_exclude_unset` + and `response_model_exclude_defaults`. You probably want to use one of + those two instead of this one, as those allow returning `None` values + when it makes sense. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). + """ + ), + ] = False, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include this *path operation* in the generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi). + """ + ), + ] = True, + response_class: Annotated[ + Type[Response], + Doc( + """ + Response class to be used for this *path operation*. + + This will not be used if you return a response directly. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). + """ + ), + ] = Default(JSONResponse), + name: Annotated[ + Optional[str], + Doc( + """ + Name for this *path operation*. Only used internally. + """ + ), + ] = None, + callbacks: Annotated[ + Optional[List[BaseRoute]], + Doc( + """ + List of *path operations* that will be used as OpenAPI callbacks. + + This is only for OpenAPI documentation, the callbacks won't be used + directly. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + openapi_extra: Annotated[ + Optional[Dict[str, Any]], + Doc( + """ + Extra metadata to be included in the OpenAPI schema for this *path + operation*. + + Read more about it in the + [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[routing.APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP OPTIONS operation. + + ## Example + + ```python + from fastapi import FastAPI + + app = FastAPI() + + @app.options("/items/") + def get_item_options(): + return {"additions": ["Aji", "Guacamole"]} + ``` + """ return self.router.options( path, response_model=response_model, @@ -739,35 +3332,353 @@ def options( generate_unique_id_function=generate_unique_id_function, ) - def head( - self, - path: str, - *, - response_model: Any = Default(None), - status_code: Optional[int] = None, - tags: Optional[List[Union[str, Enum]]] = None, - dependencies: Optional[Sequence[Depends]] = None, - summary: Optional[str] = None, - description: Optional[str] = None, - response_description: str = "Successful Response", - responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, - deprecated: Optional[bool] = None, - operation_id: Optional[str] = None, - response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, - response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, - response_model_by_alias: bool = True, - response_model_exclude_unset: bool = False, - response_model_exclude_defaults: bool = False, - response_model_exclude_none: bool = False, - include_in_schema: bool = True, - response_class: Type[Response] = Default(JSONResponse), - name: Optional[str] = None, - callbacks: Optional[List[BaseRoute]] = None, - openapi_extra: Optional[Dict[str, Any]] = None, - generate_unique_id_function: Callable[[routing.APIRoute], str] = Default( - generate_unique_id - ), + def head( + self, + path: Annotated[ + str, + Doc( + """ + The URL path to be used for this *path operation*. + + For example, in `http://example.com/items`, the path is `/items`. + """ + ), + ], + *, + response_model: Annotated[ + Any, + Doc( + """ + The type to use for the response. + + It could be any valid Pydantic *field* type. So, it doesn't have to + be a Pydantic model, it could be other things, like a `list`, `dict`, + etc. + + It will be used for: + + * Documentation: the generated OpenAPI (and the UI at `/docs`) will + show it as the response (JSON Schema). + * Serialization: you could return an arbitrary object and the + `response_model` would be used to serialize that object into the + corresponding JSON. + * Filtering: the JSON sent to the client will only contain the data + (fields) defined in the `response_model`. If you returned an object + that contains an attribute `password` but the `response_model` does + not include that field, the JSON sent to the client would not have + that `password`. + * Validation: whatever you return will be serialized with the + `response_model`, converting any data as necessary to generate the + corresponding JSON. But if the data in the object returned is not + valid, that would mean a violation of the contract with the client, + so it's an error from the API developer. So, FastAPI will raise an + error and return a 500 error code (Internal Server Error). + + Read more about it in the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + """ + ), + ] = Default(None), + status_code: Annotated[ + Optional[int], + Doc( + """ + The default status code to be used for the response. + + You could override the status code by returning a response directly. + + Read more about it in the + [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). + """ + ), + ] = None, + tags: Annotated[ + Optional[List[Union[str, Enum]]], + Doc( + """ + A list of tags to be applied to the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). + """ + ), + ] = None, + dependencies: Annotated[ + Optional[Sequence[Depends]], + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to the + *path operation*. + + Read more about it in the + [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). + """ + ), + ] = None, + summary: Annotated[ + Optional[str], + Doc( + """ + A summary for the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + A description for the *path operation*. + + If not provided, it will be extracted automatically from the docstring + of the *path operation function*. + + It can contain Markdown. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + response_description: Annotated[ + str, + Doc( + """ + The description for the default response. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = "Successful Response", + responses: Annotated[ + Optional[Dict[Union[int, str], Dict[str, Any]]], + Doc( + """ + Additional responses that could be returned by this *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + deprecated: Annotated[ + Optional[bool], + Doc( + """ + Mark this *path operation* as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + operation_id: Annotated[ + Optional[str], + Doc( + """ + Custom operation ID to be used by this *path operation*. + + By default, it is generated automatically. + + If you provide a custom operation ID, you need to make sure it is + unique for the whole API. + + You can customize the + operation ID generation with the parameter + `generate_unique_id_function` in the `FastAPI` class. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = None, + response_model_include: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to include only certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_exclude: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to exclude certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_by_alias: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response model + should be serialized by alias when an alias is used. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = True, + response_model_exclude_unset: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that were not set and + have their default values. This is different from + `response_model_exclude_defaults` in that if the fields are set, + they will be included in the response, even if the value is the same + as the default. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_defaults: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that have the same value + as the default. This is different from `response_model_exclude_unset` + in that if the fields are set but contain the same default values, + they will be excluded from the response. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_none: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data should + exclude fields set to `None`. + + This is much simpler (less smart) than `response_model_exclude_unset` + and `response_model_exclude_defaults`. You probably want to use one of + those two instead of this one, as those allow returning `None` values + when it makes sense. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). + """ + ), + ] = False, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include this *path operation* in the generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi). + """ + ), + ] = True, + response_class: Annotated[ + Type[Response], + Doc( + """ + Response class to be used for this *path operation*. + + This will not be used if you return a response directly. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). + """ + ), + ] = Default(JSONResponse), + name: Annotated[ + Optional[str], + Doc( + """ + Name for this *path operation*. Only used internally. + """ + ), + ] = None, + callbacks: Annotated[ + Optional[List[BaseRoute]], + Doc( + """ + List of *path operations* that will be used as OpenAPI callbacks. + + This is only for OpenAPI documentation, the callbacks won't be used + directly. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + openapi_extra: Annotated[ + Optional[Dict[str, Any]], + Doc( + """ + Extra metadata to be included in the OpenAPI schema for this *path + operation*. + + Read more about it in the + [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[routing.APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP HEAD operation. + + ## Example + + ```python + from fastapi import FastAPI, Response + + app = FastAPI() + + @app.head("/items/", status_code=204) + def get_items_headers(response: Response): + response.headers["X-Cat-Dog"] = "Alone in the world" + ``` + """ return self.router.head( path, response_model=response_model, @@ -796,33 +3707,356 @@ def head( def patch( self, - path: str, + path: Annotated[ + str, + Doc( + """ + The URL path to be used for this *path operation*. + + For example, in `http://example.com/items`, the path is `/items`. + """ + ), + ], *, - response_model: Any = Default(None), - status_code: Optional[int] = None, - tags: Optional[List[Union[str, Enum]]] = None, - dependencies: Optional[Sequence[Depends]] = None, - summary: Optional[str] = None, - description: Optional[str] = None, - response_description: str = "Successful Response", - responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, - deprecated: Optional[bool] = None, - operation_id: Optional[str] = None, - response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, - response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, - response_model_by_alias: bool = True, - response_model_exclude_unset: bool = False, - response_model_exclude_defaults: bool = False, - response_model_exclude_none: bool = False, - include_in_schema: bool = True, - response_class: Type[Response] = Default(JSONResponse), - name: Optional[str] = None, - callbacks: Optional[List[BaseRoute]] = None, - openapi_extra: Optional[Dict[str, Any]] = None, - generate_unique_id_function: Callable[[routing.APIRoute], str] = Default( - generate_unique_id - ), + response_model: Annotated[ + Any, + Doc( + """ + The type to use for the response. + + It could be any valid Pydantic *field* type. So, it doesn't have to + be a Pydantic model, it could be other things, like a `list`, `dict`, + etc. + + It will be used for: + + * Documentation: the generated OpenAPI (and the UI at `/docs`) will + show it as the response (JSON Schema). + * Serialization: you could return an arbitrary object and the + `response_model` would be used to serialize that object into the + corresponding JSON. + * Filtering: the JSON sent to the client will only contain the data + (fields) defined in the `response_model`. If you returned an object + that contains an attribute `password` but the `response_model` does + not include that field, the JSON sent to the client would not have + that `password`. + * Validation: whatever you return will be serialized with the + `response_model`, converting any data as necessary to generate the + corresponding JSON. But if the data in the object returned is not + valid, that would mean a violation of the contract with the client, + so it's an error from the API developer. So, FastAPI will raise an + error and return a 500 error code (Internal Server Error). + + Read more about it in the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + """ + ), + ] = Default(None), + status_code: Annotated[ + Optional[int], + Doc( + """ + The default status code to be used for the response. + + You could override the status code by returning a response directly. + + Read more about it in the + [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). + """ + ), + ] = None, + tags: Annotated[ + Optional[List[Union[str, Enum]]], + Doc( + """ + A list of tags to be applied to the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). + """ + ), + ] = None, + dependencies: Annotated[ + Optional[Sequence[Depends]], + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to the + *path operation*. + + Read more about it in the + [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). + """ + ), + ] = None, + summary: Annotated[ + Optional[str], + Doc( + """ + A summary for the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + A description for the *path operation*. + + If not provided, it will be extracted automatically from the docstring + of the *path operation function*. + + It can contain Markdown. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + response_description: Annotated[ + str, + Doc( + """ + The description for the default response. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = "Successful Response", + responses: Annotated[ + Optional[Dict[Union[int, str], Dict[str, Any]]], + Doc( + """ + Additional responses that could be returned by this *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + deprecated: Annotated[ + Optional[bool], + Doc( + """ + Mark this *path operation* as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + operation_id: Annotated[ + Optional[str], + Doc( + """ + Custom operation ID to be used by this *path operation*. + + By default, it is generated automatically. + + If you provide a custom operation ID, you need to make sure it is + unique for the whole API. + + You can customize the + operation ID generation with the parameter + `generate_unique_id_function` in the `FastAPI` class. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = None, + response_model_include: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to include only certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_exclude: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to exclude certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_by_alias: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response model + should be serialized by alias when an alias is used. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = True, + response_model_exclude_unset: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that were not set and + have their default values. This is different from + `response_model_exclude_defaults` in that if the fields are set, + they will be included in the response, even if the value is the same + as the default. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_defaults: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that have the same value + as the default. This is different from `response_model_exclude_unset` + in that if the fields are set but contain the same default values, + they will be excluded from the response. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_none: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data should + exclude fields set to `None`. + + This is much simpler (less smart) than `response_model_exclude_unset` + and `response_model_exclude_defaults`. You probably want to use one of + those two instead of this one, as those allow returning `None` values + when it makes sense. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). + """ + ), + ] = False, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include this *path operation* in the generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi). + """ + ), + ] = True, + response_class: Annotated[ + Type[Response], + Doc( + """ + Response class to be used for this *path operation*. + + This will not be used if you return a response directly. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). + """ + ), + ] = Default(JSONResponse), + name: Annotated[ + Optional[str], + Doc( + """ + Name for this *path operation*. Only used internally. + """ + ), + ] = None, + callbacks: Annotated[ + Optional[List[BaseRoute]], + Doc( + """ + List of *path operations* that will be used as OpenAPI callbacks. + + This is only for OpenAPI documentation, the callbacks won't be used + directly. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + openapi_extra: Annotated[ + Optional[Dict[str, Any]], + Doc( + """ + Extra metadata to be included in the OpenAPI schema for this *path + operation*. + + Read more about it in the + [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[routing.APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP PATCH operation. + + ## Example + + ```python + from fastapi import FastAPI + from pydantic import BaseModel + + class Item(BaseModel): + name: str + description: str | None = None + + app = FastAPI() + + @app.patch("/items/") + def update_item(item: Item): + return {"message": "Item updated in place"} + ``` + """ return self.router.patch( path, response_model=response_model, @@ -851,33 +4085,351 @@ def patch( def trace( self, - path: str, + path: Annotated[ + str, + Doc( + """ + The URL path to be used for this *path operation*. + + For example, in `http://example.com/items`, the path is `/items`. + """ + ), + ], *, - response_model: Any = Default(None), - status_code: Optional[int] = None, - tags: Optional[List[Union[str, Enum]]] = None, - dependencies: Optional[Sequence[Depends]] = None, - summary: Optional[str] = None, - description: Optional[str] = None, - response_description: str = "Successful Response", - responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, - deprecated: Optional[bool] = None, - operation_id: Optional[str] = None, - response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, - response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, - response_model_by_alias: bool = True, - response_model_exclude_unset: bool = False, - response_model_exclude_defaults: bool = False, - response_model_exclude_none: bool = False, - include_in_schema: bool = True, - response_class: Type[Response] = Default(JSONResponse), - name: Optional[str] = None, - callbacks: Optional[List[BaseRoute]] = None, - openapi_extra: Optional[Dict[str, Any]] = None, - generate_unique_id_function: Callable[[routing.APIRoute], str] = Default( - generate_unique_id - ), + response_model: Annotated[ + Any, + Doc( + """ + The type to use for the response. + + It could be any valid Pydantic *field* type. So, it doesn't have to + be a Pydantic model, it could be other things, like a `list`, `dict`, + etc. + + It will be used for: + + * Documentation: the generated OpenAPI (and the UI at `/docs`) will + show it as the response (JSON Schema). + * Serialization: you could return an arbitrary object and the + `response_model` would be used to serialize that object into the + corresponding JSON. + * Filtering: the JSON sent to the client will only contain the data + (fields) defined in the `response_model`. If you returned an object + that contains an attribute `password` but the `response_model` does + not include that field, the JSON sent to the client would not have + that `password`. + * Validation: whatever you return will be serialized with the + `response_model`, converting any data as necessary to generate the + corresponding JSON. But if the data in the object returned is not + valid, that would mean a violation of the contract with the client, + so it's an error from the API developer. So, FastAPI will raise an + error and return a 500 error code (Internal Server Error). + + Read more about it in the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + """ + ), + ] = Default(None), + status_code: Annotated[ + Optional[int], + Doc( + """ + The default status code to be used for the response. + + You could override the status code by returning a response directly. + + Read more about it in the + [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). + """ + ), + ] = None, + tags: Annotated[ + Optional[List[Union[str, Enum]]], + Doc( + """ + A list of tags to be applied to the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). + """ + ), + ] = None, + dependencies: Annotated[ + Optional[Sequence[Depends]], + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to the + *path operation*. + + Read more about it in the + [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). + """ + ), + ] = None, + summary: Annotated[ + Optional[str], + Doc( + """ + A summary for the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + A description for the *path operation*. + + If not provided, it will be extracted automatically from the docstring + of the *path operation function*. + + It can contain Markdown. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + response_description: Annotated[ + str, + Doc( + """ + The description for the default response. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = "Successful Response", + responses: Annotated[ + Optional[Dict[Union[int, str], Dict[str, Any]]], + Doc( + """ + Additional responses that could be returned by this *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + deprecated: Annotated[ + Optional[bool], + Doc( + """ + Mark this *path operation* as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + operation_id: Annotated[ + Optional[str], + Doc( + """ + Custom operation ID to be used by this *path operation*. + + By default, it is generated automatically. + + If you provide a custom operation ID, you need to make sure it is + unique for the whole API. + + You can customize the + operation ID generation with the parameter + `generate_unique_id_function` in the `FastAPI` class. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = None, + response_model_include: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to include only certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_exclude: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to exclude certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_by_alias: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response model + should be serialized by alias when an alias is used. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = True, + response_model_exclude_unset: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that were not set and + have their default values. This is different from + `response_model_exclude_defaults` in that if the fields are set, + they will be included in the response, even if the value is the same + as the default. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_defaults: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that have the same value + as the default. This is different from `response_model_exclude_unset` + in that if the fields are set but contain the same default values, + they will be excluded from the response. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_none: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data should + exclude fields set to `None`. + + This is much simpler (less smart) than `response_model_exclude_unset` + and `response_model_exclude_defaults`. You probably want to use one of + those two instead of this one, as those allow returning `None` values + when it makes sense. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). + """ + ), + ] = False, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include this *path operation* in the generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi). + """ + ), + ] = True, + response_class: Annotated[ + Type[Response], + Doc( + """ + Response class to be used for this *path operation*. + + This will not be used if you return a response directly. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). + """ + ), + ] = Default(JSONResponse), + name: Annotated[ + Optional[str], + Doc( + """ + Name for this *path operation*. Only used internally. + """ + ), + ] = None, + callbacks: Annotated[ + Optional[List[BaseRoute]], + Doc( + """ + List of *path operations* that will be used as OpenAPI callbacks. + + This is only for OpenAPI documentation, the callbacks won't be used + directly. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + openapi_extra: Annotated[ + Optional[Dict[str, Any]], + Doc( + """ + Extra metadata to be included in the OpenAPI schema for this *path + operation*. + + Read more about it in the + [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[routing.APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP TRACE operation. + + ## Example + + ```python + from fastapi import FastAPI + + app = FastAPI() + + @app.put("/items/{item_id}") + def trace_item(item_id: str): + return None + ``` + """ return self.router.trace( path, response_model=response_model, @@ -913,14 +4465,72 @@ def decorator(func: DecoratedCallable) -> DecoratedCallable: return decorator + @deprecated( + """ + on_event is deprecated, use lifespan event handlers instead. + + Read more about it in the + [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). + """ + ) def on_event( - self, event_type: str + self, + event_type: Annotated[ + str, + Doc( + """ + The type of event. `startup` or `shutdown`. + """ + ), + ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add an event handler for the application. + + `on_event` is deprecated, use `lifespan` event handlers instead. + + Read more about it in the + [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). + """ return self.router.on_event(event_type) def middleware( - self, middleware_type: str + self, + middleware_type: Annotated[ + str, + Doc( + """ + The type of middleware. Currently only supports `http`. + """ + ), + ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a middleware to the application. + + Read more about it in the + [FastAPI docs for Middleware](https://fastapi.tiangolo.com/tutorial/middleware/). + + ## Example + + ```python + import time + + from fastapi import FastAPI, Request + + app = FastAPI() + + + @app.middleware("http") + async def add_process_time_header(request: Request, call_next): + start_time = time.time() + response = await call_next(request) + process_time = time.time() - start_time + response.headers["X-Process-Time"] = str(process_time) + return response + ``` + """ + def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_middleware(BaseHTTPMiddleware, dispatch=func) return func @@ -928,8 +4538,46 @@ def decorator(func: DecoratedCallable) -> DecoratedCallable: return decorator def exception_handler( - self, exc_class_or_status_code: Union[int, Type[Exception]] + self, + exc_class_or_status_code: Annotated[ + Union[int, Type[Exception]], + Doc( + """ + The Exception class this would handle, or a status code. + """ + ), + ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add an exception handler to the app. + + Read more about it in the + [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/). + + ## Example + + ```python + from fastapi import FastAPI, Request + from fastapi.responses import JSONResponse + + + class UnicornException(Exception): + def __init__(self, name: str): + self.name = name + + + app = FastAPI() + + + @app.exception_handler(UnicornException) + async def unicorn_exception_handler(request: Request, exc: UnicornException): + return JSONResponse( + status_code=418, + content={"message": f"Oops! {exc.name} did something. There goes a rainbow..."}, + ) + ``` + """ + def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_exception_handler(exc_class_or_status_code, func) return func diff --git a/fastapi/background.py b/fastapi/background.py index dd3bbe2491303..35ab1b227021f 100644 --- a/fastapi/background.py +++ b/fastapi/background.py @@ -1 +1,59 @@ -from starlette.background import BackgroundTasks as BackgroundTasks # noqa +from typing import Any, Callable + +from starlette.background import BackgroundTasks as StarletteBackgroundTasks +from typing_extensions import Annotated, Doc, ParamSpec # type: ignore [attr-defined] + +P = ParamSpec("P") + + +class BackgroundTasks(StarletteBackgroundTasks): + """ + A collection of background tasks that will be called after a response has been + sent to the client. + + Read more about it in the + [FastAPI docs for Background Tasks](https://fastapi.tiangolo.com/tutorial/background-tasks/). + + ## Example + + ```python + from fastapi import BackgroundTasks, FastAPI + + app = FastAPI() + + + def write_notification(email: str, message=""): + with open("log.txt", mode="w") as email_file: + content = f"notification for {email}: {message}" + email_file.write(content) + + + @app.post("/send-notification/{email}") + async def send_notification(email: str, background_tasks: BackgroundTasks): + background_tasks.add_task(write_notification, email, message="some notification") + return {"message": "Notification sent in the background"} + ``` + """ + + def add_task( + self, + func: Annotated[ + Callable[P, Any], + Doc( + """ + The function to call after the response is sent. + + It can be a regular `def` function or an `async def` function. + """ + ), + ], + *args: P.args, + **kwargs: P.kwargs, + ) -> None: + """ + Add a function to be called in the background after the response is sent. + + Read more about it in the + [FastAPI docs for Background Tasks](https://fastapi.tiangolo.com/tutorial/background-tasks/). + """ + return super().add_task(func, *args, **kwargs) diff --git a/fastapi/concurrency.py b/fastapi/concurrency.py index 31b878d5df8a5..894bd3ed11873 100644 --- a/fastapi/concurrency.py +++ b/fastapi/concurrency.py @@ -1,4 +1,3 @@ -from contextlib import AsyncExitStack as AsyncExitStack # noqa from contextlib import asynccontextmanager as asynccontextmanager from typing import AsyncGenerator, ContextManager, TypeVar @@ -19,7 +18,7 @@ async def contextmanager_in_threadpool( ) -> AsyncGenerator[_T, None]: # blocking __exit__ from running waiting on a free thread # can create race conditions/deadlocks if the context manager itself - # has it's own internal pool (e.g. a database connection pool) + # has its own internal pool (e.g. a database connection pool) # to avoid this we let __exit__ run without a capacity limit # since we're creating a new limiter for each call, any non-zero limit # works (1 is arbitrary) diff --git a/fastapi/datastructures.py b/fastapi/datastructures.py index b20a25ab6ed09..ce03e3ce4747a 100644 --- a/fastapi/datastructures.py +++ b/fastapi/datastructures.py @@ -1,5 +1,22 @@ -from typing import Any, Callable, Dict, Iterable, Type, TypeVar - +from typing import ( + Any, + BinaryIO, + Callable, + Dict, + Iterable, + Optional, + Type, + TypeVar, + cast, +) + +from fastapi._compat import ( + PYDANTIC_V2, + CoreSchema, + GetJsonSchemaHandler, + JsonSchemaValue, + with_info_plain_validator_function, +) from starlette.datastructures import URL as URL # noqa: F401 from starlette.datastructures import Address as Address # noqa: F401 from starlette.datastructures import FormData as FormData # noqa: F401 @@ -7,9 +24,120 @@ from starlette.datastructures import QueryParams as QueryParams # noqa: F401 from starlette.datastructures import State as State # noqa: F401 from starlette.datastructures import UploadFile as StarletteUploadFile +from typing_extensions import Annotated, Doc # type: ignore [attr-defined] class UploadFile(StarletteUploadFile): + """ + A file uploaded in a request. + + Define it as a *path operation function* (or dependency) parameter. + + If you are using a regular `def` function, you can use the `upload_file.file` + attribute to access the raw standard Python file (blocking, not async), useful and + needed for non-async code. + + Read more about it in the + [FastAPI docs for Request Files](https://fastapi.tiangolo.com/tutorial/request-files/). + + ## Example + + ```python + from typing import Annotated + + from fastapi import FastAPI, File, UploadFile + + app = FastAPI() + + + @app.post("/files/") + async def create_file(file: Annotated[bytes, File()]): + return {"file_size": len(file)} + + + @app.post("/uploadfile/") + async def create_upload_file(file: UploadFile): + return {"filename": file.filename} + ``` + """ + + file: Annotated[ + BinaryIO, + Doc("The standard Python file object (non-async)."), + ] + filename: Annotated[Optional[str], Doc("The original file name.")] + size: Annotated[Optional[int], Doc("The size of the file in bytes.")] + headers: Annotated[Headers, Doc("The headers of the request.")] + content_type: Annotated[ + Optional[str], Doc("The content type of the request, from the headers.") + ] + + async def write( + self, + data: Annotated[ + bytes, + Doc( + """ + The bytes to write to the file. + """ + ), + ], + ) -> None: + """ + Write some bytes to the file. + + You normally wouldn't use this from a file you read in a request. + + To be awaitable, compatible with async, this is run in threadpool. + """ + return await super().write(data) + + async def read( + self, + size: Annotated[ + int, + Doc( + """ + The number of bytes to read from the file. + """ + ), + ] = -1, + ) -> bytes: + """ + Read some bytes from the file. + + To be awaitable, compatible with async, this is run in threadpool. + """ + return await super().read(size) + + async def seek( + self, + offset: Annotated[ + int, + Doc( + """ + The position in bytes to seek to in the file. + """ + ), + ], + ) -> None: + """ + Move to a position in the file. + + Any next read or write will be done from that position. + + To be awaitable, compatible with async, this is run in threadpool. + """ + return await super().seek(offset) + + async def close(self) -> None: + """ + Close the file. + + To be awaitable, compatible with async, this is run in threadpool. + """ + return await super().close() + @classmethod def __get_validators__(cls: Type["UploadFile"]) -> Iterable[Callable[..., Any]]: yield cls.validate @@ -21,8 +149,28 @@ def validate(cls: Type["UploadFile"], v: Any) -> Any: return v @classmethod - def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None: - field_schema.update({"type": "string", "format": "binary"}) + def _validate(cls, __input_value: Any, _: Any) -> "UploadFile": + if not isinstance(__input_value, StarletteUploadFile): + raise ValueError(f"Expected UploadFile, received: {type(__input_value)}") + return cast(UploadFile, __input_value) + + if not PYDANTIC_V2: + + @classmethod + def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None: + field_schema.update({"type": "string", "format": "binary"}) + + @classmethod + def __get_pydantic_json_schema__( + cls, core_schema: CoreSchema, handler: GetJsonSchemaHandler + ) -> JsonSchemaValue: + return {"type": "string", "format": "binary"} + + @classmethod + def __get_pydantic_core_schema__( + cls, source: Type[Any], handler: Callable[[Any], CoreSchema] + ) -> CoreSchema: + return with_info_plain_validator_function(cls._validate) class DefaultPlaceholder: diff --git a/fastapi/dependencies/models.py b/fastapi/dependencies/models.py index 443590b9c82b7..61ef006387781 100644 --- a/fastapi/dependencies/models.py +++ b/fastapi/dependencies/models.py @@ -1,7 +1,7 @@ from typing import Any, Callable, List, Optional, Sequence +from fastapi._compat import ModelField from fastapi.security.base import SecurityBase -from pydantic.fields import ModelField class SecurityRequirement: diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index f131001ce2c9f..02284b4ed001b 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -1,7 +1,6 @@ -import dataclasses import inspect -from contextlib import contextmanager -from copy import copy, deepcopy +from contextlib import AsyncExitStack, contextmanager +from copy import deepcopy from typing import ( Any, Callable, @@ -20,8 +19,33 @@ import anyio from fastapi import params +from fastapi._compat import ( + PYDANTIC_V2, + ErrorWrapper, + ModelField, + Required, + Undefined, + _regenerate_error_with_loc, + copy_field_info, + create_body_model, + evaluate_forwardref, + field_annotation_is_scalar, + get_annotation_from_field_info, + get_missing_field_error, + is_bytes_field, + is_bytes_sequence_field, + is_scalar_field, + is_scalar_sequence_field, + is_sequence_field, + is_uploadfile_or_nonable_uploadfile_annotation, + is_uploadfile_sequence_annotation, + lenient_issubclass, + sequence_types, + serialize_sequence_value, + value_is_sequence, +) +from fastapi.background import BackgroundTasks from fastapi.concurrency import ( - AsyncExitStack, asynccontextmanager, contextmanager_in_threadpool, ) @@ -31,50 +55,14 @@ from fastapi.security.oauth2 import OAuth2, SecurityScopes from fastapi.security.open_id_connect_url import OpenIdConnect from fastapi.utils import create_response_field, get_path_param_names -from pydantic import BaseModel, create_model -from pydantic.error_wrappers import ErrorWrapper -from pydantic.errors import MissingError -from pydantic.fields import ( - SHAPE_FROZENSET, - SHAPE_LIST, - SHAPE_SEQUENCE, - SHAPE_SET, - SHAPE_SINGLETON, - SHAPE_TUPLE, - SHAPE_TUPLE_ELLIPSIS, - FieldInfo, - ModelField, - Required, - Undefined, -) -from pydantic.schema import get_annotation_from_field_info -from pydantic.typing import evaluate_forwardref, get_args, get_origin -from pydantic.utils import lenient_issubclass -from starlette.background import BackgroundTasks +from pydantic.fields import FieldInfo +from starlette.background import BackgroundTasks as StarletteBackgroundTasks from starlette.concurrency import run_in_threadpool from starlette.datastructures import FormData, Headers, QueryParams, UploadFile from starlette.requests import HTTPConnection, Request from starlette.responses import Response from starlette.websockets import WebSocket -from typing_extensions import Annotated - -sequence_shapes = { - SHAPE_LIST, - SHAPE_SET, - SHAPE_FROZENSET, - SHAPE_TUPLE, - SHAPE_SEQUENCE, - SHAPE_TUPLE_ELLIPSIS, -} -sequence_types = (list, set, tuple) -sequence_shape_to_type = { - SHAPE_LIST: list, - SHAPE_SET: set, - SHAPE_TUPLE: tuple, - SHAPE_SEQUENCE: list, - SHAPE_TUPLE_ELLIPSIS: list, -} - +from typing_extensions import Annotated, get_args, get_origin multipart_not_installed_error = ( 'Form data requires "python-multipart" to be installed. \n' @@ -216,36 +204,6 @@ def get_flat_params(dependant: Dependant) -> List[ModelField]: ) -def is_scalar_field(field: ModelField) -> bool: - field_info = field.field_info - if not ( - field.shape == SHAPE_SINGLETON - and not lenient_issubclass(field.type_, BaseModel) - and not lenient_issubclass(field.type_, sequence_types + (dict,)) - and not dataclasses.is_dataclass(field.type_) - and not isinstance(field_info, params.Body) - ): - return False - if field.sub_fields: - if not all(is_scalar_field(f) for f in field.sub_fields): - return False - return True - - -def is_scalar_sequence_field(field: ModelField) -> bool: - if (field.shape in sequence_shapes) and not lenient_issubclass( - field.type_, BaseModel - ): - if field.sub_fields is not None: - for sub_field in field.sub_fields: - if not is_scalar_field(sub_field): - return False - return True - if lenient_issubclass(field.type_, sequence_types): - return True - return False - - def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature: signature = inspect.signature(call) globalns = getattr(call, "__globals__", {}) @@ -347,7 +305,7 @@ def add_non_field_param_to_dependency( elif lenient_issubclass(type_annotation, Response): dependant.response_param_name = param_name return True - elif lenient_issubclass(type_annotation, BackgroundTasks): + elif lenient_issubclass(type_annotation, StarletteBackgroundTasks): dependant.background_tasks_param_name = param_name return True elif lenient_issubclass(type_annotation, SecurityScopes): @@ -364,13 +322,13 @@ def analyze_param( is_path_param: bool, ) -> Tuple[Any, Optional[params.Depends], Optional[ModelField]]: field_info = None - used_default_field_info = False depends = None type_annotation: Any = Any - if ( - annotation is not inspect.Signature.empty - and get_origin(annotation) is Annotated # type: ignore[comparison-overlap] - ): + use_annotation: Any = Any + if annotation is not inspect.Signature.empty: + use_annotation = annotation + type_annotation = annotation + if get_origin(use_annotation) is Annotated: annotated_args = get_args(annotation) type_annotation = annotated_args[0] fastapi_annotations = [ @@ -378,13 +336,22 @@ def analyze_param( for arg in annotated_args[1:] if isinstance(arg, (FieldInfo, params.Depends)) ] - assert ( - len(fastapi_annotations) <= 1 - ), f"Cannot specify multiple `Annotated` FastAPI arguments for {param_name!r}" - fastapi_annotation = next(iter(fastapi_annotations), None) + fastapi_specific_annotations = [ + arg + for arg in fastapi_annotations + if isinstance(arg, (params.Param, params.Body, params.Depends)) + ] + if fastapi_specific_annotations: + fastapi_annotation: Union[ + FieldInfo, params.Depends, None + ] = fastapi_specific_annotations[-1] + else: + fastapi_annotation = None if isinstance(fastapi_annotation, FieldInfo): # Copy `field_info` because we mutate `field_info.default` below. - field_info = copy(fastapi_annotation) + field_info = copy_field_info( + field_info=fastapi_annotation, annotation=use_annotation + ) assert field_info.default is Undefined or field_info.default is Required, ( f"`{field_info.__class__.__name__}` default value cannot be set in" f" `Annotated` for {param_name!r}. Set the default value with `=` instead." @@ -396,8 +363,6 @@ def analyze_param( field_info.default = Required elif isinstance(fastapi_annotation, params.Depends): depends = fastapi_annotation - elif annotation is not inspect.Signature.empty: - type_annotation = annotation if isinstance(value, params.Depends): assert depends is None, ( @@ -415,13 +380,22 @@ def analyze_param( f" together for {param_name!r}" ) field_info = value + if PYDANTIC_V2: + field_info.annotation = type_annotation if depends is not None and depends.dependency is None: depends.dependency = type_annotation if lenient_issubclass( type_annotation, - (Request, WebSocket, HTTPConnection, Response, BackgroundTasks, SecurityScopes), + ( + Request, + WebSocket, + HTTPConnection, + Response, + StarletteBackgroundTasks, + SecurityScopes, + ), ): assert depends is None, f"Cannot specify `Depends` for type {type_annotation!r}" assert ( @@ -433,10 +407,15 @@ def analyze_param( # We might check here that `default_value is Required`, but the fact is that the same # parameter might sometimes be a path parameter and sometimes not. See # `tests/test_infer_param_optionality.py` for an example. - field_info = params.Path() + field_info = params.Path(annotation=use_annotation) + elif is_uploadfile_or_nonable_uploadfile_annotation( + type_annotation + ) or is_uploadfile_sequence_annotation(type_annotation): + field_info = params.File(annotation=use_annotation, default=default_value) + elif not field_annotation_is_scalar(annotation=type_annotation): + field_info = params.Body(annotation=use_annotation, default=default_value) else: - field_info = params.Query(default=default_value) - used_default_field_info = True + field_info = params.Query(annotation=use_annotation, default=default_value) field = None if field_info is not None: @@ -450,8 +429,8 @@ def analyze_param( and getattr(field_info, "in_", None) is None ): field_info.in_ = params.ParamTypes.query - annotation = get_annotation_from_field_info( - annotation if annotation is not inspect.Signature.empty else Any, + use_annotation_from_field_info = get_annotation_from_field_info( + use_annotation, field_info, param_name, ) @@ -459,19 +438,15 @@ def analyze_param( alias = param_name.replace("_", "-") else: alias = field_info.alias or param_name + field_info.alias = alias field = create_response_field( name=param_name, - type_=annotation, + type_=use_annotation_from_field_info, default=field_info.default, alias=alias, required=field_info.default in (Required, Undefined), field_info=field_info, ) - if used_default_field_info: - if lenient_issubclass(field.type_, UploadFile): - field.field_info = params.File(field_info.default) - elif not is_scalar_field(field=field): - field.field_info = params.Body(field_info.default) return type_annotation, depends, field @@ -496,16 +471,17 @@ def is_body_param(*, param_field: ModelField, is_path_param: bool) -> bool: def add_param_to_fields(*, field: ModelField, dependant: Dependant) -> None: - field_info = cast(params.Param, field.field_info) - if field_info.in_ == params.ParamTypes.path: + field_info = field.field_info + field_info_in = getattr(field_info, "in_", None) + if field_info_in == params.ParamTypes.path: dependant.path_params.append(field) - elif field_info.in_ == params.ParamTypes.query: + elif field_info_in == params.ParamTypes.query: dependant.query_params.append(field) - elif field_info.in_ == params.ParamTypes.header: + elif field_info_in == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( - field_info.in_ == params.ParamTypes.cookie + field_info_in == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {field.name}" dependant.cookie_params.append(field) @@ -548,19 +524,20 @@ async def solve_dependencies( request: Union[Request, WebSocket], dependant: Dependant, body: Optional[Union[Dict[str, Any], FormData]] = None, - background_tasks: Optional[BackgroundTasks] = None, + background_tasks: Optional[StarletteBackgroundTasks] = None, response: Optional[Response] = None, dependency_overrides_provider: Optional[Any] = None, dependency_cache: Optional[Dict[Tuple[Callable[..., Any], Tuple[str]], Any]] = None, + async_exit_stack: AsyncExitStack, ) -> Tuple[ Dict[str, Any], - List[ErrorWrapper], - Optional[BackgroundTasks], + List[Any], + Optional[StarletteBackgroundTasks], Response, Dict[Tuple[Callable[..., Any], Tuple[str]], Any], ]: values: Dict[str, Any] = {} - errors: List[ErrorWrapper] = [] + errors: List[Any] = [] if response is None: response = Response() del response.headers["content-length"] @@ -598,6 +575,7 @@ async def solve_dependencies( response=response, dependency_overrides_provider=dependency_overrides_provider, dependency_cache=dependency_cache, + async_exit_stack=async_exit_stack, ) ( sub_values, @@ -613,10 +591,8 @@ async def solve_dependencies( if sub_dependant.use_cache and sub_dependant.cache_key in dependency_cache: solved = dependency_cache[sub_dependant.cache_key] elif is_gen_callable(call) or is_async_gen_callable(call): - stack = request.scope.get("fastapi_astack") - assert isinstance(stack, AsyncExitStack) solved = await solve_generator( - call=call, stack=stack, sub_values=sub_values + call=call, stack=async_exit_stack, sub_values=sub_values ) elif is_coroutine_callable(call): solved = await call(**sub_values) @@ -674,7 +650,7 @@ async def solve_dependencies( def request_params_to_args( required_params: Sequence[ModelField], received_params: Union[Mapping[str, Any], QueryParams, Headers], -) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: +) -> Tuple[Dict[str, Any], List[Any]]: values = {} errors = [] for field in required_params: @@ -688,23 +664,19 @@ def request_params_to_args( assert isinstance( field_info, params.Param ), "Params must be subclasses of Param" + loc = (field_info.in_.value, field.alias) if value is None: if field.required: - errors.append( - ErrorWrapper( - MissingError(), loc=(field_info.in_.value, field.alias) - ) - ) + errors.append(get_missing_field_error(loc=loc)) else: values[field.name] = deepcopy(field.default) continue - v_, errors_ = field.validate( - value, values, loc=(field_info.in_.value, field.alias) - ) + v_, errors_ = field.validate(value, values, loc=loc) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): - errors.extend(errors_) + new_errors = _regenerate_error_with_loc(errors=errors_, loc_prefix=()) + errors.extend(new_errors) else: values[field.name] = v_ return values, errors @@ -713,9 +685,9 @@ def request_params_to_args( async def request_body_to_args( required_params: List[ModelField], received_body: Optional[Union[Dict[str, Any], FormData]], -) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: +) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]: values = {} - errors = [] + errors: List[Dict[str, Any]] = [] if required_params: field = required_params[0] field_info = field.field_info @@ -733,9 +705,7 @@ async def request_body_to_args( value: Optional[Any] = None if received_body is not None: - if ( - field.shape in sequence_shapes or field.type_ in sequence_types - ) and isinstance(received_body, FormData): + if (is_sequence_field(field)) and isinstance(received_body, FormData): value = received_body.getlist(field.alias) else: try: @@ -748,7 +718,7 @@ async def request_body_to_args( or (isinstance(field_info, params.Form) and value == "") or ( isinstance(field_info, params.Form) - and field.shape in sequence_shapes + and is_sequence_field(field) and len(value) == 0 ) ): @@ -759,20 +729,21 @@ async def request_body_to_args( continue if ( isinstance(field_info, params.File) - and lenient_issubclass(field.type_, bytes) + and is_bytes_field(field) and isinstance(value, UploadFile) ): value = await value.read() elif ( - field.shape in sequence_shapes + is_bytes_sequence_field(field) and isinstance(field_info, params.File) - and lenient_issubclass(field.type_, bytes) - and isinstance(value, sequence_types) + and value_is_sequence(value) ): + # For types + assert isinstance(value, sequence_types) # type: ignore[arg-type] results: List[Union[bytes, str]] = [] async def process_fn( - fn: Callable[[], Coroutine[Any, Any, Any]] + fn: Callable[[], Coroutine[Any, Any, Any]], ) -> None: result = await fn() results.append(result) # noqa: B023 @@ -780,24 +751,19 @@ async def process_fn( async with anyio.create_task_group() as tg: for sub_value in value: tg.start_soon(process_fn, sub_value.read) - value = sequence_shape_to_type[field.shape](results) + value = serialize_sequence_value(field=field, value=results) v_, errors_ = field.validate(value, values, loc=loc) - if isinstance(errors_, ErrorWrapper): - errors.append(errors_) - elif isinstance(errors_, list): + if isinstance(errors_, list): errors.extend(errors_) + elif errors_: + errors.append(errors_) else: values[field.name] = v_ return values, errors -def get_missing_field_error(loc: Tuple[str, ...]) -> ErrorWrapper: - missing_field_error = ErrorWrapper(MissingError(), loc=loc) - return missing_field_error - - def get_body_field(*, dependant: Dependant, name: str) -> Optional[ModelField]: flat_dependant = get_flat_dependant(dependant) if not flat_dependant.body_params: @@ -815,12 +781,16 @@ def get_body_field(*, dependant: Dependant, name: str) -> Optional[ModelField]: for param in flat_dependant.body_params: setattr(param.field_info, "embed", True) # noqa: B010 model_name = "Body_" + name - BodyModel: Type[BaseModel] = create_model(model_name) - for f in flat_dependant.body_params: - BodyModel.__fields__[f.name] = f + BodyModel = create_body_model( + fields=flat_dependant.body_params, model_name=model_name + ) required = any(True for f in flat_dependant.body_params if f.required) - - BodyFieldInfo_kwargs: Dict[str, Any] = {"default": None} + BodyFieldInfo_kwargs: Dict[str, Any] = { + "annotation": BodyModel, + "alias": "body", + } + if not required: + BodyFieldInfo_kwargs["default"] = None if any(isinstance(f.field_info, params.File) for f in flat_dependant.body_params): BodyFieldInfo: Type[params.Body] = params.File elif any(isinstance(f.field_info, params.Form) for f in flat_dependant.body_params): diff --git a/fastapi/encoders.py b/fastapi/encoders.py index 2f95bcbf6692d..431387f716dad 100644 --- a/fastapi/encoders.py +++ b/fastapi/encoders.py @@ -1,19 +1,92 @@ import dataclasses -from collections import defaultdict +import datetime +from collections import defaultdict, deque +from decimal import Decimal from enum import Enum -from pathlib import PurePath +from ipaddress import ( + IPv4Address, + IPv4Interface, + IPv4Network, + IPv6Address, + IPv6Interface, + IPv6Network, +) +from pathlib import Path, PurePath +from re import Pattern from types import GeneratorType -from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union +from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union +from uuid import UUID +from fastapi.types import IncEx from pydantic import BaseModel -from pydantic.json import ENCODERS_BY_TYPE +from pydantic.color import Color +from pydantic.networks import AnyUrl, NameEmail +from pydantic.types import SecretBytes, SecretStr +from typing_extensions import Annotated, Doc # type: ignore [attr-defined] -SetIntStr = Set[Union[int, str]] -DictIntStrAny = Dict[Union[int, str], Any] +from ._compat import PYDANTIC_V2, Url, _model_dump + + +# Taken from Pydantic v1 as is +def isoformat(o: Union[datetime.date, datetime.time]) -> str: + return o.isoformat() + + +# Taken from Pydantic v1 as is +# TODO: pv2 should this return strings instead? +def decimal_encoder(dec_value: Decimal) -> Union[int, float]: + """ + Encodes a Decimal as int of there's no exponent, otherwise float + + This is useful when we use ConstrainedDecimal to represent Numeric(x,0) + where a integer (but not int typed) is used. Encoding this as a float + results in failed round-tripping between encode and parse. + Our Id type is a prime example of this. + + >>> decimal_encoder(Decimal("1.0")) + 1.0 + + >>> decimal_encoder(Decimal("1")) + 1 + """ + if dec_value.as_tuple().exponent >= 0: # type: ignore[operator] + return int(dec_value) + else: + return float(dec_value) + + +ENCODERS_BY_TYPE: Dict[Type[Any], Callable[[Any], Any]] = { + bytes: lambda o: o.decode(), + Color: str, + datetime.date: isoformat, + datetime.datetime: isoformat, + datetime.time: isoformat, + datetime.timedelta: lambda td: td.total_seconds(), + Decimal: decimal_encoder, + Enum: lambda o: o.value, + frozenset: list, + deque: list, + GeneratorType: list, + IPv4Address: str, + IPv4Interface: str, + IPv4Network: str, + IPv6Address: str, + IPv6Interface: str, + IPv6Network: str, + NameEmail: str, + Path: str, + Pattern: lambda o: o.pattern, + SecretBytes: str, + SecretStr: str, + set: list, + UUID: str, + Url: str, + AnyUrl: str, +} def generate_encoders_by_class_tuples( - type_encoder_map: Dict[Any, Callable[[Any], Any]] + type_encoder_map: Dict[Any, Callable[[Any], Any]], ) -> Dict[Callable[[Any], Any], Tuple[Any, ...]]: encoders_by_class_tuples: Dict[Callable[[Any], Any], Tuple[Any, ...]] = defaultdict( tuple @@ -27,16 +100,107 @@ def generate_encoders_by_class_tuples( def jsonable_encoder( - obj: Any, - include: Optional[Union[SetIntStr, DictIntStrAny]] = None, - exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, - by_alias: bool = True, - exclude_unset: bool = False, - exclude_defaults: bool = False, - exclude_none: bool = False, - custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None, - sqlalchemy_safe: bool = True, + obj: Annotated[ + Any, + Doc( + """ + The input object to convert to JSON. + """ + ), + ], + include: Annotated[ + Optional[IncEx], + Doc( + """ + Pydantic's `include` parameter, passed to Pydantic models to set the + fields to include. + """ + ), + ] = None, + exclude: Annotated[ + Optional[IncEx], + Doc( + """ + Pydantic's `exclude` parameter, passed to Pydantic models to set the + fields to exclude. + """ + ), + ] = None, + by_alias: Annotated[ + bool, + Doc( + """ + Pydantic's `by_alias` parameter, passed to Pydantic models to define if + the output should use the alias names (when provided) or the Python + attribute names. In an API, if you set an alias, it's probably because you + want to use it in the result, so you probably want to leave this set to + `True`. + """ + ), + ] = True, + exclude_unset: Annotated[ + bool, + Doc( + """ + Pydantic's `exclude_unset` parameter, passed to Pydantic models to define + if it should exclude from the output the fields that were not explicitly + set (and that only had their default values). + """ + ), + ] = False, + exclude_defaults: Annotated[ + bool, + Doc( + """ + Pydantic's `exclude_defaults` parameter, passed to Pydantic models to define + if it should exclude from the output the fields that had the same default + value, even when they were explicitly set. + """ + ), + ] = False, + exclude_none: Annotated[ + bool, + Doc( + """ + Pydantic's `exclude_none` parameter, passed to Pydantic models to define + if it should exclude from the output any fields that have a `None` value. + """ + ), + ] = False, + custom_encoder: Annotated[ + Optional[Dict[Any, Callable[[Any], Any]]], + Doc( + """ + Pydantic's `custom_encoder` parameter, passed to Pydantic models to define + a custom encoder. + """ + ), + ] = None, + sqlalchemy_safe: Annotated[ + bool, + Doc( + """ + Exclude from the output any fields that start with the name `_sa`. + + This is mainly a hack for compatibility with SQLAlchemy objects, they + store internal SQLAlchemy-specific state in attributes named with `_sa`, + and those objects can't (and shouldn't be) serialized to JSON. + """ + ), + ] = True, ) -> Any: + """ + Convert any object to something that can be encoded in JSON. + + This is used internally by FastAPI to make sure anything you return can be + encoded as JSON before it is sent to the client. + + You can also use it yourself, for example to convert objects before saving them + in a database that supports only JSON. + + Read more about it in the + [FastAPI docs for JSON Compatible Encoder](https://fastapi.tiangolo.com/tutorial/encoder/). + """ custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: @@ -50,10 +214,15 @@ def jsonable_encoder( if exclude is not None and not isinstance(exclude, (set, dict)): exclude = set(exclude) if isinstance(obj, BaseModel): - encoder = getattr(obj.__config__, "json_encoders", {}) - if custom_encoder: - encoder.update(custom_encoder) - obj_dict = obj.dict( + # TODO: remove when deprecating Pydantic v1 + encoders: Dict[Any, Any] = {} + if not PYDANTIC_V2: + encoders = getattr(obj.__config__, "json_encoders", {}) # type: ignore[attr-defined] + if custom_encoder: + encoders.update(custom_encoder) + obj_dict = _model_dump( + obj, + mode="json", include=include, exclude=exclude, by_alias=by_alias, @@ -67,7 +236,8 @@ def jsonable_encoder( obj_dict, exclude_none=exclude_none, exclude_defaults=exclude_defaults, - custom_encoder=encoder, + # TODO: remove when deprecating Pydantic v1 + custom_encoder=encoders, sqlalchemy_safe=sqlalchemy_safe, ) if dataclasses.is_dataclass(obj): @@ -124,7 +294,7 @@ def jsonable_encoder( ) encoded_dict[encoded_key] = encoded_value return encoded_dict - if isinstance(obj, (list, set, frozenset, GeneratorType, tuple)): + if isinstance(obj, (list, set, frozenset, GeneratorType, tuple, deque)): encoded_list = [] for item in obj: encoded_list.append( diff --git a/fastapi/exceptions.py b/fastapi/exceptions.py index cac5330a22910..680d288e4dc1f 100644 --- a/fastapi/exceptions.py +++ b/fastapi/exceptions.py @@ -1,21 +1,141 @@ -from typing import Any, Dict, Optional, Sequence, Type +from typing import Any, Dict, Optional, Sequence, Type, Union -from pydantic import BaseModel, ValidationError, create_model -from pydantic.error_wrappers import ErrorList +from pydantic import BaseModel, create_model from starlette.exceptions import HTTPException as StarletteHTTPException -from starlette.exceptions import WebSocketException as WebSocketException # noqa: F401 +from starlette.exceptions import WebSocketException as StarletteWebSocketException +from typing_extensions import Annotated, Doc # type: ignore [attr-defined] class HTTPException(StarletteHTTPException): + """ + An HTTP exception you can raise in your own code to show errors to the client. + + This is for client errors, invalid authentication, invalid data, etc. Not for server + errors in your code. + + Read more about it in the + [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/). + + ## Example + + ```python + from fastapi import FastAPI, HTTPException + + app = FastAPI() + + items = {"foo": "The Foo Wrestlers"} + + + @app.get("/items/{item_id}") + async def read_item(item_id: str): + if item_id not in items: + raise HTTPException(status_code=404, detail="Item not found") + return {"item": items[item_id]} + ``` + """ + def __init__( self, - status_code: int, - detail: Any = None, - headers: Optional[Dict[str, str]] = None, + status_code: Annotated[ + int, + Doc( + """ + HTTP status code to send to the client. + """ + ), + ], + detail: Annotated[ + Any, + Doc( + """ + Any data to be sent to the client in the `detail` key of the JSON + response. + """ + ), + ] = None, + headers: Annotated[ + Optional[Dict[str, str]], + Doc( + """ + Any headers to send to the client in the response. + """ + ), + ] = None, ) -> None: super().__init__(status_code=status_code, detail=detail, headers=headers) +class WebSocketException(StarletteWebSocketException): + """ + A WebSocket exception you can raise in your own code to show errors to the client. + + This is for client errors, invalid authentication, invalid data, etc. Not for server + errors in your code. + + Read more about it in the + [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). + + ## Example + + ```python + from typing import Annotated + + from fastapi import ( + Cookie, + FastAPI, + WebSocket, + WebSocketException, + status, + ) + + app = FastAPI() + + @app.websocket("/items/{item_id}/ws") + async def websocket_endpoint( + *, + websocket: WebSocket, + session: Annotated[str | None, Cookie()] = None, + item_id: str, + ): + if session is None: + raise WebSocketException(code=status.WS_1008_POLICY_VIOLATION) + await websocket.accept() + while True: + data = await websocket.receive_text() + await websocket.send_text(f"Session cookie is: {session}") + await websocket.send_text(f"Message text was: {data}, for item ID: {item_id}") + ``` + """ + + def __init__( + self, + code: Annotated[ + int, + Doc( + """ + A closing code from the + [valid codes defined in the specification](https://datatracker.ietf.org/doc/html/rfc6455#section-7.4.1). + """ + ), + ], + reason: Annotated[ + Union[str, None], + Doc( + """ + The reason to close the WebSocket connection. + + It is UTF-8-encoded data. The interpretation of the reason is up to the + application, it is not specified by the WebSocket specification. + + It could contain text that could be human-readable or interpretable + by the client code, etc. + """ + ), + ] = None, + ) -> None: + super().__init__(code=code, reason=reason) + + RequestErrorModel: Type[BaseModel] = create_model("Request") WebSocketErrorModel: Type[BaseModel] = create_model("WebSocket") @@ -26,12 +146,31 @@ class FastAPIError(RuntimeError): """ -class RequestValidationError(ValidationError): - def __init__(self, errors: Sequence[ErrorList], *, body: Any = None) -> None: +class ValidationException(Exception): + def __init__(self, errors: Sequence[Any]) -> None: + self._errors = errors + + def errors(self) -> Sequence[Any]: + return self._errors + + +class RequestValidationError(ValidationException): + def __init__(self, errors: Sequence[Any], *, body: Any = None) -> None: + super().__init__(errors) self.body = body - super().__init__(errors, RequestErrorModel) -class WebSocketRequestValidationError(ValidationError): - def __init__(self, errors: Sequence[ErrorList]) -> None: - super().__init__(errors, WebSocketErrorModel) +class WebSocketRequestValidationError(ValidationException): + pass + + +class ResponseValidationError(ValidationException): + def __init__(self, errors: Sequence[Any], *, body: Any = None) -> None: + super().__init__(errors) + self.body = body + + def __str__(self) -> str: + message = f"{len(self._errors)} validation errors:\n" + for err in self._errors: + message += f" {err}\n" + return message diff --git a/fastapi/middleware/asyncexitstack.py b/fastapi/middleware/asyncexitstack.py deleted file mode 100644 index 30a0ae626c26c..0000000000000 --- a/fastapi/middleware/asyncexitstack.py +++ /dev/null @@ -1,25 +0,0 @@ -from typing import Optional - -from fastapi.concurrency import AsyncExitStack -from starlette.types import ASGIApp, Receive, Scope, Send - - -class AsyncExitStackMiddleware: - def __init__(self, app: ASGIApp, context_name: str = "fastapi_astack") -> None: - self.app = app - self.context_name = context_name - - async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: - dependency_exception: Optional[Exception] = None - async with AsyncExitStack() as stack: - scope[self.context_name] = stack - try: - await self.app(scope, receive, send) - except Exception as e: - dependency_exception = e - raise e - if dependency_exception: - # This exception was possibly handled by the dependency but it should - # still bubble up so that the ServerErrorMiddleware can return a 500 - # or the ExceptionMiddleware can catch and handle any other exceptions - raise dependency_exception diff --git a/fastapi/openapi/constants.py b/fastapi/openapi/constants.py index 1897ad750915e..d724ee3cfdbcd 100644 --- a/fastapi/openapi/constants.py +++ b/fastapi/openapi/constants.py @@ -1,2 +1,3 @@ METHODS_WITH_BODY = {"GET", "HEAD", "POST", "PUT", "DELETE", "PATCH"} REF_PREFIX = "#/components/schemas/" +REF_TEMPLATE = "#/components/schemas/{model}" diff --git a/fastapi/openapi/docs.py b/fastapi/openapi/docs.py index bf335118fc791..69473d19cb256 100644 --- a/fastapi/openapi/docs.py +++ b/fastapi/openapi/docs.py @@ -3,8 +3,18 @@ from fastapi.encoders import jsonable_encoder from starlette.responses import HTMLResponse +from typing_extensions import Annotated, Doc # type: ignore [attr-defined] -swagger_ui_default_parameters = { +swagger_ui_default_parameters: Annotated[ + Dict[str, Any], + Doc( + """ + Default configurations for Swagger UI. + + You can use it as a template to add any other configurations needed. + """ + ), +] = { "dom_id": "#swagger-ui", "layout": "BaseLayout", "deepLinking": True, @@ -15,15 +25,91 @@ def get_swagger_ui_html( *, - openapi_url: str, - title: str, - swagger_js_url: str = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@4/swagger-ui-bundle.js", - swagger_css_url: str = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@4/swagger-ui.css", - swagger_favicon_url: str = "https://fastapi.tiangolo.com/img/favicon.png", - oauth2_redirect_url: Optional[str] = None, - init_oauth: Optional[Dict[str, Any]] = None, - swagger_ui_parameters: Optional[Dict[str, Any]] = None, + openapi_url: Annotated[ + str, + Doc( + """ + The OpenAPI URL that Swagger UI should load and use. + + This is normally done automatically by FastAPI using the default URL + `/openapi.json`. + """ + ), + ], + title: Annotated[ + str, + Doc( + """ + The HTML `` content, normally shown in the browser tab. + """ + ), + ], + swagger_js_url: Annotated[ + str, + Doc( + """ + The URL to use to load the Swagger UI JavaScript. + + It is normally set to a CDN URL. + """ + ), + ] = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.9.0/swagger-ui-bundle.js", + swagger_css_url: Annotated[ + str, + Doc( + """ + The URL to use to load the Swagger UI CSS. + + It is normally set to a CDN URL. + """ + ), + ] = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.9.0/swagger-ui.css", + swagger_favicon_url: Annotated[ + str, + Doc( + """ + The URL of the favicon to use. It is normally shown in the browser tab. + """ + ), + ] = "https://fastapi.tiangolo.com/img/favicon.png", + oauth2_redirect_url: Annotated[ + Optional[str], + Doc( + """ + The OAuth2 redirect URL, it is normally automatically handled by FastAPI. + """ + ), + ] = None, + init_oauth: Annotated[ + Optional[Dict[str, Any]], + Doc( + """ + A dictionary with Swagger UI OAuth2 initialization configurations. + """ + ), + ] = None, + swagger_ui_parameters: Annotated[ + Optional[Dict[str, Any]], + Doc( + """ + Configuration parameters for Swagger UI. + + It defaults to [swagger_ui_default_parameters][fastapi.openapi.docs.swagger_ui_default_parameters]. + """ + ), + ] = None, ) -> HTMLResponse: + """ + Generate and return the HTML that loads Swagger UI for the interactive + API docs (normally served at `/docs`). + + You would only call this function yourself if you needed to override some parts, + for example the URLs to use to load Swagger UI's JavaScript and CSS. + + Read more about it in the + [FastAPI docs for Configure Swagger UI](https://fastapi.tiangolo.com/how-to/configure-swagger-ui/) + and the [FastAPI docs for Custom Docs UI Static Assets (Self-Hosting)](https://fastapi.tiangolo.com/how-to/custom-docs-ui-assets/). + """ current_swagger_ui_parameters = swagger_ui_default_parameters.copy() if swagger_ui_parameters: current_swagger_ui_parameters.update(swagger_ui_parameters) @@ -74,12 +160,62 @@ def get_swagger_ui_html( def get_redoc_html( *, - openapi_url: str, - title: str, - redoc_js_url: str = "https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js", - redoc_favicon_url: str = "https://fastapi.tiangolo.com/img/favicon.png", - with_google_fonts: bool = True, + openapi_url: Annotated[ + str, + Doc( + """ + The OpenAPI URL that ReDoc should load and use. + + This is normally done automatically by FastAPI using the default URL + `/openapi.json`. + """ + ), + ], + title: Annotated[ + str, + Doc( + """ + The HTML `<title>` content, normally shown in the browser tab. + """ + ), + ], + redoc_js_url: Annotated[ + str, + Doc( + """ + The URL to use to load the ReDoc JavaScript. + + It is normally set to a CDN URL. + """ + ), + ] = "https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js", + redoc_favicon_url: Annotated[ + str, + Doc( + """ + The URL of the favicon to use. It is normally shown in the browser tab. + """ + ), + ] = "https://fastapi.tiangolo.com/img/favicon.png", + with_google_fonts: Annotated[ + bool, + Doc( + """ + Load and use Google Fonts. + """ + ), + ] = True, ) -> HTMLResponse: + """ + Generate and return the HTML response that loads ReDoc for the alternative + API docs (normally served at `/redoc`). + + You would only call this function yourself if you needed to override some parts, + for example the URLs to use to load ReDoc's JavaScript and CSS. + + Read more about it in the + [FastAPI docs for Custom Docs UI Static Assets (Self-Hosting)](https://fastapi.tiangolo.com/how-to/custom-docs-ui-assets/). + """ html = f""" <!DOCTYPE html> <html> @@ -118,6 +254,11 @@ def get_redoc_html( def get_swagger_ui_oauth2_redirect_html() -> HTMLResponse: + """ + Generate the HTML response with the OAuth2 redirection for Swagger UI. + + You normally don't need to use or change this. + """ # copied from https://github.com/swagger-api/swagger-ui/blob/v4.14.0/dist/oauth2-redirect.html html = """ <!doctype html> diff --git a/fastapi/openapi/models.py b/fastapi/openapi/models.py index 81a24f389b63b..5f3bdbb2066a6 100644 --- a/fastapi/openapi/models.py +++ b/fastapi/openapi/models.py @@ -1,12 +1,21 @@ from enum import Enum -from typing import Any, Callable, Dict, Iterable, List, Optional, Union - +from typing import Any, Callable, Dict, Iterable, List, Optional, Set, Type, Union + +from fastapi._compat import ( + PYDANTIC_V2, + CoreSchema, + GetJsonSchemaHandler, + JsonSchemaValue, + _model_rebuild, + with_info_plain_validator_function, +) from fastapi.logger import logger from pydantic import AnyUrl, BaseModel, Field -from typing_extensions import Literal +from typing_extensions import Annotated, Literal, TypedDict +from typing_extensions import deprecated as typing_deprecated try: - import email_validator # type: ignore + import email_validator assert email_validator # make autoflake ignore the unused import from pydantic import EmailStr @@ -25,43 +34,85 @@ def validate(cls, v: Any) -> str: ) return str(v) + @classmethod + def _validate(cls, __input_value: Any, _: Any) -> str: + logger.warning( + "email-validator not installed, email fields will be treated as str.\n" + "To install, run: pip install email-validator" + ) + return str(__input_value) + + @classmethod + def __get_pydantic_json_schema__( + cls, core_schema: CoreSchema, handler: GetJsonSchemaHandler + ) -> JsonSchemaValue: + return {"type": "string", "format": "email"} + + @classmethod + def __get_pydantic_core_schema__( + cls, source: Type[Any], handler: Callable[[Any], CoreSchema] + ) -> CoreSchema: + return with_info_plain_validator_function(cls._validate) + class Contact(BaseModel): name: Optional[str] = None url: Optional[AnyUrl] = None email: Optional[EmailStr] = None - class Config: - extra = "allow" + if PYDANTIC_V2: + model_config = {"extra": "allow"} + + else: + + class Config: + extra = "allow" class License(BaseModel): name: str + identifier: Optional[str] = None url: Optional[AnyUrl] = None - class Config: - extra = "allow" + if PYDANTIC_V2: + model_config = {"extra": "allow"} + + else: + + class Config: + extra = "allow" class Info(BaseModel): title: str + summary: Optional[str] = None description: Optional[str] = None termsOfService: Optional[str] = None contact: Optional[Contact] = None license: Optional[License] = None version: str - class Config: - extra = "allow" + if PYDANTIC_V2: + model_config = {"extra": "allow"} + + else: + + class Config: + extra = "allow" class ServerVariable(BaseModel): - enum: Optional[List[str]] = None + enum: Annotated[Optional[List[str]], Field(min_length=1)] = None default: str description: Optional[str] = None - class Config: - extra = "allow" + if PYDANTIC_V2: + model_config = {"extra": "allow"} + + else: + + class Config: + extra = "allow" class Server(BaseModel): @@ -69,8 +120,13 @@ class Server(BaseModel): description: Optional[str] = None variables: Optional[Dict[str, ServerVariable]] = None - class Config: - extra = "allow" + if PYDANTIC_V2: + model_config = {"extra": "allow"} + + else: + + class Config: + extra = "allow" class Reference(BaseModel): @@ -89,22 +145,68 @@ class XML(BaseModel): attribute: Optional[bool] = None wrapped: Optional[bool] = None - class Config: - extra = "allow" + if PYDANTIC_V2: + model_config = {"extra": "allow"} + + else: + + class Config: + extra = "allow" class ExternalDocumentation(BaseModel): description: Optional[str] = None url: AnyUrl - class Config: - extra = "allow" + if PYDANTIC_V2: + model_config = {"extra": "allow"} + + else: + + class Config: + extra = "allow" class Schema(BaseModel): + # Ref: JSON Schema 2020-12: https://json-schema.org/draft/2020-12/json-schema-core.html#name-the-json-schema-core-vocabu + # Core Vocabulary + schema_: Optional[str] = Field(default=None, alias="$schema") + vocabulary: Optional[str] = Field(default=None, alias="$vocabulary") + id: Optional[str] = Field(default=None, alias="$id") + anchor: Optional[str] = Field(default=None, alias="$anchor") + dynamicAnchor: Optional[str] = Field(default=None, alias="$dynamicAnchor") ref: Optional[str] = Field(default=None, alias="$ref") - title: Optional[str] = None - multipleOf: Optional[float] = None + dynamicRef: Optional[str] = Field(default=None, alias="$dynamicRef") + defs: Optional[Dict[str, "SchemaOrBool"]] = Field(default=None, alias="$defs") + comment: Optional[str] = Field(default=None, alias="$comment") + # Ref: JSON Schema 2020-12: https://json-schema.org/draft/2020-12/json-schema-core.html#name-a-vocabulary-for-applying-s + # A Vocabulary for Applying Subschemas + allOf: Optional[List["SchemaOrBool"]] = None + anyOf: Optional[List["SchemaOrBool"]] = None + oneOf: Optional[List["SchemaOrBool"]] = None + not_: Optional["SchemaOrBool"] = Field(default=None, alias="not") + if_: Optional["SchemaOrBool"] = Field(default=None, alias="if") + then: Optional["SchemaOrBool"] = None + else_: Optional["SchemaOrBool"] = Field(default=None, alias="else") + dependentSchemas: Optional[Dict[str, "SchemaOrBool"]] = None + prefixItems: Optional[List["SchemaOrBool"]] = None + # TODO: uncomment and remove below when deprecating Pydantic v1 + # It generales a list of schemas for tuples, before prefixItems was available + # items: Optional["SchemaOrBool"] = None + items: Optional[Union["SchemaOrBool", List["SchemaOrBool"]]] = None + contains: Optional["SchemaOrBool"] = None + properties: Optional[Dict[str, "SchemaOrBool"]] = None + patternProperties: Optional[Dict[str, "SchemaOrBool"]] = None + additionalProperties: Optional["SchemaOrBool"] = None + propertyNames: Optional["SchemaOrBool"] = None + unevaluatedItems: Optional["SchemaOrBool"] = None + unevaluatedProperties: Optional["SchemaOrBool"] = None + # Ref: JSON Schema Validation 2020-12: https://json-schema.org/draft/2020-12/json-schema-validation.html#name-a-vocabulary-for-structural + # A Vocabulary for Structural Validation + type: Optional[str] = None + enum: Optional[List[Any]] = None + const: Optional[Any] = None + multipleOf: Optional[float] = Field(default=None, gt=0) maximum: Optional[float] = None exclusiveMaximum: Optional[float] = None minimum: Optional[float] = None @@ -115,42 +217,69 @@ class Schema(BaseModel): maxItems: Optional[int] = Field(default=None, ge=0) minItems: Optional[int] = Field(default=None, ge=0) uniqueItems: Optional[bool] = None + maxContains: Optional[int] = Field(default=None, ge=0) + minContains: Optional[int] = Field(default=None, ge=0) maxProperties: Optional[int] = Field(default=None, ge=0) minProperties: Optional[int] = Field(default=None, ge=0) required: Optional[List[str]] = None - enum: Optional[List[Any]] = None - type: Optional[str] = None - allOf: Optional[List["Schema"]] = None - oneOf: Optional[List["Schema"]] = None - anyOf: Optional[List["Schema"]] = None - not_: Optional["Schema"] = Field(default=None, alias="not") - items: Optional[Union["Schema", List["Schema"]]] = None - properties: Optional[Dict[str, "Schema"]] = None - additionalProperties: Optional[Union["Schema", Reference, bool]] = None - description: Optional[str] = None + dependentRequired: Optional[Dict[str, Set[str]]] = None + # Ref: JSON Schema Validation 2020-12: https://json-schema.org/draft/2020-12/json-schema-validation.html#name-vocabularies-for-semantic-c + # Vocabularies for Semantic Content With "format" format: Optional[str] = None + # Ref: JSON Schema Validation 2020-12: https://json-schema.org/draft/2020-12/json-schema-validation.html#name-a-vocabulary-for-the-conten + # A Vocabulary for the Contents of String-Encoded Data + contentEncoding: Optional[str] = None + contentMediaType: Optional[str] = None + contentSchema: Optional["SchemaOrBool"] = None + # Ref: JSON Schema Validation 2020-12: https://json-schema.org/draft/2020-12/json-schema-validation.html#name-a-vocabulary-for-basic-meta + # A Vocabulary for Basic Meta-Data Annotations + title: Optional[str] = None + description: Optional[str] = None default: Optional[Any] = None - nullable: Optional[bool] = None - discriminator: Optional[Discriminator] = None + deprecated: Optional[bool] = None readOnly: Optional[bool] = None writeOnly: Optional[bool] = None + examples: Optional[List[Any]] = None + # Ref: OpenAPI 3.1.0: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#schema-object + # Schema Object + discriminator: Optional[Discriminator] = None xml: Optional[XML] = None externalDocs: Optional[ExternalDocumentation] = None - example: Optional[Any] = None - deprecated: Optional[bool] = None + example: Annotated[ + Optional[Any], + typing_deprecated( + "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " + "although still supported. Use examples instead." + ), + ] = None - class Config: - extra: str = "allow" + if PYDANTIC_V2: + model_config = {"extra": "allow"} + else: -class Example(BaseModel): - summary: Optional[str] = None - description: Optional[str] = None - value: Optional[Any] = None - externalValue: Optional[AnyUrl] = None + class Config: + extra = "allow" + + +# Ref: https://json-schema.org/draft/2020-12/json-schema-core.html#name-json-schema-documents +# A JSON Schema MUST be an object or a boolean. +SchemaOrBool = Union[Schema, bool] - class Config: - extra = "allow" + +class Example(TypedDict, total=False): + summary: Optional[str] + description: Optional[str] + value: Optional[Any] + externalValue: Optional[AnyUrl] + + if PYDANTIC_V2: # type: ignore [misc] + __pydantic_config__ = {"extra": "allow"} + + else: + + class Config: + extra = "allow" class ParameterInType(Enum): @@ -167,8 +296,13 @@ class Encoding(BaseModel): explode: Optional[bool] = None allowReserved: Optional[bool] = None - class Config: - extra = "allow" + if PYDANTIC_V2: + model_config = {"extra": "allow"} + + else: + + class Config: + extra = "allow" class MediaType(BaseModel): @@ -177,8 +311,13 @@ class MediaType(BaseModel): examples: Optional[Dict[str, Union[Example, Reference]]] = None encoding: Optional[Dict[str, Encoding]] = None - class Config: - extra = "allow" + if PYDANTIC_V2: + model_config = {"extra": "allow"} + + else: + + class Config: + extra = "allow" class ParameterBase(BaseModel): @@ -195,8 +334,13 @@ class ParameterBase(BaseModel): # Serialization rules for more complex scenarios content: Optional[Dict[str, MediaType]] = None - class Config: - extra = "allow" + if PYDANTIC_V2: + model_config = {"extra": "allow"} + + else: + + class Config: + extra = "allow" class Parameter(ParameterBase): @@ -213,8 +357,13 @@ class RequestBody(BaseModel): content: Dict[str, MediaType] required: Optional[bool] = None - class Config: - extra = "allow" + if PYDANTIC_V2: + model_config = {"extra": "allow"} + + else: + + class Config: + extra = "allow" class Link(BaseModel): @@ -225,8 +374,13 @@ class Link(BaseModel): description: Optional[str] = None server: Optional[Server] = None - class Config: - extra = "allow" + if PYDANTIC_V2: + model_config = {"extra": "allow"} + + else: + + class Config: + extra = "allow" class Response(BaseModel): @@ -235,8 +389,13 @@ class Response(BaseModel): content: Optional[Dict[str, MediaType]] = None links: Optional[Dict[str, Union[Link, Reference]]] = None - class Config: - extra = "allow" + if PYDANTIC_V2: + model_config = {"extra": "allow"} + + else: + + class Config: + extra = "allow" class Operation(BaseModel): @@ -248,14 +407,19 @@ class Operation(BaseModel): parameters: Optional[List[Union[Parameter, Reference]]] = None requestBody: Optional[Union[RequestBody, Reference]] = None # Using Any for Specification Extensions - responses: Dict[str, Union[Response, Any]] + responses: Optional[Dict[str, Union[Response, Any]]] = None callbacks: Optional[Dict[str, Union[Dict[str, "PathItem"], Reference]]] = None deprecated: Optional[bool] = None security: Optional[List[Dict[str, List[str]]]] = None servers: Optional[List[Server]] = None - class Config: - extra = "allow" + if PYDANTIC_V2: + model_config = {"extra": "allow"} + + else: + + class Config: + extra = "allow" class PathItem(BaseModel): @@ -273,8 +437,13 @@ class PathItem(BaseModel): servers: Optional[List[Server]] = None parameters: Optional[List[Union[Parameter, Reference]]] = None - class Config: - extra = "allow" + if PYDANTIC_V2: + model_config = {"extra": "allow"} + + else: + + class Config: + extra = "allow" class SecuritySchemeType(Enum): @@ -288,8 +457,13 @@ class SecurityBase(BaseModel): type_: SecuritySchemeType = Field(alias="type") description: Optional[str] = None - class Config: - extra = "allow" + if PYDANTIC_V2: + model_config = {"extra": "allow"} + + else: + + class Config: + extra = "allow" class APIKeyIn(Enum): @@ -318,8 +492,13 @@ class OAuthFlow(BaseModel): refreshUrl: Optional[str] = None scopes: Dict[str, str] = {} - class Config: - extra = "allow" + if PYDANTIC_V2: + model_config = {"extra": "allow"} + + else: + + class Config: + extra = "allow" class OAuthFlowImplicit(OAuthFlow): @@ -345,8 +524,13 @@ class OAuthFlows(BaseModel): clientCredentials: Optional[OAuthFlowClientCredentials] = None authorizationCode: Optional[OAuthFlowAuthorizationCode] = None - class Config: - extra = "allow" + if PYDANTIC_V2: + model_config = {"extra": "allow"} + + else: + + class Config: + extra = "allow" class OAuth2(SecurityBase): @@ -375,9 +559,15 @@ class Components(BaseModel): links: Optional[Dict[str, Union[Link, Reference]]] = None # Using Any for Specification Extensions callbacks: Optional[Dict[str, Union[Dict[str, PathItem], Reference, Any]]] = None + pathItems: Optional[Dict[str, Union[PathItem, Reference]]] = None + + if PYDANTIC_V2: + model_config = {"extra": "allow"} + + else: - class Config: - extra = "allow" + class Config: + extra = "allow" class Tag(BaseModel): @@ -385,25 +575,37 @@ class Tag(BaseModel): description: Optional[str] = None externalDocs: Optional[ExternalDocumentation] = None - class Config: - extra = "allow" + if PYDANTIC_V2: + model_config = {"extra": "allow"} + + else: + + class Config: + extra = "allow" class OpenAPI(BaseModel): openapi: str info: Info + jsonSchemaDialect: Optional[str] = None servers: Optional[List[Server]] = None # Using Any for Specification Extensions - paths: Dict[str, Union[PathItem, Any]] + paths: Optional[Dict[str, Union[PathItem, Any]]] = None + webhooks: Optional[Dict[str, Union[PathItem, Reference]]] = None components: Optional[Components] = None security: Optional[List[Dict[str, List[str]]]] = None tags: Optional[List[Tag]] = None externalDocs: Optional[ExternalDocumentation] = None - class Config: - extra = "allow" + if PYDANTIC_V2: + model_config = {"extra": "allow"} + + else: + + class Config: + extra = "allow" -Schema.update_forward_refs() -Operation.update_forward_refs() -Encoding.update_forward_refs() +_model_rebuild(Schema) +_model_rebuild(Operation) +_model_rebuild(Encoding) diff --git a/fastapi/openapi/utils.py b/fastapi/openapi/utils.py index 6d736647b5b03..5bfb5acef7fc4 100644 --- a/fastapi/openapi/utils.py +++ b/fastapi/openapi/utils.py @@ -1,35 +1,37 @@ import http.client import inspect import warnings -from enum import Enum from typing import Any, Dict, List, Optional, Sequence, Set, Tuple, Type, Union, cast from fastapi import routing +from fastapi._compat import ( + GenerateJsonSchema, + JsonSchemaValue, + ModelField, + Undefined, + get_compat_model_name_map, + get_definitions, + get_schema_from_model_field, + lenient_issubclass, +) from fastapi.datastructures import DefaultPlaceholder from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import get_flat_dependant, get_flat_params from fastapi.encoders import jsonable_encoder -from fastapi.openapi.constants import METHODS_WITH_BODY, REF_PREFIX +from fastapi.openapi.constants import METHODS_WITH_BODY, REF_PREFIX, REF_TEMPLATE from fastapi.openapi.models import OpenAPI from fastapi.params import Body, Param from fastapi.responses import Response +from fastapi.types import ModelNameMap from fastapi.utils import ( deep_dict_update, generate_operation_id_for_path, - get_model_definitions, is_body_allowed_for_status_code, ) -from pydantic import BaseModel -from pydantic.fields import ModelField, Undefined -from pydantic.schema import ( - field_schema, - get_flat_models_from_fields, - get_model_name_map, -) -from pydantic.utils import lenient_issubclass from starlette.responses import JSONResponse from starlette.routing import BaseRoute from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY +from typing_extensions import Literal validation_error_definition = { "title": "ValidationError", @@ -88,7 +90,12 @@ def get_openapi_security_definitions( def get_openapi_operation_parameters( *, all_route_params: Sequence[ModelField], - model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], + schema_generator: GenerateJsonSchema, + model_name_map: ModelNameMap, + field_mapping: Dict[ + Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue + ], + separate_input_output_schemas: bool = True, ) -> List[Dict[str, Any]]: parameters = [] for param in all_route_params: @@ -96,18 +103,23 @@ def get_openapi_operation_parameters( field_info = cast(Param, field_info) if not field_info.include_in_schema: continue + param_schema = get_schema_from_model_field( + field=param, + schema_generator=schema_generator, + model_name_map=model_name_map, + field_mapping=field_mapping, + separate_input_output_schemas=separate_input_output_schemas, + ) parameter = { "name": param.alias, "in": field_info.in_.value, "required": param.required, - "schema": field_schema( - param, model_name_map=model_name_map, ref_prefix=REF_PREFIX - )[0], + "schema": param_schema, } if field_info.description: parameter["description"] = field_info.description - if field_info.examples: - parameter["examples"] = jsonable_encoder(field_info.examples) + if field_info.openapi_examples: + parameter["examples"] = jsonable_encoder(field_info.openapi_examples) elif field_info.example != Undefined: parameter["example"] = jsonable_encoder(field_info.example) if field_info.deprecated: @@ -119,13 +131,22 @@ def get_openapi_operation_parameters( def get_openapi_operation_request_body( *, body_field: Optional[ModelField], - model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], + schema_generator: GenerateJsonSchema, + model_name_map: ModelNameMap, + field_mapping: Dict[ + Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue + ], + separate_input_output_schemas: bool = True, ) -> Optional[Dict[str, Any]]: if not body_field: return None assert isinstance(body_field, ModelField) - body_schema, _, _ = field_schema( - body_field, model_name_map=model_name_map, ref_prefix=REF_PREFIX + body_schema = get_schema_from_model_field( + field=body_field, + schema_generator=schema_generator, + model_name_map=model_name_map, + field_mapping=field_mapping, + separate_input_output_schemas=separate_input_output_schemas, ) field_info = cast(Body, body_field.field_info) request_media_type = field_info.media_type @@ -134,8 +155,10 @@ def get_openapi_operation_request_body( if required: request_body_oai["required"] = required request_media_content: Dict[str, Any] = {"schema": body_schema} - if field_info.examples: - request_media_content["examples"] = jsonable_encoder(field_info.examples) + if field_info.openapi_examples: + request_media_content["examples"] = jsonable_encoder( + field_info.openapi_examples + ) elif field_info.example != Undefined: request_media_content["example"] = jsonable_encoder(field_info.example) request_body_oai["content"] = {request_media_type: request_media_content} @@ -190,7 +213,15 @@ def get_openapi_operation_metadata( def get_openapi_path( - *, route: routing.APIRoute, model_name_map: Dict[type, str], operation_ids: Set[str] + *, + route: routing.APIRoute, + operation_ids: Set[str], + schema_generator: GenerateJsonSchema, + model_name_map: ModelNameMap, + field_mapping: Dict[ + Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue + ], + separate_input_output_schemas: bool = True, ) -> Tuple[Dict[str, Any], Dict[str, Any], Dict[str, Any]]: path = {} security_schemes: Dict[str, Any] = {} @@ -218,7 +249,11 @@ def get_openapi_path( security_schemes.update(security_definitions) all_route_params = get_flat_params(route.dependant) operation_parameters = get_openapi_operation_parameters( - all_route_params=all_route_params, model_name_map=model_name_map + all_route_params=all_route_params, + schema_generator=schema_generator, + model_name_map=model_name_map, + field_mapping=field_mapping, + separate_input_output_schemas=separate_input_output_schemas, ) parameters.extend(operation_parameters) if parameters: @@ -236,7 +271,11 @@ def get_openapi_path( operation["parameters"] = list(all_parameters.values()) if method in METHODS_WITH_BODY: request_body_oai = get_openapi_operation_request_body( - body_field=route.body_field, model_name_map=model_name_map + body_field=route.body_field, + schema_generator=schema_generator, + model_name_map=model_name_map, + field_mapping=field_mapping, + separate_input_output_schemas=separate_input_output_schemas, ) if request_body_oai: operation["requestBody"] = request_body_oai @@ -250,8 +289,11 @@ def get_openapi_path( cb_definitions, ) = get_openapi_path( route=callback, - model_name_map=model_name_map, operation_ids=operation_ids, + schema_generator=schema_generator, + model_name_map=model_name_map, + field_mapping=field_mapping, + separate_input_output_schemas=separate_input_output_schemas, ) callbacks[callback.name] = {callback.path: cb_path} operation["callbacks"] = callbacks @@ -277,10 +319,12 @@ def get_openapi_path( response_schema = {"type": "string"} if lenient_issubclass(current_response_class, JSONResponse): if route.response_field: - response_schema, _, _ = field_schema( - route.response_field, + response_schema = get_schema_from_model_field( + field=route.response_field, + schema_generator=schema_generator, model_name_map=model_name_map, - ref_prefix=REF_PREFIX, + field_mapping=field_mapping, + separate_input_output_schemas=separate_input_output_schemas, ) else: response_schema = {} @@ -309,8 +353,12 @@ def get_openapi_path( field = route.response_fields.get(additional_status_code) additional_field_schema: Optional[Dict[str, Any]] = None if field: - additional_field_schema, _, _ = field_schema( - field, model_name_map=model_name_map, ref_prefix=REF_PREFIX + additional_field_schema = get_schema_from_model_field( + field=field, + schema_generator=schema_generator, + model_name_map=model_name_map, + field_mapping=field_mapping, + separate_input_output_schemas=separate_input_output_schemas, ) media_type = route_response_media_type or "application/json" additional_schema = ( @@ -356,13 +404,13 @@ def get_openapi_path( return path, security_schemes, definitions -def get_flat_models_from_routes( +def get_fields_from_routes( routes: Sequence[BaseRoute], -) -> Set[Union[Type[BaseModel], Type[Enum]]]: +) -> List[ModelField]: body_fields_from_routes: List[ModelField] = [] responses_from_routes: List[ModelField] = [] request_fields_from_routes: List[ModelField] = [] - callback_flat_models: Set[Union[Type[BaseModel], Type[Enum]]] = set() + callback_flat_models: List[ModelField] = [] for route in routes: if getattr(route, "include_in_schema", None) and isinstance( route, routing.APIRoute @@ -377,13 +425,12 @@ def get_flat_models_from_routes( if route.response_fields: responses_from_routes.extend(route.response_fields.values()) if route.callbacks: - callback_flat_models |= get_flat_models_from_routes(route.callbacks) + callback_flat_models.extend(get_fields_from_routes(route.callbacks)) params = get_flat_params(route.dependant) request_fields_from_routes.extend(params) - flat_models = callback_flat_models | get_flat_models_from_fields( - body_fields_from_routes + responses_from_routes + request_fields_from_routes, - known_models=set(), + flat_models = callback_flat_models + list( + body_fields_from_routes + responses_from_routes + request_fields_from_routes ) return flat_models @@ -392,16 +439,21 @@ def get_openapi( *, title: str, version: str, - openapi_version: str = "3.0.2", + openapi_version: str = "3.1.0", + summary: Optional[str] = None, description: Optional[str] = None, routes: Sequence[BaseRoute], + webhooks: Optional[Sequence[BaseRoute]] = None, tags: Optional[List[Dict[str, Any]]] = None, servers: Optional[List[Dict[str, Union[str, Any]]]] = None, terms_of_service: Optional[str] = None, contact: Optional[Dict[str, Union[str, Any]]] = None, license_info: Optional[Dict[str, Union[str, Any]]] = None, + separate_input_output_schemas: bool = True, ) -> Dict[str, Any]: info: Dict[str, Any] = {"title": title, "version": version} + if summary: + info["summary"] = summary if description: info["description"] = description if terms_of_service: @@ -415,16 +467,26 @@ def get_openapi( output["servers"] = servers components: Dict[str, Dict[str, Any]] = {} paths: Dict[str, Dict[str, Any]] = {} + webhook_paths: Dict[str, Dict[str, Any]] = {} operation_ids: Set[str] = set() - flat_models = get_flat_models_from_routes(routes) - model_name_map = get_model_name_map(flat_models) - definitions = get_model_definitions( - flat_models=flat_models, model_name_map=model_name_map + all_fields = get_fields_from_routes(list(routes or []) + list(webhooks or [])) + model_name_map = get_compat_model_name_map(all_fields) + schema_generator = GenerateJsonSchema(ref_template=REF_TEMPLATE) + field_mapping, definitions = get_definitions( + fields=all_fields, + schema_generator=schema_generator, + model_name_map=model_name_map, + separate_input_output_schemas=separate_input_output_schemas, ) - for route in routes: + for route in routes or []: if isinstance(route, routing.APIRoute): result = get_openapi_path( - route=route, model_name_map=model_name_map, operation_ids=operation_ids + route=route, + operation_ids=operation_ids, + schema_generator=schema_generator, + model_name_map=model_name_map, + field_mapping=field_mapping, + separate_input_output_schemas=separate_input_output_schemas, ) if result: path, security_schemes, path_definitions = result @@ -436,11 +498,33 @@ def get_openapi( ) if path_definitions: definitions.update(path_definitions) + for webhook in webhooks or []: + if isinstance(webhook, routing.APIRoute): + result = get_openapi_path( + route=webhook, + operation_ids=operation_ids, + schema_generator=schema_generator, + model_name_map=model_name_map, + field_mapping=field_mapping, + separate_input_output_schemas=separate_input_output_schemas, + ) + if result: + path, security_schemes, path_definitions = result + if path: + webhook_paths.setdefault(webhook.path_format, {}).update(path) + if security_schemes: + components.setdefault("securitySchemes", {}).update( + security_schemes + ) + if path_definitions: + definitions.update(path_definitions) if definitions: components["schemas"] = {k: definitions[k] for k in sorted(definitions)} if components: output["components"] = components output["paths"] = paths + if webhook_paths: + output["webhooks"] = webhook_paths if tags: output["tags"] = tags return jsonable_encoder(OpenAPI(**output), by_alias=True, exclude_none=True) # type: ignore diff --git a/fastapi/param_functions.py b/fastapi/param_functions.py index 75f054e9dcbf5..3f6dbc959d895 100644 --- a/fastapi/param_functions.py +++ b/fastapi/param_functions.py @@ -1,31 +1,315 @@ -from typing import Any, Callable, Dict, Optional, Sequence +from typing import Any, Callable, Dict, List, Optional, Sequence, Union from fastapi import params -from pydantic.fields import Undefined +from fastapi._compat import Undefined +from fastapi.openapi.models import Example +from typing_extensions import Annotated, Doc, deprecated # type: ignore [attr-defined] + +_Unset: Any = Undefined def Path( # noqa: N802 - default: Any = ..., + default: Annotated[ + Any, + Doc( + """ + Default value if the parameter field is not set. + + This doesn't affect `Path` parameters as the value is always required. + The parameter is available only for compatibility. + """ + ), + ] = ..., *, - alias: Optional[str] = None, - title: Optional[str] = None, - description: Optional[str] = None, - gt: Optional[float] = None, - ge: Optional[float] = None, - lt: Optional[float] = None, - le: Optional[float] = None, - min_length: Optional[int] = None, - max_length: Optional[int] = None, - regex: Optional[str] = None, - example: Any = Undefined, - examples: Optional[Dict[str, Any]] = None, - deprecated: Optional[bool] = None, - include_in_schema: bool = True, - **extra: Any, + default_factory: Annotated[ + Union[Callable[[], Any], None], + Doc( + """ + A callable to generate the default value. + + This doesn't affect `Path` parameters as the value is always required. + The parameter is available only for compatibility. + """ + ), + ] = _Unset, + alias: Annotated[ + Optional[str], + Doc( + """ + An alternative name for the parameter field. + + This will be used to extract the data and for the generated OpenAPI. + It is particularly useful when you can't use the name you want because it + is a Python reserved keyword or similar. + """ + ), + ] = None, + alias_priority: Annotated[ + Union[int, None], + Doc( + """ + Priority of the alias. This affects whether an alias generator is used. + """ + ), + ] = _Unset, + # TODO: update when deprecating Pydantic v1, import these types + # validation_alias: str | AliasPath | AliasChoices | None + validation_alias: Annotated[ + Union[str, None], + Doc( + """ + 'Whitelist' validation step. The parameter field will be the single one + allowed by the alias or set of aliases defined. + """ + ), + ] = None, + serialization_alias: Annotated[ + Union[str, None], + Doc( + """ + 'Blacklist' validation step. The vanilla parameter field will be the + single one of the alias' or set of aliases' fields and all the other + fields will be ignored at serialization time. + """ + ), + ] = None, + title: Annotated[ + Optional[str], + Doc( + """ + Human-readable title. + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + Human-readable description. + """ + ), + ] = None, + gt: Annotated[ + Optional[float], + Doc( + """ + Greater than. If set, value must be greater than this. Only applicable to + numbers. + """ + ), + ] = None, + ge: Annotated[ + Optional[float], + Doc( + """ + Greater than or equal. If set, value must be greater than or equal to + this. Only applicable to numbers. + """ + ), + ] = None, + lt: Annotated[ + Optional[float], + Doc( + """ + Less than. If set, value must be less than this. Only applicable to numbers. + """ + ), + ] = None, + le: Annotated[ + Optional[float], + Doc( + """ + Less than or equal. If set, value must be less than or equal to this. + Only applicable to numbers. + """ + ), + ] = None, + min_length: Annotated[ + Optional[int], + Doc( + """ + Minimum length for strings. + """ + ), + ] = None, + max_length: Annotated[ + Optional[int], + Doc( + """ + Maximum length for strings. + """ + ), + ] = None, + pattern: Annotated[ + Optional[str], + Doc( + """ + RegEx pattern for strings. + """ + ), + ] = None, + regex: Annotated[ + Optional[str], + Doc( + """ + RegEx pattern for strings. + """ + ), + deprecated( + "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." + ), + ] = None, + discriminator: Annotated[ + Union[str, None], + Doc( + """ + Parameter field name for discriminating the type in a tagged union. + """ + ), + ] = None, + strict: Annotated[ + Union[bool, None], + Doc( + """ + If `True`, strict validation is applied to the field. + """ + ), + ] = _Unset, + multiple_of: Annotated[ + Union[float, None], + Doc( + """ + Value must be a multiple of this. Only applicable to numbers. + """ + ), + ] = _Unset, + allow_inf_nan: Annotated[ + Union[bool, None], + Doc( + """ + Allow `inf`, `-inf`, `nan`. Only applicable to numbers. + """ + ), + ] = _Unset, + max_digits: Annotated[ + Union[int, None], + Doc( + """ + Maximum number of allow digits for strings. + """ + ), + ] = _Unset, + decimal_places: Annotated[ + Union[int, None], + Doc( + """ + Maximum number of decimal places allowed for numbers. + """ + ), + ] = _Unset, + examples: Annotated[ + Optional[List[Any]], + Doc( + """ + Example values for this field. + """ + ), + ] = None, + example: Annotated[ + Optional[Any], + deprecated( + "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " + "although still supported. Use examples instead." + ), + ] = _Unset, + openapi_examples: Annotated[ + Optional[Dict[str, Example]], + Doc( + """ + OpenAPI-specific examples. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Swagger UI (that provides the `/docs` interface) has better support for the + OpenAPI-specific examples than the JSON Schema `examples`, that's the main + use case for this. + + Read more about it in the + [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter). + """ + ), + ] = None, + deprecated: Annotated[ + Optional[bool], + Doc( + """ + Mark this parameter field as deprecated. + + It will affect the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + include_in_schema: Annotated[ + bool, + Doc( + """ + To include (or not) this parameter field in the generated OpenAPI. + You probably don't need it, but it's available. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = True, + json_schema_extra: Annotated[ + Union[Dict[str, Any], None], + Doc( + """ + Any additional JSON schema data. + """ + ), + ] = None, + **extra: Annotated[ + Any, + Doc( + """ + Include extra fields used by the JSON Schema. + """ + ), + deprecated( + """ + The `extra` kwargs is deprecated. Use `json_schema_extra` instead. + """ + ), + ], ) -> Any: + """ + Declare a path parameter for a *path operation*. + + Read more about it in the + [FastAPI docs for Path Parameters and Numeric Validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/). + + ```python + from typing import Annotated + + from fastapi import FastAPI, Path + + app = FastAPI() + + + @app.get("/items/{item_id}") + async def read_items( + item_id: Annotated[int, Path(title="The ID of the item to get")], + ): + return {"item_id": item_id} + ``` + """ return params.Path( default=default, + default_factory=default_factory, alias=alias, + alias_priority=alias_priority, + validation_alias=validation_alias, + serialization_alias=serialization_alias, title=title, description=description, gt=gt, @@ -34,37 +318,302 @@ def Path( # noqa: N802 le=le, min_length=min_length, max_length=max_length, + pattern=pattern, regex=regex, + discriminator=discriminator, + strict=strict, + multiple_of=multiple_of, + allow_inf_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, example=example, examples=examples, + openapi_examples=openapi_examples, deprecated=deprecated, include_in_schema=include_in_schema, + json_schema_extra=json_schema_extra, **extra, ) def Query( # noqa: N802 - default: Any = Undefined, + default: Annotated[ + Any, + Doc( + """ + Default value if the parameter field is not set. + """ + ), + ] = Undefined, *, - alias: Optional[str] = None, - title: Optional[str] = None, - description: Optional[str] = None, - gt: Optional[float] = None, - ge: Optional[float] = None, - lt: Optional[float] = None, - le: Optional[float] = None, - min_length: Optional[int] = None, - max_length: Optional[int] = None, - regex: Optional[str] = None, - example: Any = Undefined, - examples: Optional[Dict[str, Any]] = None, - deprecated: Optional[bool] = None, - include_in_schema: bool = True, - **extra: Any, + default_factory: Annotated[ + Union[Callable[[], Any], None], + Doc( + """ + A callable to generate the default value. + + This doesn't affect `Path` parameters as the value is always required. + The parameter is available only for compatibility. + """ + ), + ] = _Unset, + alias: Annotated[ + Optional[str], + Doc( + """ + An alternative name for the parameter field. + + This will be used to extract the data and for the generated OpenAPI. + It is particularly useful when you can't use the name you want because it + is a Python reserved keyword or similar. + """ + ), + ] = None, + alias_priority: Annotated[ + Union[int, None], + Doc( + """ + Priority of the alias. This affects whether an alias generator is used. + """ + ), + ] = _Unset, + # TODO: update when deprecating Pydantic v1, import these types + # validation_alias: str | AliasPath | AliasChoices | None + validation_alias: Annotated[ + Union[str, None], + Doc( + """ + 'Whitelist' validation step. The parameter field will be the single one + allowed by the alias or set of aliases defined. + """ + ), + ] = None, + serialization_alias: Annotated[ + Union[str, None], + Doc( + """ + 'Blacklist' validation step. The vanilla parameter field will be the + single one of the alias' or set of aliases' fields and all the other + fields will be ignored at serialization time. + """ + ), + ] = None, + title: Annotated[ + Optional[str], + Doc( + """ + Human-readable title. + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + Human-readable description. + """ + ), + ] = None, + gt: Annotated[ + Optional[float], + Doc( + """ + Greater than. If set, value must be greater than this. Only applicable to + numbers. + """ + ), + ] = None, + ge: Annotated[ + Optional[float], + Doc( + """ + Greater than or equal. If set, value must be greater than or equal to + this. Only applicable to numbers. + """ + ), + ] = None, + lt: Annotated[ + Optional[float], + Doc( + """ + Less than. If set, value must be less than this. Only applicable to numbers. + """ + ), + ] = None, + le: Annotated[ + Optional[float], + Doc( + """ + Less than or equal. If set, value must be less than or equal to this. + Only applicable to numbers. + """ + ), + ] = None, + min_length: Annotated[ + Optional[int], + Doc( + """ + Minimum length for strings. + """ + ), + ] = None, + max_length: Annotated[ + Optional[int], + Doc( + """ + Maximum length for strings. + """ + ), + ] = None, + pattern: Annotated[ + Optional[str], + Doc( + """ + RegEx pattern for strings. + """ + ), + ] = None, + regex: Annotated[ + Optional[str], + Doc( + """ + RegEx pattern for strings. + """ + ), + deprecated( + "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." + ), + ] = None, + discriminator: Annotated[ + Union[str, None], + Doc( + """ + Parameter field name for discriminating the type in a tagged union. + """ + ), + ] = None, + strict: Annotated[ + Union[bool, None], + Doc( + """ + If `True`, strict validation is applied to the field. + """ + ), + ] = _Unset, + multiple_of: Annotated[ + Union[float, None], + Doc( + """ + Value must be a multiple of this. Only applicable to numbers. + """ + ), + ] = _Unset, + allow_inf_nan: Annotated[ + Union[bool, None], + Doc( + """ + Allow `inf`, `-inf`, `nan`. Only applicable to numbers. + """ + ), + ] = _Unset, + max_digits: Annotated[ + Union[int, None], + Doc( + """ + Maximum number of allow digits for strings. + """ + ), + ] = _Unset, + decimal_places: Annotated[ + Union[int, None], + Doc( + """ + Maximum number of decimal places allowed for numbers. + """ + ), + ] = _Unset, + examples: Annotated[ + Optional[List[Any]], + Doc( + """ + Example values for this field. + """ + ), + ] = None, + example: Annotated[ + Optional[Any], + deprecated( + "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " + "although still supported. Use examples instead." + ), + ] = _Unset, + openapi_examples: Annotated[ + Optional[Dict[str, Example]], + Doc( + """ + OpenAPI-specific examples. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Swagger UI (that provides the `/docs` interface) has better support for the + OpenAPI-specific examples than the JSON Schema `examples`, that's the main + use case for this. + + Read more about it in the + [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter). + """ + ), + ] = None, + deprecated: Annotated[ + Optional[bool], + Doc( + """ + Mark this parameter field as deprecated. + + It will affect the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + include_in_schema: Annotated[ + bool, + Doc( + """ + To include (or not) this parameter field in the generated OpenAPI. + You probably don't need it, but it's available. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = True, + json_schema_extra: Annotated[ + Union[Dict[str, Any], None], + Doc( + """ + Any additional JSON schema data. + """ + ), + ] = None, + **extra: Annotated[ + Any, + Doc( + """ + Include extra fields used by the JSON Schema. + """ + ), + deprecated( + """ + The `extra` kwargs is deprecated. Use `json_schema_extra` instead. + """ + ), + ], ) -> Any: return params.Query( default=default, + default_factory=default_factory, alias=alias, + alias_priority=alias_priority, + validation_alias=validation_alias, + serialization_alias=serialization_alias, title=title, description=description, gt=gt, @@ -73,38 +622,313 @@ def Query( # noqa: N802 le=le, min_length=min_length, max_length=max_length, + pattern=pattern, regex=regex, + discriminator=discriminator, + strict=strict, + multiple_of=multiple_of, + allow_inf_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, example=example, examples=examples, + openapi_examples=openapi_examples, deprecated=deprecated, include_in_schema=include_in_schema, + json_schema_extra=json_schema_extra, **extra, ) def Header( # noqa: N802 - default: Any = Undefined, + default: Annotated[ + Any, + Doc( + """ + Default value if the parameter field is not set. + """ + ), + ] = Undefined, *, - alias: Optional[str] = None, - convert_underscores: bool = True, - title: Optional[str] = None, - description: Optional[str] = None, - gt: Optional[float] = None, - ge: Optional[float] = None, - lt: Optional[float] = None, - le: Optional[float] = None, - min_length: Optional[int] = None, - max_length: Optional[int] = None, - regex: Optional[str] = None, - example: Any = Undefined, - examples: Optional[Dict[str, Any]] = None, - deprecated: Optional[bool] = None, - include_in_schema: bool = True, - **extra: Any, + default_factory: Annotated[ + Union[Callable[[], Any], None], + Doc( + """ + A callable to generate the default value. + + This doesn't affect `Path` parameters as the value is always required. + The parameter is available only for compatibility. + """ + ), + ] = _Unset, + alias: Annotated[ + Optional[str], + Doc( + """ + An alternative name for the parameter field. + + This will be used to extract the data and for the generated OpenAPI. + It is particularly useful when you can't use the name you want because it + is a Python reserved keyword or similar. + """ + ), + ] = None, + alias_priority: Annotated[ + Union[int, None], + Doc( + """ + Priority of the alias. This affects whether an alias generator is used. + """ + ), + ] = _Unset, + # TODO: update when deprecating Pydantic v1, import these types + # validation_alias: str | AliasPath | AliasChoices | None + validation_alias: Annotated[ + Union[str, None], + Doc( + """ + 'Whitelist' validation step. The parameter field will be the single one + allowed by the alias or set of aliases defined. + """ + ), + ] = None, + serialization_alias: Annotated[ + Union[str, None], + Doc( + """ + 'Blacklist' validation step. The vanilla parameter field will be the + single one of the alias' or set of aliases' fields and all the other + fields will be ignored at serialization time. + """ + ), + ] = None, + convert_underscores: Annotated[ + bool, + Doc( + """ + Automatically convert underscores to hyphens in the parameter field name. + + Read more about it in the + [FastAPI docs for Header Parameters](https://fastapi.tiangolo.com/tutorial/header-params/#automatic-conversion) + """ + ), + ] = True, + title: Annotated[ + Optional[str], + Doc( + """ + Human-readable title. + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + Human-readable description. + """ + ), + ] = None, + gt: Annotated[ + Optional[float], + Doc( + """ + Greater than. If set, value must be greater than this. Only applicable to + numbers. + """ + ), + ] = None, + ge: Annotated[ + Optional[float], + Doc( + """ + Greater than or equal. If set, value must be greater than or equal to + this. Only applicable to numbers. + """ + ), + ] = None, + lt: Annotated[ + Optional[float], + Doc( + """ + Less than. If set, value must be less than this. Only applicable to numbers. + """ + ), + ] = None, + le: Annotated[ + Optional[float], + Doc( + """ + Less than or equal. If set, value must be less than or equal to this. + Only applicable to numbers. + """ + ), + ] = None, + min_length: Annotated[ + Optional[int], + Doc( + """ + Minimum length for strings. + """ + ), + ] = None, + max_length: Annotated[ + Optional[int], + Doc( + """ + Maximum length for strings. + """ + ), + ] = None, + pattern: Annotated[ + Optional[str], + Doc( + """ + RegEx pattern for strings. + """ + ), + ] = None, + regex: Annotated[ + Optional[str], + Doc( + """ + RegEx pattern for strings. + """ + ), + deprecated( + "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." + ), + ] = None, + discriminator: Annotated[ + Union[str, None], + Doc( + """ + Parameter field name for discriminating the type in a tagged union. + """ + ), + ] = None, + strict: Annotated[ + Union[bool, None], + Doc( + """ + If `True`, strict validation is applied to the field. + """ + ), + ] = _Unset, + multiple_of: Annotated[ + Union[float, None], + Doc( + """ + Value must be a multiple of this. Only applicable to numbers. + """ + ), + ] = _Unset, + allow_inf_nan: Annotated[ + Union[bool, None], + Doc( + """ + Allow `inf`, `-inf`, `nan`. Only applicable to numbers. + """ + ), + ] = _Unset, + max_digits: Annotated[ + Union[int, None], + Doc( + """ + Maximum number of allow digits for strings. + """ + ), + ] = _Unset, + decimal_places: Annotated[ + Union[int, None], + Doc( + """ + Maximum number of decimal places allowed for numbers. + """ + ), + ] = _Unset, + examples: Annotated[ + Optional[List[Any]], + Doc( + """ + Example values for this field. + """ + ), + ] = None, + example: Annotated[ + Optional[Any], + deprecated( + "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " + "although still supported. Use examples instead." + ), + ] = _Unset, + openapi_examples: Annotated[ + Optional[Dict[str, Example]], + Doc( + """ + OpenAPI-specific examples. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Swagger UI (that provides the `/docs` interface) has better support for the + OpenAPI-specific examples than the JSON Schema `examples`, that's the main + use case for this. + + Read more about it in the + [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter). + """ + ), + ] = None, + deprecated: Annotated[ + Optional[bool], + Doc( + """ + Mark this parameter field as deprecated. + + It will affect the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + include_in_schema: Annotated[ + bool, + Doc( + """ + To include (or not) this parameter field in the generated OpenAPI. + You probably don't need it, but it's available. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = True, + json_schema_extra: Annotated[ + Union[Dict[str, Any], None], + Doc( + """ + Any additional JSON schema data. + """ + ), + ] = None, + **extra: Annotated[ + Any, + Doc( + """ + Include extra fields used by the JSON Schema. + """ + ), + deprecated( + """ + The `extra` kwargs is deprecated. Use `json_schema_extra` instead. + """ + ), + ], ) -> Any: return params.Header( default=default, + default_factory=default_factory, alias=alias, + alias_priority=alias_priority, + validation_alias=validation_alias, + serialization_alias=serialization_alias, convert_underscores=convert_underscores, title=title, description=description, @@ -114,37 +938,302 @@ def Header( # noqa: N802 le=le, min_length=min_length, max_length=max_length, + pattern=pattern, regex=regex, + discriminator=discriminator, + strict=strict, + multiple_of=multiple_of, + allow_inf_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, example=example, examples=examples, + openapi_examples=openapi_examples, deprecated=deprecated, include_in_schema=include_in_schema, + json_schema_extra=json_schema_extra, **extra, ) def Cookie( # noqa: N802 - default: Any = Undefined, + default: Annotated[ + Any, + Doc( + """ + Default value if the parameter field is not set. + """ + ), + ] = Undefined, *, - alias: Optional[str] = None, - title: Optional[str] = None, - description: Optional[str] = None, - gt: Optional[float] = None, - ge: Optional[float] = None, - lt: Optional[float] = None, - le: Optional[float] = None, - min_length: Optional[int] = None, - max_length: Optional[int] = None, - regex: Optional[str] = None, - example: Any = Undefined, - examples: Optional[Dict[str, Any]] = None, - deprecated: Optional[bool] = None, - include_in_schema: bool = True, - **extra: Any, + default_factory: Annotated[ + Union[Callable[[], Any], None], + Doc( + """ + A callable to generate the default value. + + This doesn't affect `Path` parameters as the value is always required. + The parameter is available only for compatibility. + """ + ), + ] = _Unset, + alias: Annotated[ + Optional[str], + Doc( + """ + An alternative name for the parameter field. + + This will be used to extract the data and for the generated OpenAPI. + It is particularly useful when you can't use the name you want because it + is a Python reserved keyword or similar. + """ + ), + ] = None, + alias_priority: Annotated[ + Union[int, None], + Doc( + """ + Priority of the alias. This affects whether an alias generator is used. + """ + ), + ] = _Unset, + # TODO: update when deprecating Pydantic v1, import these types + # validation_alias: str | AliasPath | AliasChoices | None + validation_alias: Annotated[ + Union[str, None], + Doc( + """ + 'Whitelist' validation step. The parameter field will be the single one + allowed by the alias or set of aliases defined. + """ + ), + ] = None, + serialization_alias: Annotated[ + Union[str, None], + Doc( + """ + 'Blacklist' validation step. The vanilla parameter field will be the + single one of the alias' or set of aliases' fields and all the other + fields will be ignored at serialization time. + """ + ), + ] = None, + title: Annotated[ + Optional[str], + Doc( + """ + Human-readable title. + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + Human-readable description. + """ + ), + ] = None, + gt: Annotated[ + Optional[float], + Doc( + """ + Greater than. If set, value must be greater than this. Only applicable to + numbers. + """ + ), + ] = None, + ge: Annotated[ + Optional[float], + Doc( + """ + Greater than or equal. If set, value must be greater than or equal to + this. Only applicable to numbers. + """ + ), + ] = None, + lt: Annotated[ + Optional[float], + Doc( + """ + Less than. If set, value must be less than this. Only applicable to numbers. + """ + ), + ] = None, + le: Annotated[ + Optional[float], + Doc( + """ + Less than or equal. If set, value must be less than or equal to this. + Only applicable to numbers. + """ + ), + ] = None, + min_length: Annotated[ + Optional[int], + Doc( + """ + Minimum length for strings. + """ + ), + ] = None, + max_length: Annotated[ + Optional[int], + Doc( + """ + Maximum length for strings. + """ + ), + ] = None, + pattern: Annotated[ + Optional[str], + Doc( + """ + RegEx pattern for strings. + """ + ), + ] = None, + regex: Annotated[ + Optional[str], + Doc( + """ + RegEx pattern for strings. + """ + ), + deprecated( + "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." + ), + ] = None, + discriminator: Annotated[ + Union[str, None], + Doc( + """ + Parameter field name for discriminating the type in a tagged union. + """ + ), + ] = None, + strict: Annotated[ + Union[bool, None], + Doc( + """ + If `True`, strict validation is applied to the field. + """ + ), + ] = _Unset, + multiple_of: Annotated[ + Union[float, None], + Doc( + """ + Value must be a multiple of this. Only applicable to numbers. + """ + ), + ] = _Unset, + allow_inf_nan: Annotated[ + Union[bool, None], + Doc( + """ + Allow `inf`, `-inf`, `nan`. Only applicable to numbers. + """ + ), + ] = _Unset, + max_digits: Annotated[ + Union[int, None], + Doc( + """ + Maximum number of allow digits for strings. + """ + ), + ] = _Unset, + decimal_places: Annotated[ + Union[int, None], + Doc( + """ + Maximum number of decimal places allowed for numbers. + """ + ), + ] = _Unset, + examples: Annotated[ + Optional[List[Any]], + Doc( + """ + Example values for this field. + """ + ), + ] = None, + example: Annotated[ + Optional[Any], + deprecated( + "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " + "although still supported. Use examples instead." + ), + ] = _Unset, + openapi_examples: Annotated[ + Optional[Dict[str, Example]], + Doc( + """ + OpenAPI-specific examples. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Swagger UI (that provides the `/docs` interface) has better support for the + OpenAPI-specific examples than the JSON Schema `examples`, that's the main + use case for this. + + Read more about it in the + [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter). + """ + ), + ] = None, + deprecated: Annotated[ + Optional[bool], + Doc( + """ + Mark this parameter field as deprecated. + + It will affect the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + include_in_schema: Annotated[ + bool, + Doc( + """ + To include (or not) this parameter field in the generated OpenAPI. + You probably don't need it, but it's available. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = True, + json_schema_extra: Annotated[ + Union[Dict[str, Any], None], + Doc( + """ + Any additional JSON schema data. + """ + ), + ] = None, + **extra: Annotated[ + Any, + Doc( + """ + Include extra fields used by the JSON Schema. + """ + ), + deprecated( + """ + The `extra` kwargs is deprecated. Use `json_schema_extra` instead. + """ + ), + ], ) -> Any: return params.Cookie( default=default, + default_factory=default_factory, alias=alias, + alias_priority=alias_priority, + validation_alias=validation_alias, + serialization_alias=serialization_alias, title=title, description=description, gt=gt, @@ -153,39 +1242,327 @@ def Cookie( # noqa: N802 le=le, min_length=min_length, max_length=max_length, + pattern=pattern, regex=regex, + discriminator=discriminator, + strict=strict, + multiple_of=multiple_of, + allow_inf_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, example=example, examples=examples, + openapi_examples=openapi_examples, deprecated=deprecated, include_in_schema=include_in_schema, + json_schema_extra=json_schema_extra, **extra, ) def Body( # noqa: N802 - default: Any = Undefined, + default: Annotated[ + Any, + Doc( + """ + Default value if the parameter field is not set. + """ + ), + ] = Undefined, *, - embed: bool = False, - media_type: str = "application/json", - alias: Optional[str] = None, - title: Optional[str] = None, - description: Optional[str] = None, - gt: Optional[float] = None, - ge: Optional[float] = None, - lt: Optional[float] = None, - le: Optional[float] = None, - min_length: Optional[int] = None, - max_length: Optional[int] = None, - regex: Optional[str] = None, - example: Any = Undefined, - examples: Optional[Dict[str, Any]] = None, - **extra: Any, + default_factory: Annotated[ + Union[Callable[[], Any], None], + Doc( + """ + A callable to generate the default value. + + This doesn't affect `Path` parameters as the value is always required. + The parameter is available only for compatibility. + """ + ), + ] = _Unset, + embed: Annotated[ + bool, + Doc( + """ + When `embed` is `True`, the parameter will be expected in a JSON body as a + key instead of being the JSON body itself. + + This happens automatically when more than one `Body` parameter is declared. + + Read more about it in the + [FastAPI docs for Body - Multiple Parameters](https://fastapi.tiangolo.com/tutorial/body-multiple-params/#embed-a-single-body-parameter). + """ + ), + ] = False, + media_type: Annotated[ + str, + Doc( + """ + The media type of this parameter field. Changing it would affect the + generated OpenAPI, but currently it doesn't affect the parsing of the data. + """ + ), + ] = "application/json", + alias: Annotated[ + Optional[str], + Doc( + """ + An alternative name for the parameter field. + + This will be used to extract the data and for the generated OpenAPI. + It is particularly useful when you can't use the name you want because it + is a Python reserved keyword or similar. + """ + ), + ] = None, + alias_priority: Annotated[ + Union[int, None], + Doc( + """ + Priority of the alias. This affects whether an alias generator is used. + """ + ), + ] = _Unset, + # TODO: update when deprecating Pydantic v1, import these types + # validation_alias: str | AliasPath | AliasChoices | None + validation_alias: Annotated[ + Union[str, None], + Doc( + """ + 'Whitelist' validation step. The parameter field will be the single one + allowed by the alias or set of aliases defined. + """ + ), + ] = None, + serialization_alias: Annotated[ + Union[str, None], + Doc( + """ + 'Blacklist' validation step. The vanilla parameter field will be the + single one of the alias' or set of aliases' fields and all the other + fields will be ignored at serialization time. + """ + ), + ] = None, + title: Annotated[ + Optional[str], + Doc( + """ + Human-readable title. + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + Human-readable description. + """ + ), + ] = None, + gt: Annotated[ + Optional[float], + Doc( + """ + Greater than. If set, value must be greater than this. Only applicable to + numbers. + """ + ), + ] = None, + ge: Annotated[ + Optional[float], + Doc( + """ + Greater than or equal. If set, value must be greater than or equal to + this. Only applicable to numbers. + """ + ), + ] = None, + lt: Annotated[ + Optional[float], + Doc( + """ + Less than. If set, value must be less than this. Only applicable to numbers. + """ + ), + ] = None, + le: Annotated[ + Optional[float], + Doc( + """ + Less than or equal. If set, value must be less than or equal to this. + Only applicable to numbers. + """ + ), + ] = None, + min_length: Annotated[ + Optional[int], + Doc( + """ + Minimum length for strings. + """ + ), + ] = None, + max_length: Annotated[ + Optional[int], + Doc( + """ + Maximum length for strings. + """ + ), + ] = None, + pattern: Annotated[ + Optional[str], + Doc( + """ + RegEx pattern for strings. + """ + ), + ] = None, + regex: Annotated[ + Optional[str], + Doc( + """ + RegEx pattern for strings. + """ + ), + deprecated( + "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." + ), + ] = None, + discriminator: Annotated[ + Union[str, None], + Doc( + """ + Parameter field name for discriminating the type in a tagged union. + """ + ), + ] = None, + strict: Annotated[ + Union[bool, None], + Doc( + """ + If `True`, strict validation is applied to the field. + """ + ), + ] = _Unset, + multiple_of: Annotated[ + Union[float, None], + Doc( + """ + Value must be a multiple of this. Only applicable to numbers. + """ + ), + ] = _Unset, + allow_inf_nan: Annotated[ + Union[bool, None], + Doc( + """ + Allow `inf`, `-inf`, `nan`. Only applicable to numbers. + """ + ), + ] = _Unset, + max_digits: Annotated[ + Union[int, None], + Doc( + """ + Maximum number of allow digits for strings. + """ + ), + ] = _Unset, + decimal_places: Annotated[ + Union[int, None], + Doc( + """ + Maximum number of decimal places allowed for numbers. + """ + ), + ] = _Unset, + examples: Annotated[ + Optional[List[Any]], + Doc( + """ + Example values for this field. + """ + ), + ] = None, + example: Annotated[ + Optional[Any], + deprecated( + "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " + "although still supported. Use examples instead." + ), + ] = _Unset, + openapi_examples: Annotated[ + Optional[Dict[str, Example]], + Doc( + """ + OpenAPI-specific examples. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Swagger UI (that provides the `/docs` interface) has better support for the + OpenAPI-specific examples than the JSON Schema `examples`, that's the main + use case for this. + + Read more about it in the + [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter). + """ + ), + ] = None, + deprecated: Annotated[ + Optional[bool], + Doc( + """ + Mark this parameter field as deprecated. + + It will affect the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + include_in_schema: Annotated[ + bool, + Doc( + """ + To include (or not) this parameter field in the generated OpenAPI. + You probably don't need it, but it's available. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = True, + json_schema_extra: Annotated[ + Union[Dict[str, Any], None], + Doc( + """ + Any additional JSON schema data. + """ + ), + ] = None, + **extra: Annotated[ + Any, + Doc( + """ + Include extra fields used by the JSON Schema. + """ + ), + deprecated( + """ + The `extra` kwargs is deprecated. Use `json_schema_extra` instead. + """ + ), + ], ) -> Any: return params.Body( default=default, + default_factory=default_factory, embed=embed, media_type=media_type, alias=alias, + alias_priority=alias_priority, + validation_alias=validation_alias, + serialization_alias=serialization_alias, title=title, description=description, gt=gt, @@ -194,35 +1571,312 @@ def Body( # noqa: N802 le=le, min_length=min_length, max_length=max_length, + pattern=pattern, regex=regex, + discriminator=discriminator, + strict=strict, + multiple_of=multiple_of, + allow_inf_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, example=example, examples=examples, + openapi_examples=openapi_examples, + deprecated=deprecated, + include_in_schema=include_in_schema, + json_schema_extra=json_schema_extra, **extra, ) def Form( # noqa: N802 - default: Any = Undefined, + default: Annotated[ + Any, + Doc( + """ + Default value if the parameter field is not set. + """ + ), + ] = Undefined, *, - media_type: str = "application/x-www-form-urlencoded", - alias: Optional[str] = None, - title: Optional[str] = None, - description: Optional[str] = None, - gt: Optional[float] = None, - ge: Optional[float] = None, - lt: Optional[float] = None, - le: Optional[float] = None, - min_length: Optional[int] = None, - max_length: Optional[int] = None, - regex: Optional[str] = None, - example: Any = Undefined, - examples: Optional[Dict[str, Any]] = None, - **extra: Any, + default_factory: Annotated[ + Union[Callable[[], Any], None], + Doc( + """ + A callable to generate the default value. + + This doesn't affect `Path` parameters as the value is always required. + The parameter is available only for compatibility. + """ + ), + ] = _Unset, + media_type: Annotated[ + str, + Doc( + """ + The media type of this parameter field. Changing it would affect the + generated OpenAPI, but currently it doesn't affect the parsing of the data. + """ + ), + ] = "application/x-www-form-urlencoded", + alias: Annotated[ + Optional[str], + Doc( + """ + An alternative name for the parameter field. + + This will be used to extract the data and for the generated OpenAPI. + It is particularly useful when you can't use the name you want because it + is a Python reserved keyword or similar. + """ + ), + ] = None, + alias_priority: Annotated[ + Union[int, None], + Doc( + """ + Priority of the alias. This affects whether an alias generator is used. + """ + ), + ] = _Unset, + # TODO: update when deprecating Pydantic v1, import these types + # validation_alias: str | AliasPath | AliasChoices | None + validation_alias: Annotated[ + Union[str, None], + Doc( + """ + 'Whitelist' validation step. The parameter field will be the single one + allowed by the alias or set of aliases defined. + """ + ), + ] = None, + serialization_alias: Annotated[ + Union[str, None], + Doc( + """ + 'Blacklist' validation step. The vanilla parameter field will be the + single one of the alias' or set of aliases' fields and all the other + fields will be ignored at serialization time. + """ + ), + ] = None, + title: Annotated[ + Optional[str], + Doc( + """ + Human-readable title. + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + Human-readable description. + """ + ), + ] = None, + gt: Annotated[ + Optional[float], + Doc( + """ + Greater than. If set, value must be greater than this. Only applicable to + numbers. + """ + ), + ] = None, + ge: Annotated[ + Optional[float], + Doc( + """ + Greater than or equal. If set, value must be greater than or equal to + this. Only applicable to numbers. + """ + ), + ] = None, + lt: Annotated[ + Optional[float], + Doc( + """ + Less than. If set, value must be less than this. Only applicable to numbers. + """ + ), + ] = None, + le: Annotated[ + Optional[float], + Doc( + """ + Less than or equal. If set, value must be less than or equal to this. + Only applicable to numbers. + """ + ), + ] = None, + min_length: Annotated[ + Optional[int], + Doc( + """ + Minimum length for strings. + """ + ), + ] = None, + max_length: Annotated[ + Optional[int], + Doc( + """ + Maximum length for strings. + """ + ), + ] = None, + pattern: Annotated[ + Optional[str], + Doc( + """ + RegEx pattern for strings. + """ + ), + ] = None, + regex: Annotated[ + Optional[str], + Doc( + """ + RegEx pattern for strings. + """ + ), + deprecated( + "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." + ), + ] = None, + discriminator: Annotated[ + Union[str, None], + Doc( + """ + Parameter field name for discriminating the type in a tagged union. + """ + ), + ] = None, + strict: Annotated[ + Union[bool, None], + Doc( + """ + If `True`, strict validation is applied to the field. + """ + ), + ] = _Unset, + multiple_of: Annotated[ + Union[float, None], + Doc( + """ + Value must be a multiple of this. Only applicable to numbers. + """ + ), + ] = _Unset, + allow_inf_nan: Annotated[ + Union[bool, None], + Doc( + """ + Allow `inf`, `-inf`, `nan`. Only applicable to numbers. + """ + ), + ] = _Unset, + max_digits: Annotated[ + Union[int, None], + Doc( + """ + Maximum number of allow digits for strings. + """ + ), + ] = _Unset, + decimal_places: Annotated[ + Union[int, None], + Doc( + """ + Maximum number of decimal places allowed for numbers. + """ + ), + ] = _Unset, + examples: Annotated[ + Optional[List[Any]], + Doc( + """ + Example values for this field. + """ + ), + ] = None, + example: Annotated[ + Optional[Any], + deprecated( + "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " + "although still supported. Use examples instead." + ), + ] = _Unset, + openapi_examples: Annotated[ + Optional[Dict[str, Example]], + Doc( + """ + OpenAPI-specific examples. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Swagger UI (that provides the `/docs` interface) has better support for the + OpenAPI-specific examples than the JSON Schema `examples`, that's the main + use case for this. + + Read more about it in the + [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter). + """ + ), + ] = None, + deprecated: Annotated[ + Optional[bool], + Doc( + """ + Mark this parameter field as deprecated. + + It will affect the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + include_in_schema: Annotated[ + bool, + Doc( + """ + To include (or not) this parameter field in the generated OpenAPI. + You probably don't need it, but it's available. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = True, + json_schema_extra: Annotated[ + Union[Dict[str, Any], None], + Doc( + """ + Any additional JSON schema data. + """ + ), + ] = None, + **extra: Annotated[ + Any, + Doc( + """ + Include extra fields used by the JSON Schema. + """ + ), + deprecated( + """ + The `extra` kwargs is deprecated. Use `json_schema_extra` instead. + """ + ), + ], ) -> Any: return params.Form( default=default, + default_factory=default_factory, media_type=media_type, alias=alias, + alias_priority=alias_priority, + validation_alias=validation_alias, + serialization_alias=serialization_alias, title=title, description=description, gt=gt, @@ -231,35 +1885,312 @@ def Form( # noqa: N802 le=le, min_length=min_length, max_length=max_length, + pattern=pattern, regex=regex, + discriminator=discriminator, + strict=strict, + multiple_of=multiple_of, + allow_inf_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, example=example, examples=examples, + openapi_examples=openapi_examples, + deprecated=deprecated, + include_in_schema=include_in_schema, + json_schema_extra=json_schema_extra, **extra, ) def File( # noqa: N802 - default: Any = Undefined, + default: Annotated[ + Any, + Doc( + """ + Default value if the parameter field is not set. + """ + ), + ] = Undefined, *, - media_type: str = "multipart/form-data", - alias: Optional[str] = None, - title: Optional[str] = None, - description: Optional[str] = None, - gt: Optional[float] = None, - ge: Optional[float] = None, - lt: Optional[float] = None, - le: Optional[float] = None, - min_length: Optional[int] = None, - max_length: Optional[int] = None, - regex: Optional[str] = None, - example: Any = Undefined, - examples: Optional[Dict[str, Any]] = None, - **extra: Any, + default_factory: Annotated[ + Union[Callable[[], Any], None], + Doc( + """ + A callable to generate the default value. + + This doesn't affect `Path` parameters as the value is always required. + The parameter is available only for compatibility. + """ + ), + ] = _Unset, + media_type: Annotated[ + str, + Doc( + """ + The media type of this parameter field. Changing it would affect the + generated OpenAPI, but currently it doesn't affect the parsing of the data. + """ + ), + ] = "multipart/form-data", + alias: Annotated[ + Optional[str], + Doc( + """ + An alternative name for the parameter field. + + This will be used to extract the data and for the generated OpenAPI. + It is particularly useful when you can't use the name you want because it + is a Python reserved keyword or similar. + """ + ), + ] = None, + alias_priority: Annotated[ + Union[int, None], + Doc( + """ + Priority of the alias. This affects whether an alias generator is used. + """ + ), + ] = _Unset, + # TODO: update when deprecating Pydantic v1, import these types + # validation_alias: str | AliasPath | AliasChoices | None + validation_alias: Annotated[ + Union[str, None], + Doc( + """ + 'Whitelist' validation step. The parameter field will be the single one + allowed by the alias or set of aliases defined. + """ + ), + ] = None, + serialization_alias: Annotated[ + Union[str, None], + Doc( + """ + 'Blacklist' validation step. The vanilla parameter field will be the + single one of the alias' or set of aliases' fields and all the other + fields will be ignored at serialization time. + """ + ), + ] = None, + title: Annotated[ + Optional[str], + Doc( + """ + Human-readable title. + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + Human-readable description. + """ + ), + ] = None, + gt: Annotated[ + Optional[float], + Doc( + """ + Greater than. If set, value must be greater than this. Only applicable to + numbers. + """ + ), + ] = None, + ge: Annotated[ + Optional[float], + Doc( + """ + Greater than or equal. If set, value must be greater than or equal to + this. Only applicable to numbers. + """ + ), + ] = None, + lt: Annotated[ + Optional[float], + Doc( + """ + Less than. If set, value must be less than this. Only applicable to numbers. + """ + ), + ] = None, + le: Annotated[ + Optional[float], + Doc( + """ + Less than or equal. If set, value must be less than or equal to this. + Only applicable to numbers. + """ + ), + ] = None, + min_length: Annotated[ + Optional[int], + Doc( + """ + Minimum length for strings. + """ + ), + ] = None, + max_length: Annotated[ + Optional[int], + Doc( + """ + Maximum length for strings. + """ + ), + ] = None, + pattern: Annotated[ + Optional[str], + Doc( + """ + RegEx pattern for strings. + """ + ), + ] = None, + regex: Annotated[ + Optional[str], + Doc( + """ + RegEx pattern for strings. + """ + ), + deprecated( + "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." + ), + ] = None, + discriminator: Annotated[ + Union[str, None], + Doc( + """ + Parameter field name for discriminating the type in a tagged union. + """ + ), + ] = None, + strict: Annotated[ + Union[bool, None], + Doc( + """ + If `True`, strict validation is applied to the field. + """ + ), + ] = _Unset, + multiple_of: Annotated[ + Union[float, None], + Doc( + """ + Value must be a multiple of this. Only applicable to numbers. + """ + ), + ] = _Unset, + allow_inf_nan: Annotated[ + Union[bool, None], + Doc( + """ + Allow `inf`, `-inf`, `nan`. Only applicable to numbers. + """ + ), + ] = _Unset, + max_digits: Annotated[ + Union[int, None], + Doc( + """ + Maximum number of allow digits for strings. + """ + ), + ] = _Unset, + decimal_places: Annotated[ + Union[int, None], + Doc( + """ + Maximum number of decimal places allowed for numbers. + """ + ), + ] = _Unset, + examples: Annotated[ + Optional[List[Any]], + Doc( + """ + Example values for this field. + """ + ), + ] = None, + example: Annotated[ + Optional[Any], + deprecated( + "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " + "although still supported. Use examples instead." + ), + ] = _Unset, + openapi_examples: Annotated[ + Optional[Dict[str, Example]], + Doc( + """ + OpenAPI-specific examples. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Swagger UI (that provides the `/docs` interface) has better support for the + OpenAPI-specific examples than the JSON Schema `examples`, that's the main + use case for this. + + Read more about it in the + [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter). + """ + ), + ] = None, + deprecated: Annotated[ + Optional[bool], + Doc( + """ + Mark this parameter field as deprecated. + + It will affect the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + include_in_schema: Annotated[ + bool, + Doc( + """ + To include (or not) this parameter field in the generated OpenAPI. + You probably don't need it, but it's available. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = True, + json_schema_extra: Annotated[ + Union[Dict[str, Any], None], + Doc( + """ + Any additional JSON schema data. + """ + ), + ] = None, + **extra: Annotated[ + Any, + Doc( + """ + Include extra fields used by the JSON Schema. + """ + ), + deprecated( + """ + The `extra` kwargs is deprecated. Use `json_schema_extra` instead. + """ + ), + ], ) -> Any: return params.File( default=default, + default_factory=default_factory, media_type=media_type, alias=alias, + alias_priority=alias_priority, + validation_alias=validation_alias, + serialization_alias=serialization_alias, title=title, description=description, gt=gt, @@ -268,23 +2199,162 @@ def File( # noqa: N802 le=le, min_length=min_length, max_length=max_length, + pattern=pattern, regex=regex, + discriminator=discriminator, + strict=strict, + multiple_of=multiple_of, + allow_inf_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, example=example, examples=examples, + openapi_examples=openapi_examples, + deprecated=deprecated, + include_in_schema=include_in_schema, + json_schema_extra=json_schema_extra, **extra, ) def Depends( # noqa: N802 - dependency: Optional[Callable[..., Any]] = None, *, use_cache: bool = True + dependency: Annotated[ + Optional[Callable[..., Any]], + Doc( + """ + A "dependable" callable (like a function). + + Don't call it directly, FastAPI will call it for you, just pass the object + directly. + """ + ), + ] = None, + *, + use_cache: Annotated[ + bool, + Doc( + """ + By default, after a dependency is called the first time in a request, if + the dependency is declared again for the rest of the request (for example + if the dependency is needed by several dependencies), the value will be + re-used for the rest of the request. + + Set `use_cache` to `False` to disable this behavior and ensure the + dependency is called again (if declared more than once) in the same request. + """ + ), + ] = True, ) -> Any: + """ + Declare a FastAPI dependency. + + It takes a single "dependable" callable (like a function). + + Don't call it directly, FastAPI will call it for you. + + Read more about it in the + [FastAPI docs for Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/). + + **Example** + + ```python + from typing import Annotated + + from fastapi import Depends, FastAPI + + app = FastAPI() + + + async def common_parameters(q: str | None = None, skip: int = 0, limit: int = 100): + return {"q": q, "skip": skip, "limit": limit} + + + @app.get("/items/") + async def read_items(commons: Annotated[dict, Depends(common_parameters)]): + return commons + ``` + """ return params.Depends(dependency=dependency, use_cache=use_cache) def Security( # noqa: N802 - dependency: Optional[Callable[..., Any]] = None, + dependency: Annotated[ + Optional[Callable[..., Any]], + Doc( + """ + A "dependable" callable (like a function). + + Don't call it directly, FastAPI will call it for you, just pass the object + directly. + """ + ), + ] = None, *, - scopes: Optional[Sequence[str]] = None, - use_cache: bool = True, + scopes: Annotated[ + Optional[Sequence[str]], + Doc( + """ + OAuth2 scopes required for the *path operation* that uses this Security + dependency. + + The term "scope" comes from the OAuth2 specification, it seems to be + intentionaly vague and interpretable. It normally refers to permissions, + in cases to roles. + + These scopes are integrated with OpenAPI (and the API docs at `/docs`). + So they are visible in the OpenAPI specification. + ) + """ + ), + ] = None, + use_cache: Annotated[ + bool, + Doc( + """ + By default, after a dependency is called the first time in a request, if + the dependency is declared again for the rest of the request (for example + if the dependency is needed by several dependencies), the value will be + re-used for the rest of the request. + + Set `use_cache` to `False` to disable this behavior and ensure the + dependency is called again (if declared more than once) in the same request. + """ + ), + ] = True, ) -> Any: + """ + Declare a FastAPI Security dependency. + + The only difference with a regular dependency is that it can declare OAuth2 + scopes that will be integrated with OpenAPI and the automatic UI docs (by default + at `/docs`). + + It takes a single "dependable" callable (like a function). + + Don't call it directly, FastAPI will call it for you. + + Read more about it in the + [FastAPI docs for Security](https://fastapi.tiangolo.com/tutorial/security/) and + in the + [FastAPI docs for OAuth2 scopes](https://fastapi.tiangolo.com/advanced/security/oauth2-scopes/). + + **Example** + + ```python + from typing import Annotated + + from fastapi import Depends, FastAPI + + from .db import User + from .security import get_current_active_user + + app = FastAPI() + + @app.get("/users/me/items/") + async def read_own_items( + current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])] + ): + return [{"item_id": "Foo", "owner": current_user.username}] + ``` + """ return params.Security(dependency=dependency, scopes=scopes, use_cache=use_cache) diff --git a/fastapi/params.py b/fastapi/params.py index 16c5c309a785f..b40944dba6f56 100644 --- a/fastapi/params.py +++ b/fastapi/params.py @@ -1,7 +1,14 @@ +import warnings from enum import Enum -from typing import Any, Callable, Dict, Optional, Sequence +from typing import Any, Callable, Dict, List, Optional, Sequence, Union -from pydantic.fields import FieldInfo, Undefined +from fastapi.openapi.models import Example +from pydantic.fields import FieldInfo +from typing_extensions import Annotated, deprecated + +from ._compat import PYDANTIC_V2, Undefined + +_Unset: Any = Undefined class ParamTypes(Enum): @@ -18,7 +25,14 @@ def __init__( self, default: Any = Undefined, *, + default_factory: Union[Callable[[], Any], None] = _Unset, + annotation: Optional[Any] = None, alias: Optional[str] = None, + alias_priority: Union[int, None] = _Unset, + # TODO: update when deprecating Pydantic v1, import these types + # validation_alias: str | AliasPath | AliasChoices | None + validation_alias: Union[str, None] = None, + serialization_alias: Union[str, None] = None, title: Optional[str] = None, description: Optional[str] = None, gt: Optional[float] = None, @@ -27,19 +41,46 @@ def __init__( le: Optional[float] = None, min_length: Optional[int] = None, max_length: Optional[int] = None, - regex: Optional[str] = None, - example: Any = Undefined, - examples: Optional[Dict[str, Any]] = None, + pattern: Optional[str] = None, + regex: Annotated[ + Optional[str], + deprecated( + "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." + ), + ] = None, + discriminator: Union[str, None] = None, + strict: Union[bool, None] = _Unset, + multiple_of: Union[float, None] = _Unset, + allow_inf_nan: Union[bool, None] = _Unset, + max_digits: Union[int, None] = _Unset, + decimal_places: Union[int, None] = _Unset, + examples: Optional[List[Any]] = None, + example: Annotated[ + Optional[Any], + deprecated( + "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " + "although still supported. Use examples instead." + ), + ] = _Unset, + openapi_examples: Optional[Dict[str, Example]] = None, deprecated: Optional[bool] = None, include_in_schema: bool = True, + json_schema_extra: Union[Dict[str, Any], None] = None, **extra: Any, ): self.deprecated = deprecated + if example is not _Unset: + warnings.warn( + "`example` has been deprecated, please use `examples` instead", + category=DeprecationWarning, + stacklevel=4, + ) self.example = example - self.examples = examples self.include_in_schema = include_in_schema - super().__init__( + self.openapi_examples = openapi_examples + kwargs = dict( default=default, + default_factory=default_factory, alias=alias, title=title, description=description, @@ -49,9 +90,40 @@ def __init__( le=le, min_length=min_length, max_length=max_length, - regex=regex, + discriminator=discriminator, + multiple_of=multiple_of, + allow_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, **extra, ) + if examples is not None: + kwargs["examples"] = examples + if regex is not None: + warnings.warn( + "`regex` has been deprecated, please use `pattern` instead", + category=DeprecationWarning, + stacklevel=4, + ) + current_json_schema_extra = json_schema_extra or extra + if PYDANTIC_V2: + kwargs.update( + { + "annotation": annotation, + "alias_priority": alias_priority, + "validation_alias": validation_alias, + "serialization_alias": serialization_alias, + "strict": strict, + "json_schema_extra": current_json_schema_extra, + } + ) + kwargs["pattern"] = pattern or regex + else: + kwargs["regex"] = pattern or regex + kwargs.update(**current_json_schema_extra) + use_kwargs = {k: v for k, v in kwargs.items() if v is not _Unset} + + super().__init__(**use_kwargs) def __repr__(self) -> str: return f"{self.__class__.__name__}({self.default})" @@ -64,7 +136,14 @@ def __init__( self, default: Any = ..., *, + default_factory: Union[Callable[[], Any], None] = _Unset, + annotation: Optional[Any] = None, alias: Optional[str] = None, + alias_priority: Union[int, None] = _Unset, + # TODO: update when deprecating Pydantic v1, import these types + # validation_alias: str | AliasPath | AliasChoices | None + validation_alias: Union[str, None] = None, + serialization_alias: Union[str, None] = None, title: Optional[str] = None, description: Optional[str] = None, gt: Optional[float] = None, @@ -73,18 +152,43 @@ def __init__( le: Optional[float] = None, min_length: Optional[int] = None, max_length: Optional[int] = None, - regex: Optional[str] = None, - example: Any = Undefined, - examples: Optional[Dict[str, Any]] = None, + pattern: Optional[str] = None, + regex: Annotated[ + Optional[str], + deprecated( + "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." + ), + ] = None, + discriminator: Union[str, None] = None, + strict: Union[bool, None] = _Unset, + multiple_of: Union[float, None] = _Unset, + allow_inf_nan: Union[bool, None] = _Unset, + max_digits: Union[int, None] = _Unset, + decimal_places: Union[int, None] = _Unset, + examples: Optional[List[Any]] = None, + example: Annotated[ + Optional[Any], + deprecated( + "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " + "although still supported. Use examples instead." + ), + ] = _Unset, + openapi_examples: Optional[Dict[str, Example]] = None, deprecated: Optional[bool] = None, include_in_schema: bool = True, + json_schema_extra: Union[Dict[str, Any], None] = None, **extra: Any, ): assert default is ..., "Path parameters cannot have a default value" self.in_ = self.in_ super().__init__( default=default, + default_factory=default_factory, + annotation=annotation, alias=alias, + alias_priority=alias_priority, + validation_alias=validation_alias, + serialization_alias=serialization_alias, title=title, description=description, gt=gt, @@ -93,11 +197,20 @@ def __init__( le=le, min_length=min_length, max_length=max_length, + pattern=pattern, regex=regex, + discriminator=discriminator, + strict=strict, + multiple_of=multiple_of, + allow_inf_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, deprecated=deprecated, example=example, examples=examples, + openapi_examples=openapi_examples, include_in_schema=include_in_schema, + json_schema_extra=json_schema_extra, **extra, ) @@ -109,7 +222,14 @@ def __init__( self, default: Any = Undefined, *, + default_factory: Union[Callable[[], Any], None] = _Unset, + annotation: Optional[Any] = None, alias: Optional[str] = None, + alias_priority: Union[int, None] = _Unset, + # TODO: update when deprecating Pydantic v1, import these types + # validation_alias: str | AliasPath | AliasChoices | None + validation_alias: Union[str, None] = None, + serialization_alias: Union[str, None] = None, title: Optional[str] = None, description: Optional[str] = None, gt: Optional[float] = None, @@ -118,16 +238,41 @@ def __init__( le: Optional[float] = None, min_length: Optional[int] = None, max_length: Optional[int] = None, - regex: Optional[str] = None, - example: Any = Undefined, - examples: Optional[Dict[str, Any]] = None, + pattern: Optional[str] = None, + regex: Annotated[ + Optional[str], + deprecated( + "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." + ), + ] = None, + discriminator: Union[str, None] = None, + strict: Union[bool, None] = _Unset, + multiple_of: Union[float, None] = _Unset, + allow_inf_nan: Union[bool, None] = _Unset, + max_digits: Union[int, None] = _Unset, + decimal_places: Union[int, None] = _Unset, + examples: Optional[List[Any]] = None, + example: Annotated[ + Optional[Any], + deprecated( + "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " + "although still supported. Use examples instead." + ), + ] = _Unset, + openapi_examples: Optional[Dict[str, Example]] = None, deprecated: Optional[bool] = None, include_in_schema: bool = True, + json_schema_extra: Union[Dict[str, Any], None] = None, **extra: Any, ): super().__init__( default=default, + default_factory=default_factory, + annotation=annotation, alias=alias, + alias_priority=alias_priority, + validation_alias=validation_alias, + serialization_alias=serialization_alias, title=title, description=description, gt=gt, @@ -136,11 +281,20 @@ def __init__( le=le, min_length=min_length, max_length=max_length, + pattern=pattern, regex=regex, + discriminator=discriminator, + strict=strict, + multiple_of=multiple_of, + allow_inf_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, deprecated=deprecated, example=example, examples=examples, + openapi_examples=openapi_examples, include_in_schema=include_in_schema, + json_schema_extra=json_schema_extra, **extra, ) @@ -152,7 +306,14 @@ def __init__( self, default: Any = Undefined, *, + default_factory: Union[Callable[[], Any], None] = _Unset, + annotation: Optional[Any] = None, alias: Optional[str] = None, + alias_priority: Union[int, None] = _Unset, + # TODO: update when deprecating Pydantic v1, import these types + # validation_alias: str | AliasPath | AliasChoices | None + validation_alias: Union[str, None] = None, + serialization_alias: Union[str, None] = None, convert_underscores: bool = True, title: Optional[str] = None, description: Optional[str] = None, @@ -162,17 +323,42 @@ def __init__( le: Optional[float] = None, min_length: Optional[int] = None, max_length: Optional[int] = None, - regex: Optional[str] = None, - example: Any = Undefined, - examples: Optional[Dict[str, Any]] = None, + pattern: Optional[str] = None, + regex: Annotated[ + Optional[str], + deprecated( + "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." + ), + ] = None, + discriminator: Union[str, None] = None, + strict: Union[bool, None] = _Unset, + multiple_of: Union[float, None] = _Unset, + allow_inf_nan: Union[bool, None] = _Unset, + max_digits: Union[int, None] = _Unset, + decimal_places: Union[int, None] = _Unset, + examples: Optional[List[Any]] = None, + example: Annotated[ + Optional[Any], + deprecated( + "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " + "although still supported. Use examples instead." + ), + ] = _Unset, + openapi_examples: Optional[Dict[str, Example]] = None, deprecated: Optional[bool] = None, include_in_schema: bool = True, + json_schema_extra: Union[Dict[str, Any], None] = None, **extra: Any, ): self.convert_underscores = convert_underscores super().__init__( default=default, + default_factory=default_factory, + annotation=annotation, alias=alias, + alias_priority=alias_priority, + validation_alias=validation_alias, + serialization_alias=serialization_alias, title=title, description=description, gt=gt, @@ -181,11 +367,20 @@ def __init__( le=le, min_length=min_length, max_length=max_length, + pattern=pattern, regex=regex, + discriminator=discriminator, + strict=strict, + multiple_of=multiple_of, + allow_inf_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, deprecated=deprecated, example=example, examples=examples, + openapi_examples=openapi_examples, include_in_schema=include_in_schema, + json_schema_extra=json_schema_extra, **extra, ) @@ -197,7 +392,14 @@ def __init__( self, default: Any = Undefined, *, + default_factory: Union[Callable[[], Any], None] = _Unset, + annotation: Optional[Any] = None, alias: Optional[str] = None, + alias_priority: Union[int, None] = _Unset, + # TODO: update when deprecating Pydantic v1, import these types + # validation_alias: str | AliasPath | AliasChoices | None + validation_alias: Union[str, None] = None, + serialization_alias: Union[str, None] = None, title: Optional[str] = None, description: Optional[str] = None, gt: Optional[float] = None, @@ -206,16 +408,41 @@ def __init__( le: Optional[float] = None, min_length: Optional[int] = None, max_length: Optional[int] = None, - regex: Optional[str] = None, - example: Any = Undefined, - examples: Optional[Dict[str, Any]] = None, + pattern: Optional[str] = None, + regex: Annotated[ + Optional[str], + deprecated( + "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." + ), + ] = None, + discriminator: Union[str, None] = None, + strict: Union[bool, None] = _Unset, + multiple_of: Union[float, None] = _Unset, + allow_inf_nan: Union[bool, None] = _Unset, + max_digits: Union[int, None] = _Unset, + decimal_places: Union[int, None] = _Unset, + examples: Optional[List[Any]] = None, + example: Annotated[ + Optional[Any], + deprecated( + "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " + "although still supported. Use examples instead." + ), + ] = _Unset, + openapi_examples: Optional[Dict[str, Example]] = None, deprecated: Optional[bool] = None, include_in_schema: bool = True, + json_schema_extra: Union[Dict[str, Any], None] = None, **extra: Any, ): super().__init__( default=default, + default_factory=default_factory, + annotation=annotation, alias=alias, + alias_priority=alias_priority, + validation_alias=validation_alias, + serialization_alias=serialization_alias, title=title, description=description, gt=gt, @@ -224,11 +451,20 @@ def __init__( le=le, min_length=min_length, max_length=max_length, + pattern=pattern, regex=regex, + discriminator=discriminator, + strict=strict, + multiple_of=multiple_of, + allow_inf_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, deprecated=deprecated, example=example, examples=examples, + openapi_examples=openapi_examples, include_in_schema=include_in_schema, + json_schema_extra=json_schema_extra, **extra, ) @@ -238,9 +474,16 @@ def __init__( self, default: Any = Undefined, *, + default_factory: Union[Callable[[], Any], None] = _Unset, + annotation: Optional[Any] = None, embed: bool = False, media_type: str = "application/json", alias: Optional[str] = None, + alias_priority: Union[int, None] = _Unset, + # TODO: update when deprecating Pydantic v1, import these types + # validation_alias: str | AliasPath | AliasChoices | None + validation_alias: Union[str, None] = None, + serialization_alias: Union[str, None] = None, title: Optional[str] = None, description: Optional[str] = None, gt: Optional[float] = None, @@ -249,17 +492,48 @@ def __init__( le: Optional[float] = None, min_length: Optional[int] = None, max_length: Optional[int] = None, - regex: Optional[str] = None, - example: Any = Undefined, - examples: Optional[Dict[str, Any]] = None, + pattern: Optional[str] = None, + regex: Annotated[ + Optional[str], + deprecated( + "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." + ), + ] = None, + discriminator: Union[str, None] = None, + strict: Union[bool, None] = _Unset, + multiple_of: Union[float, None] = _Unset, + allow_inf_nan: Union[bool, None] = _Unset, + max_digits: Union[int, None] = _Unset, + decimal_places: Union[int, None] = _Unset, + examples: Optional[List[Any]] = None, + example: Annotated[ + Optional[Any], + deprecated( + "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " + "although still supported. Use examples instead." + ), + ] = _Unset, + openapi_examples: Optional[Dict[str, Example]] = None, + deprecated: Optional[bool] = None, + include_in_schema: bool = True, + json_schema_extra: Union[Dict[str, Any], None] = None, **extra: Any, ): self.embed = embed self.media_type = media_type + self.deprecated = deprecated + if example is not _Unset: + warnings.warn( + "`example` has been deprecated, please use `examples` instead", + category=DeprecationWarning, + stacklevel=4, + ) self.example = example - self.examples = examples - super().__init__( + self.include_in_schema = include_in_schema + self.openapi_examples = openapi_examples + kwargs = dict( default=default, + default_factory=default_factory, alias=alias, title=title, description=description, @@ -269,9 +543,41 @@ def __init__( le=le, min_length=min_length, max_length=max_length, - regex=regex, + discriminator=discriminator, + multiple_of=multiple_of, + allow_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, **extra, ) + if examples is not None: + kwargs["examples"] = examples + if regex is not None: + warnings.warn( + "`regex` has been depreacated, please use `pattern` instead", + category=DeprecationWarning, + stacklevel=4, + ) + current_json_schema_extra = json_schema_extra or extra + if PYDANTIC_V2: + kwargs.update( + { + "annotation": annotation, + "alias_priority": alias_priority, + "validation_alias": validation_alias, + "serialization_alias": serialization_alias, + "strict": strict, + "json_schema_extra": current_json_schema_extra, + } + ) + kwargs["pattern"] = pattern or regex + else: + kwargs["regex"] = pattern or regex + kwargs.update(**current_json_schema_extra) + + use_kwargs = {k: v for k, v in kwargs.items() if v is not _Unset} + + super().__init__(**use_kwargs) def __repr__(self) -> str: return f"{self.__class__.__name__}({self.default})" @@ -282,8 +588,15 @@ def __init__( self, default: Any = Undefined, *, + default_factory: Union[Callable[[], Any], None] = _Unset, + annotation: Optional[Any] = None, media_type: str = "application/x-www-form-urlencoded", alias: Optional[str] = None, + alias_priority: Union[int, None] = _Unset, + # TODO: update when deprecating Pydantic v1, import these types + # validation_alias: str | AliasPath | AliasChoices | None + validation_alias: Union[str, None] = None, + serialization_alias: Union[str, None] = None, title: Optional[str] = None, description: Optional[str] = None, gt: Optional[float] = None, @@ -292,16 +605,43 @@ def __init__( le: Optional[float] = None, min_length: Optional[int] = None, max_length: Optional[int] = None, - regex: Optional[str] = None, - example: Any = Undefined, - examples: Optional[Dict[str, Any]] = None, + pattern: Optional[str] = None, + regex: Annotated[ + Optional[str], + deprecated( + "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." + ), + ] = None, + discriminator: Union[str, None] = None, + strict: Union[bool, None] = _Unset, + multiple_of: Union[float, None] = _Unset, + allow_inf_nan: Union[bool, None] = _Unset, + max_digits: Union[int, None] = _Unset, + decimal_places: Union[int, None] = _Unset, + examples: Optional[List[Any]] = None, + example: Annotated[ + Optional[Any], + deprecated( + "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " + "although still supported. Use examples instead." + ), + ] = _Unset, + openapi_examples: Optional[Dict[str, Example]] = None, + deprecated: Optional[bool] = None, + include_in_schema: bool = True, + json_schema_extra: Union[Dict[str, Any], None] = None, **extra: Any, ): super().__init__( default=default, + default_factory=default_factory, + annotation=annotation, embed=True, media_type=media_type, alias=alias, + alias_priority=alias_priority, + validation_alias=validation_alias, + serialization_alias=serialization_alias, title=title, description=description, gt=gt, @@ -310,9 +650,20 @@ def __init__( le=le, min_length=min_length, max_length=max_length, + pattern=pattern, regex=regex, + discriminator=discriminator, + strict=strict, + multiple_of=multiple_of, + allow_inf_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, + deprecated=deprecated, example=example, examples=examples, + openapi_examples=openapi_examples, + include_in_schema=include_in_schema, + json_schema_extra=json_schema_extra, **extra, ) @@ -322,8 +673,15 @@ def __init__( self, default: Any = Undefined, *, + default_factory: Union[Callable[[], Any], None] = _Unset, + annotation: Optional[Any] = None, media_type: str = "multipart/form-data", alias: Optional[str] = None, + alias_priority: Union[int, None] = _Unset, + # TODO: update when deprecating Pydantic v1, import these types + # validation_alias: str | AliasPath | AliasChoices | None + validation_alias: Union[str, None] = None, + serialization_alias: Union[str, None] = None, title: Optional[str] = None, description: Optional[str] = None, gt: Optional[float] = None, @@ -332,15 +690,42 @@ def __init__( le: Optional[float] = None, min_length: Optional[int] = None, max_length: Optional[int] = None, - regex: Optional[str] = None, - example: Any = Undefined, - examples: Optional[Dict[str, Any]] = None, + pattern: Optional[str] = None, + regex: Annotated[ + Optional[str], + deprecated( + "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." + ), + ] = None, + discriminator: Union[str, None] = None, + strict: Union[bool, None] = _Unset, + multiple_of: Union[float, None] = _Unset, + allow_inf_nan: Union[bool, None] = _Unset, + max_digits: Union[int, None] = _Unset, + decimal_places: Union[int, None] = _Unset, + examples: Optional[List[Any]] = None, + example: Annotated[ + Optional[Any], + deprecated( + "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " + "although still supported. Use examples instead." + ), + ] = _Unset, + openapi_examples: Optional[Dict[str, Example]] = None, + deprecated: Optional[bool] = None, + include_in_schema: bool = True, + json_schema_extra: Union[Dict[str, Any], None] = None, **extra: Any, ): super().__init__( default=default, + default_factory=default_factory, + annotation=annotation, media_type=media_type, alias=alias, + alias_priority=alias_priority, + validation_alias=validation_alias, + serialization_alias=serialization_alias, title=title, description=description, gt=gt, @@ -349,9 +734,20 @@ def __init__( le=le, min_length=min_length, max_length=max_length, + pattern=pattern, regex=regex, + discriminator=discriminator, + strict=strict, + multiple_of=multiple_of, + allow_inf_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, + deprecated=deprecated, example=example, examples=examples, + openapi_examples=openapi_examples, + include_in_schema=include_in_schema, + json_schema_extra=json_schema_extra, **extra, ) diff --git a/fastapi/responses.py b/fastapi/responses.py index c0a13b7555efc..6c8db6f3353ff 100644 --- a/fastapi/responses.py +++ b/fastapi/responses.py @@ -21,12 +21,26 @@ class UJSONResponse(JSONResponse): + """ + JSON response using the high-performance ujson library to serialize data to JSON. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/). + """ + def render(self, content: Any) -> bytes: assert ujson is not None, "ujson must be installed to use UJSONResponse" return ujson.dumps(content, ensure_ascii=False).encode("utf-8") class ORJSONResponse(JSONResponse): + """ + JSON response using the high-performance orjson library to serialize data to JSON. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/). + """ + def render(self, content: Any) -> bytes: assert orjson is not None, "orjson must be installed to use ORJSONResponse" return orjson.dumps( diff --git a/fastapi/routing.py b/fastapi/routing.py index ec8af99b3a290..23a32d15fd452 100644 --- a/fastapi/routing.py +++ b/fastapi/routing.py @@ -20,6 +20,14 @@ ) from fastapi import params +from fastapi._compat import ( + ModelField, + Undefined, + _get_model_config, + _model_dump, + _normalize_errors, + lenient_issubclass, +) from fastapi.datastructures import Default, DefaultPlaceholder from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import ( @@ -29,13 +37,14 @@ get_typed_return_annotation, solve_dependencies, ) -from fastapi.encoders import DictIntStrAny, SetIntStr, jsonable_encoder +from fastapi.encoders import jsonable_encoder from fastapi.exceptions import ( FastAPIError, RequestValidationError, + ResponseValidationError, WebSocketRequestValidationError, ) -from fastapi.types import DecoratedCallable +from fastapi.types import DecoratedCallable, IncEx from fastapi.utils import ( create_cloned_field, create_response_field, @@ -44,9 +53,6 @@ is_body_allowed_for_status_code, ) from pydantic import BaseModel -from pydantic.error_wrappers import ErrorWrapper, ValidationError -from pydantic.fields import ModelField, Undefined -from pydantic.utils import lenient_issubclass from starlette import routing from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException @@ -63,6 +69,7 @@ from starlette.routing import Mount as Mount # noqa from starlette.types import ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket +from typing_extensions import Annotated, Doc, deprecated # type: ignore [attr-defined] def _prepare_response_content( @@ -73,14 +80,15 @@ def _prepare_response_content( exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): - read_with_orm_mode = getattr(res.__config__, "read_with_orm_mode", None) + read_with_orm_mode = getattr(_get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. - # Otherwise there's no way to extract lazy data that requires attribute + # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res - return res.dict( + return _model_dump( + res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, @@ -115,8 +123,8 @@ async def serialize_response( *, field: Optional[ModelField] = None, response_content: Any, - include: Optional[Union[SetIntStr, DictIntStrAny]] = None, - exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, + include: Optional[IncEx] = None, + exclude: Optional[IncEx] = None, by_alias: bool = True, exclude_unset: bool = False, exclude_defaults: bool = False, @@ -125,24 +133,40 @@ async def serialize_response( ) -> Any: if field: errors = [] - response_content = _prepare_response_content( - response_content, - exclude_unset=exclude_unset, - exclude_defaults=exclude_defaults, - exclude_none=exclude_none, - ) + if not hasattr(field, "serialize"): + # pydantic v1 + response_content = _prepare_response_content( + response_content, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + ) if is_coroutine: value, errors_ = field.validate(response_content, {}, loc=("response",)) else: value, errors_ = await run_in_threadpool( field.validate, response_content, {}, loc=("response",) ) - if isinstance(errors_, ErrorWrapper): - errors.append(errors_) - elif isinstance(errors_, list): + if isinstance(errors_, list): errors.extend(errors_) + elif errors_: + errors.append(errors_) if errors: - raise ValidationError(errors, field.type_) + raise ResponseValidationError( + errors=_normalize_errors(errors), body=response_content + ) + + if hasattr(field, "serialize"): + return field.serialize( + value, + include=include, + exclude=exclude, + by_alias=by_alias, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + ) + return jsonable_encoder( value, include=include, @@ -175,8 +199,8 @@ def get_request_handler( status_code: Optional[int] = None, response_class: Union[Type[Response], DefaultPlaceholder] = Default(JSONResponse), response_field: Optional[ModelField] = None, - response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, - response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, + response_model_include: Optional[IncEx] = None, + response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, @@ -192,86 +216,112 @@ def get_request_handler( actual_response_class = response_class async def app(request: Request) -> Response: - try: - body: Any = None - if body_field: - if is_body_form: - body = await request.form() - stack = request.scope.get("fastapi_astack") - assert isinstance(stack, AsyncExitStack) - stack.push_async_callback(body.close) - else: - body_bytes = await request.body() - if body_bytes: - json_body: Any = Undefined - content_type_value = request.headers.get("content-type") - if not content_type_value: - json_body = await request.json() - else: - message = email.message.Message() - message["content-type"] = content_type_value - if message.get_content_maintype() == "application": - subtype = message.get_content_subtype() - if subtype == "json" or subtype.endswith("+json"): - json_body = await request.json() - if json_body != Undefined: - body = json_body - else: - body = body_bytes - except json.JSONDecodeError as e: - raise RequestValidationError( - [ErrorWrapper(e, ("body", e.pos))], body=e.doc - ) from e - except HTTPException: - raise - except Exception as e: - raise HTTPException( - status_code=400, detail="There was an error parsing the body" - ) from e - solved_result = await solve_dependencies( - request=request, - dependant=dependant, - body=body, - dependency_overrides_provider=dependency_overrides_provider, - ) - values, errors, background_tasks, sub_response, _ = solved_result - if errors: - raise RequestValidationError(errors, body=body) - else: - raw_response = await run_endpoint_function( - dependant=dependant, values=values, is_coroutine=is_coroutine - ) - - if isinstance(raw_response, Response): - if raw_response.background is None: - raw_response.background = background_tasks - return raw_response - response_args: Dict[str, Any] = {"background": background_tasks} - # If status_code was set, use it, otherwise use the default from the - # response class, in the case of redirect it's 307 - current_status_code = ( - status_code if status_code else sub_response.status_code - ) - if current_status_code is not None: - response_args["status_code"] = current_status_code - if sub_response.status_code: - response_args["status_code"] = sub_response.status_code - content = await serialize_response( - field=response_field, - response_content=raw_response, - include=response_model_include, - exclude=response_model_exclude, - by_alias=response_model_by_alias, - exclude_unset=response_model_exclude_unset, - exclude_defaults=response_model_exclude_defaults, - exclude_none=response_model_exclude_none, - is_coroutine=is_coroutine, + response: Union[Response, None] = None + async with AsyncExitStack() as file_stack: + try: + body: Any = None + if body_field: + if is_body_form: + body = await request.form() + file_stack.push_async_callback(body.close) + else: + body_bytes = await request.body() + if body_bytes: + json_body: Any = Undefined + content_type_value = request.headers.get("content-type") + if not content_type_value: + json_body = await request.json() + else: + message = email.message.Message() + message["content-type"] = content_type_value + if message.get_content_maintype() == "application": + subtype = message.get_content_subtype() + if subtype == "json" or subtype.endswith("+json"): + json_body = await request.json() + if json_body != Undefined: + body = json_body + else: + body = body_bytes + except json.JSONDecodeError as e: + validation_error = RequestValidationError( + [ + { + "type": "json_invalid", + "loc": ("body", e.pos), + "msg": "JSON decode error", + "input": {}, + "ctx": {"error": e.msg}, + } + ], + body=e.doc, + ) + raise validation_error from e + except HTTPException: + # If a middleware raises an HTTPException, it should be raised again + raise + except Exception as e: + http_error = HTTPException( + status_code=400, detail="There was an error parsing the body" + ) + raise http_error from e + errors: List[Any] = [] + async with AsyncExitStack() as async_exit_stack: + solved_result = await solve_dependencies( + request=request, + dependant=dependant, + body=body, + dependency_overrides_provider=dependency_overrides_provider, + async_exit_stack=async_exit_stack, + ) + values, errors, background_tasks, sub_response, _ = solved_result + if not errors: + raw_response = await run_endpoint_function( + dependant=dependant, values=values, is_coroutine=is_coroutine + ) + if isinstance(raw_response, Response): + if raw_response.background is None: + raw_response.background = background_tasks + response = raw_response + else: + response_args: Dict[str, Any] = {"background": background_tasks} + # If status_code was set, use it, otherwise use the default from the + # response class, in the case of redirect it's 307 + current_status_code = ( + status_code if status_code else sub_response.status_code + ) + if current_status_code is not None: + response_args["status_code"] = current_status_code + if sub_response.status_code: + response_args["status_code"] = sub_response.status_code + content = await serialize_response( + field=response_field, + response_content=raw_response, + include=response_model_include, + exclude=response_model_exclude, + by_alias=response_model_by_alias, + exclude_unset=response_model_exclude_unset, + exclude_defaults=response_model_exclude_defaults, + exclude_none=response_model_exclude_none, + is_coroutine=is_coroutine, + ) + response = actual_response_class(content, **response_args) + if not is_body_allowed_for_status_code(response.status_code): + response.body = b"" + response.headers.raw.extend(sub_response.headers.raw) + if errors: + validation_error = RequestValidationError( + _normalize_errors(errors), body=body + ) + raise validation_error + if response is None: + raise FastAPIError( + "No response object was returned. There's a high chance that the " + "application code is raising an exception and a dependency with yield " + "has a block with a bare except, or a block with except Exception, " + "and is not raising the exception again. Read more about it in the " + "docs: https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/#dependencies-with-yield-and-except" ) - response = actual_response_class(content, **response_args) - if not is_body_allowed_for_status_code(response.status_code): - response.body = b"" - response.headers.raw.extend(sub_response.headers.raw) - return response + return response return app @@ -280,16 +330,22 @@ def get_websocket_app( dependant: Dependant, dependency_overrides_provider: Optional[Any] = None ) -> Callable[[WebSocket], Coroutine[Any, Any, Any]]: async def app(websocket: WebSocket) -> None: - solved_result = await solve_dependencies( - request=websocket, - dependant=dependant, - dependency_overrides_provider=dependency_overrides_provider, - ) - values, errors, _, _2, _3 = solved_result - if errors: - raise WebSocketRequestValidationError(errors) - assert dependant.call is not None, "dependant.call must be a function" - await dependant.call(**values) + async with AsyncExitStack() as async_exit_stack: + # TODO: remove this scope later, after a few releases + # This scope fastapi_astack is no longer used by FastAPI, kept for + # compatibility, just in case + websocket.scope["fastapi_astack"] = async_exit_stack + solved_result = await solve_dependencies( + request=websocket, + dependant=dependant, + dependency_overrides_provider=dependency_overrides_provider, + async_exit_stack=async_exit_stack, + ) + values, errors, _, _2, _3 = solved_result + if errors: + raise WebSocketRequestValidationError(_normalize_errors(errors)) + assert dependant.call is not None, "dependant.call must be a function" + await dependant.call(**values) return app @@ -348,8 +404,8 @@ def __init__( name: Optional[str] = None, methods: Optional[Union[Set[str], List[str]]] = None, operation_id: Optional[str] = None, - response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, - response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, + response_model_include: Optional[IncEx] = None, + response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, @@ -414,7 +470,9 @@ def __init__( ), f"Status code {status_code} must not have a response body" response_name = "Response_" + self.unique_id self.response_field = create_response_field( - name=response_name, type_=self.response_model + name=response_name, + type_=self.response_model, + mode="serialization", ) # Create a clone of the field, so that a Pydantic submodel is not returned # as is just because it's an instance of a subclass of a more limited class @@ -422,7 +480,8 @@ def __init__( # that doesn't have the hashed_password. But because it's a subclass, it # would pass the validation and be returned as is. # By being a new field, no inheritance will be passed as is. A new model - # will be always created. + # will always be created. + # TODO: remove when deprecating Pydantic v1 self.secure_cloned_response_field: Optional[ ModelField ] = create_cloned_field(self.response_field) @@ -484,30 +543,246 @@ def matches(self, scope: Scope) -> Tuple[Match, Scope]: class APIRouter(routing.Router): + """ + `APIRouter` class, used to group *path operations*, for example to structure + an app in multiple files. It would then be included in the `FastAPI` app, or + in another `APIRouter` (ultimately included in the app). + + Read more about it in the + [FastAPI docs for Bigger Applications - Multiple Files](https://fastapi.tiangolo.com/tutorial/bigger-applications/). + + ## Example + + ```python + from fastapi import APIRouter, FastAPI + + app = FastAPI() + router = APIRouter() + + + @router.get("/users/", tags=["users"]) + async def read_users(): + return [{"username": "Rick"}, {"username": "Morty"}] + + + app.include_router(router) + ``` + """ + def __init__( self, *, - prefix: str = "", - tags: Optional[List[Union[str, Enum]]] = None, - dependencies: Optional[Sequence[params.Depends]] = None, - default_response_class: Type[Response] = Default(JSONResponse), - responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, - callbacks: Optional[List[BaseRoute]] = None, - routes: Optional[List[routing.BaseRoute]] = None, - redirect_slashes: bool = True, - default: Optional[ASGIApp] = None, - dependency_overrides_provider: Optional[Any] = None, - route_class: Type[APIRoute] = APIRoute, - on_startup: Optional[Sequence[Callable[[], Any]]] = None, - on_shutdown: Optional[Sequence[Callable[[], Any]]] = None, + prefix: Annotated[str, Doc("An optional path prefix for the router.")] = "", + tags: Annotated[ + Optional[List[Union[str, Enum]]], + Doc( + """ + A list of tags to be applied to all the *path operations* in this + router. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + dependencies: Annotated[ + Optional[Sequence[params.Depends]], + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to all the + *path operations* in this router. + + Read more about it in the + [FastAPI docs for Bigger Applications - Multiple Files](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies). + """ + ), + ] = None, + default_response_class: Annotated[ + Type[Response], + Doc( + """ + The default response class to be used. + + Read more in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class). + """ + ), + ] = Default(JSONResponse), + responses: Annotated[ + Optional[Dict[Union[int, str], Dict[str, Any]]], + Doc( + """ + Additional responses to be shown in OpenAPI. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/). + + And in the + [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies). + """ + ), + ] = None, + callbacks: Annotated[ + Optional[List[BaseRoute]], + Doc( + """ + OpenAPI callbacks that should apply to all *path operations* in this + router. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + routes: Annotated[ + Optional[List[BaseRoute]], + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited + from Starlette and supported for compatibility. + + --- + + A list of routes to serve incoming HTTP and WebSocket requests. + """ + ), + deprecated( + """ + You normally wouldn't use this parameter with FastAPI, it is inherited + from Starlette and supported for compatibility. + + In FastAPI, you normally would use the *path operation methods*, + like `router.get()`, `router.post()`, etc. + """ + ), + ] = None, + redirect_slashes: Annotated[ + bool, + Doc( + """ + Whether to detect and redirect slashes in URLs when the client doesn't + use the same format. + """ + ), + ] = True, + default: Annotated[ + Optional[ASGIApp], + Doc( + """ + Default function handler for this router. Used to handle + 404 Not Found errors. + """ + ), + ] = None, + dependency_overrides_provider: Annotated[ + Optional[Any], + Doc( + """ + Only used internally by FastAPI to handle dependency overrides. + + You shouldn't need to use it. It normally points to the `FastAPI` app + object. + """ + ), + ] = None, + route_class: Annotated[ + Type[APIRoute], + Doc( + """ + Custom route (*path operation*) class to be used by this router. + + Read more about it in the + [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). + """ + ), + ] = APIRoute, + on_startup: Annotated[ + Optional[Sequence[Callable[[], Any]]], + Doc( + """ + A list of startup event handler functions. + + You should instead use the `lifespan` handlers. + + Read more in the [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/). + """ + ), + ] = None, + on_shutdown: Annotated[ + Optional[Sequence[Callable[[], Any]]], + Doc( + """ + A list of shutdown event handler functions. + + You should instead use the `lifespan` handlers. + + Read more in the + [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/). + """ + ), + ] = None, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any - lifespan: Optional[Lifespan[Any]] = None, - deprecated: Optional[bool] = None, - include_in_schema: bool = True, - generate_unique_id_function: Callable[[APIRoute], str] = Default( - generate_unique_id - ), + lifespan: Annotated[ + Optional[Lifespan[Any]], + Doc( + """ + A `Lifespan` context manager handler. This replaces `startup` and + `shutdown` functions with a single context manager. + + Read more in the + [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/). + """ + ), + ] = None, + deprecated: Annotated[ + Optional[bool], + Doc( + """ + Mark all *path operations* in this router as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + include_in_schema: Annotated[ + bool, + Doc( + """ + To include (or not) all the *path operations* in this router in the + generated OpenAPI. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi). + """ + ), + ] = True, + generate_unique_id_function: Annotated[ + Callable[[APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), ) -> None: super().__init__( routes=routes, @@ -569,8 +844,8 @@ def add_api_route( deprecated: Optional[bool] = None, methods: Optional[Union[Set[str], List[str]]] = None, operation_id: Optional[str] = None, - response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, - response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, + response_model_include: Optional[IncEx] = None, + response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, @@ -650,8 +925,8 @@ def api_route( deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, - response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, - response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, + response_model_include: Optional[IncEx] = None, + response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, @@ -720,11 +995,63 @@ def add_api_websocket_route( def websocket( self, - path: str, - name: Optional[str] = None, + path: Annotated[ + str, + Doc( + """ + WebSocket path. + """ + ), + ], + name: Annotated[ + Optional[str], + Doc( + """ + A name for the WebSocket. Only used internally. + """ + ), + ] = None, *, - dependencies: Optional[Sequence[params.Depends]] = None, + dependencies: Annotated[ + Optional[Sequence[params.Depends]], + Doc( + """ + A list of dependencies (using `Depends()`) to be used for this + WebSocket. + + Read more about it in the + [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). + """ + ), + ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Decorate a WebSocket function. + + Read more about it in the + [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). + + **Example** + + ## Example + + ```python + from fastapi import APIRouter, FastAPI, WebSocket + + app = FastAPI() + router = APIRouter() + + @router.websocket("/ws") + async def websocket_endpoint(websocket: WebSocket): + await websocket.accept() + while True: + data = await websocket.receive_text() + await websocket.send_text(f"Message text was: {data}") + + app.include_router(router) + ``` + """ + def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies @@ -744,20 +1071,139 @@ def decorator(func: DecoratedCallable) -> DecoratedCallable: def include_router( self, - router: "APIRouter", + router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, - prefix: str = "", - tags: Optional[List[Union[str, Enum]]] = None, - dependencies: Optional[Sequence[params.Depends]] = None, - default_response_class: Type[Response] = Default(JSONResponse), - responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, - callbacks: Optional[List[BaseRoute]] = None, - deprecated: Optional[bool] = None, - include_in_schema: bool = True, - generate_unique_id_function: Callable[[APIRoute], str] = Default( - generate_unique_id - ), + prefix: Annotated[str, Doc("An optional path prefix for the router.")] = "", + tags: Annotated[ + Optional[List[Union[str, Enum]]], + Doc( + """ + A list of tags to be applied to all the *path operations* in this + router. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + dependencies: Annotated[ + Optional[Sequence[params.Depends]], + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to all the + *path operations* in this router. + + Read more about it in the + [FastAPI docs for Bigger Applications - Multiple Files](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies). + """ + ), + ] = None, + default_response_class: Annotated[ + Type[Response], + Doc( + """ + The default response class to be used. + + Read more in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class). + """ + ), + ] = Default(JSONResponse), + responses: Annotated[ + Optional[Dict[Union[int, str], Dict[str, Any]]], + Doc( + """ + Additional responses to be shown in OpenAPI. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/). + + And in the + [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies). + """ + ), + ] = None, + callbacks: Annotated[ + Optional[List[BaseRoute]], + Doc( + """ + OpenAPI callbacks that should apply to all *path operations* in this + router. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + deprecated: Annotated[ + Optional[bool], + Doc( + """ + Mark all *path operations* in this router as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include (or not) all the *path operations* in this router in the + generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = True, + generate_unique_id_function: Annotated[ + Callable[[APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), ) -> None: + """ + Include another `APIRouter` in the same current `APIRouter`. + + Read more about it in the + [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). + + ## Example + + ```python + from fastapi import APIRouter, FastAPI + + app = FastAPI() + internal_router = APIRouter() + users_router = APIRouter() + + @users_router.get("/users/") + def read_users(): + return [{"name": "Rick"}, {"name": "Morty"}] + + internal_router.include_router(users_router) + app.include_router(internal_router) + ``` + """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( @@ -865,33 +1311,354 @@ def include_router( def get( self, - path: str, + path: Annotated[ + str, + Doc( + """ + The URL path to be used for this *path operation*. + + For example, in `http://example.com/items`, the path is `/items`. + """ + ), + ], *, - response_model: Any = Default(None), - status_code: Optional[int] = None, - tags: Optional[List[Union[str, Enum]]] = None, - dependencies: Optional[Sequence[params.Depends]] = None, - summary: Optional[str] = None, - description: Optional[str] = None, - response_description: str = "Successful Response", - responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, - deprecated: Optional[bool] = None, - operation_id: Optional[str] = None, - response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, - response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, - response_model_by_alias: bool = True, - response_model_exclude_unset: bool = False, - response_model_exclude_defaults: bool = False, - response_model_exclude_none: bool = False, - include_in_schema: bool = True, - response_class: Type[Response] = Default(JSONResponse), - name: Optional[str] = None, - callbacks: Optional[List[BaseRoute]] = None, - openapi_extra: Optional[Dict[str, Any]] = None, - generate_unique_id_function: Callable[[APIRoute], str] = Default( - generate_unique_id - ), + response_model: Annotated[ + Any, + Doc( + """ + The type to use for the response. + + It could be any valid Pydantic *field* type. So, it doesn't have to + be a Pydantic model, it could be other things, like a `list`, `dict`, + etc. + + It will be used for: + + * Documentation: the generated OpenAPI (and the UI at `/docs`) will + show it as the response (JSON Schema). + * Serialization: you could return an arbitrary object and the + `response_model` would be used to serialize that object into the + corresponding JSON. + * Filtering: the JSON sent to the client will only contain the data + (fields) defined in the `response_model`. If you returned an object + that contains an attribute `password` but the `response_model` does + not include that field, the JSON sent to the client would not have + that `password`. + * Validation: whatever you return will be serialized with the + `response_model`, converting any data as necessary to generate the + corresponding JSON. But if the data in the object returned is not + valid, that would mean a violation of the contract with the client, + so it's an error from the API developer. So, FastAPI will raise an + error and return a 500 error code (Internal Server Error). + + Read more about it in the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + """ + ), + ] = Default(None), + status_code: Annotated[ + Optional[int], + Doc( + """ + The default status code to be used for the response. + + You could override the status code by returning a response directly. + + Read more about it in the + [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). + """ + ), + ] = None, + tags: Annotated[ + Optional[List[Union[str, Enum]]], + Doc( + """ + A list of tags to be applied to the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). + """ + ), + ] = None, + dependencies: Annotated[ + Optional[Sequence[params.Depends]], + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to the + *path operation*. + + Read more about it in the + [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). + """ + ), + ] = None, + summary: Annotated[ + Optional[str], + Doc( + """ + A summary for the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + A description for the *path operation*. + + If not provided, it will be extracted automatically from the docstring + of the *path operation function*. + + It can contain Markdown. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + response_description: Annotated[ + str, + Doc( + """ + The description for the default response. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = "Successful Response", + responses: Annotated[ + Optional[Dict[Union[int, str], Dict[str, Any]]], + Doc( + """ + Additional responses that could be returned by this *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + deprecated: Annotated[ + Optional[bool], + Doc( + """ + Mark this *path operation* as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + operation_id: Annotated[ + Optional[str], + Doc( + """ + Custom operation ID to be used by this *path operation*. + + By default, it is generated automatically. + + If you provide a custom operation ID, you need to make sure it is + unique for the whole API. + + You can customize the + operation ID generation with the parameter + `generate_unique_id_function` in the `FastAPI` class. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = None, + response_model_include: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to include only certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_exclude: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to exclude certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_by_alias: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response model + should be serialized by alias when an alias is used. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = True, + response_model_exclude_unset: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that were not set and + have their default values. This is different from + `response_model_exclude_defaults` in that if the fields are set, + they will be included in the response, even if the value is the same + as the default. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_defaults: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that have the same value + as the default. This is different from `response_model_exclude_unset` + in that if the fields are set but contain the same default values, + they will be excluded from the response. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_none: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data should + exclude fields set to `None`. + + This is much simpler (less smart) than `response_model_exclude_unset` + and `response_model_exclude_defaults`. You probably want to use one of + those two instead of this one, as those allow returning `None` values + when it makes sense. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). + """ + ), + ] = False, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include this *path operation* in the generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi). + """ + ), + ] = True, + response_class: Annotated[ + Type[Response], + Doc( + """ + Response class to be used for this *path operation*. + + This will not be used if you return a response directly. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). + """ + ), + ] = Default(JSONResponse), + name: Annotated[ + Optional[str], + Doc( + """ + Name for this *path operation*. Only used internally. + """ + ), + ] = None, + callbacks: Annotated[ + Optional[List[BaseRoute]], + Doc( + """ + List of *path operations* that will be used as OpenAPI callbacks. + + This is only for OpenAPI documentation, the callbacks won't be used + directly. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + openapi_extra: Annotated[ + Optional[Dict[str, Any]], + Doc( + """ + Extra metadata to be included in the OpenAPI schema for this *path + operation*. + + Read more about it in the + [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP GET operation. + + ## Example + + ```python + from fastapi import APIRouter, FastAPI + + app = FastAPI() + router = APIRouter() + + @router.get("/items/") + def read_items(): + return [{"name": "Empanada"}, {"name": "Arepa"}] + + app.include_router(router) + ``` + """ return self.api_route( path=path, response_model=response_model, @@ -921,89 +1688,741 @@ def get( def put( self, - path: str, - *, - response_model: Any = Default(None), - status_code: Optional[int] = None, - tags: Optional[List[Union[str, Enum]]] = None, - dependencies: Optional[Sequence[params.Depends]] = None, - summary: Optional[str] = None, - description: Optional[str] = None, - response_description: str = "Successful Response", - responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, - deprecated: Optional[bool] = None, - operation_id: Optional[str] = None, - response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, - response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, - response_model_by_alias: bool = True, - response_model_exclude_unset: bool = False, - response_model_exclude_defaults: bool = False, - response_model_exclude_none: bool = False, - include_in_schema: bool = True, - response_class: Type[Response] = Default(JSONResponse), - name: Optional[str] = None, - callbacks: Optional[List[BaseRoute]] = None, - openapi_extra: Optional[Dict[str, Any]] = None, - generate_unique_id_function: Callable[[APIRoute], str] = Default( - generate_unique_id - ), - ) -> Callable[[DecoratedCallable], DecoratedCallable]: - return self.api_route( - path=path, - response_model=response_model, - status_code=status_code, - tags=tags, - dependencies=dependencies, - summary=summary, - description=description, - response_description=response_description, - responses=responses, - deprecated=deprecated, - methods=["PUT"], - operation_id=operation_id, - response_model_include=response_model_include, - response_model_exclude=response_model_exclude, - response_model_by_alias=response_model_by_alias, - response_model_exclude_unset=response_model_exclude_unset, - response_model_exclude_defaults=response_model_exclude_defaults, - response_model_exclude_none=response_model_exclude_none, - include_in_schema=include_in_schema, - response_class=response_class, - name=name, - callbacks=callbacks, - openapi_extra=openapi_extra, - generate_unique_id_function=generate_unique_id_function, - ) + path: Annotated[ + str, + Doc( + """ + The URL path to be used for this *path operation*. - def post( - self, - path: str, + For example, in `http://example.com/items`, the path is `/items`. + """ + ), + ], *, - response_model: Any = Default(None), - status_code: Optional[int] = None, - tags: Optional[List[Union[str, Enum]]] = None, - dependencies: Optional[Sequence[params.Depends]] = None, - summary: Optional[str] = None, - description: Optional[str] = None, - response_description: str = "Successful Response", - responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, - deprecated: Optional[bool] = None, - operation_id: Optional[str] = None, - response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, - response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, - response_model_by_alias: bool = True, - response_model_exclude_unset: bool = False, - response_model_exclude_defaults: bool = False, - response_model_exclude_none: bool = False, - include_in_schema: bool = True, - response_class: Type[Response] = Default(JSONResponse), - name: Optional[str] = None, - callbacks: Optional[List[BaseRoute]] = None, - openapi_extra: Optional[Dict[str, Any]] = None, - generate_unique_id_function: Callable[[APIRoute], str] = Default( - generate_unique_id - ), + response_model: Annotated[ + Any, + Doc( + """ + The type to use for the response. + + It could be any valid Pydantic *field* type. So, it doesn't have to + be a Pydantic model, it could be other things, like a `list`, `dict`, + etc. + + It will be used for: + + * Documentation: the generated OpenAPI (and the UI at `/docs`) will + show it as the response (JSON Schema). + * Serialization: you could return an arbitrary object and the + `response_model` would be used to serialize that object into the + corresponding JSON. + * Filtering: the JSON sent to the client will only contain the data + (fields) defined in the `response_model`. If you returned an object + that contains an attribute `password` but the `response_model` does + not include that field, the JSON sent to the client would not have + that `password`. + * Validation: whatever you return will be serialized with the + `response_model`, converting any data as necessary to generate the + corresponding JSON. But if the data in the object returned is not + valid, that would mean a violation of the contract with the client, + so it's an error from the API developer. So, FastAPI will raise an + error and return a 500 error code (Internal Server Error). + + Read more about it in the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + """ + ), + ] = Default(None), + status_code: Annotated[ + Optional[int], + Doc( + """ + The default status code to be used for the response. + + You could override the status code by returning a response directly. + + Read more about it in the + [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). + """ + ), + ] = None, + tags: Annotated[ + Optional[List[Union[str, Enum]]], + Doc( + """ + A list of tags to be applied to the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). + """ + ), + ] = None, + dependencies: Annotated[ + Optional[Sequence[params.Depends]], + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to the + *path operation*. + + Read more about it in the + [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). + """ + ), + ] = None, + summary: Annotated[ + Optional[str], + Doc( + """ + A summary for the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + A description for the *path operation*. + + If not provided, it will be extracted automatically from the docstring + of the *path operation function*. + + It can contain Markdown. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + response_description: Annotated[ + str, + Doc( + """ + The description for the default response. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = "Successful Response", + responses: Annotated[ + Optional[Dict[Union[int, str], Dict[str, Any]]], + Doc( + """ + Additional responses that could be returned by this *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + deprecated: Annotated[ + Optional[bool], + Doc( + """ + Mark this *path operation* as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + operation_id: Annotated[ + Optional[str], + Doc( + """ + Custom operation ID to be used by this *path operation*. + + By default, it is generated automatically. + + If you provide a custom operation ID, you need to make sure it is + unique for the whole API. + + You can customize the + operation ID generation with the parameter + `generate_unique_id_function` in the `FastAPI` class. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = None, + response_model_include: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to include only certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_exclude: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to exclude certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_by_alias: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response model + should be serialized by alias when an alias is used. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = True, + response_model_exclude_unset: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that were not set and + have their default values. This is different from + `response_model_exclude_defaults` in that if the fields are set, + they will be included in the response, even if the value is the same + as the default. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_defaults: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that have the same value + as the default. This is different from `response_model_exclude_unset` + in that if the fields are set but contain the same default values, + they will be excluded from the response. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_none: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data should + exclude fields set to `None`. + + This is much simpler (less smart) than `response_model_exclude_unset` + and `response_model_exclude_defaults`. You probably want to use one of + those two instead of this one, as those allow returning `None` values + when it makes sense. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). + """ + ), + ] = False, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include this *path operation* in the generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi). + """ + ), + ] = True, + response_class: Annotated[ + Type[Response], + Doc( + """ + Response class to be used for this *path operation*. + + This will not be used if you return a response directly. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). + """ + ), + ] = Default(JSONResponse), + name: Annotated[ + Optional[str], + Doc( + """ + Name for this *path operation*. Only used internally. + """ + ), + ] = None, + callbacks: Annotated[ + Optional[List[BaseRoute]], + Doc( + """ + List of *path operations* that will be used as OpenAPI callbacks. + + This is only for OpenAPI documentation, the callbacks won't be used + directly. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + openapi_extra: Annotated[ + Optional[Dict[str, Any]], + Doc( + """ + Extra metadata to be included in the OpenAPI schema for this *path + operation*. + + Read more about it in the + [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP PUT operation. + + ## Example + + ```python + from fastapi import APIRouter, FastAPI + from pydantic import BaseModel + + class Item(BaseModel): + name: str + description: str | None = None + + app = FastAPI() + router = APIRouter() + + @router.put("/items/{item_id}") + def replace_item(item_id: str, item: Item): + return {"message": "Item replaced", "id": item_id} + + app.include_router(router) + ``` + """ + return self.api_route( + path=path, + response_model=response_model, + status_code=status_code, + tags=tags, + dependencies=dependencies, + summary=summary, + description=description, + response_description=response_description, + responses=responses, + deprecated=deprecated, + methods=["PUT"], + operation_id=operation_id, + response_model_include=response_model_include, + response_model_exclude=response_model_exclude, + response_model_by_alias=response_model_by_alias, + response_model_exclude_unset=response_model_exclude_unset, + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, + include_in_schema=include_in_schema, + response_class=response_class, + name=name, + callbacks=callbacks, + openapi_extra=openapi_extra, + generate_unique_id_function=generate_unique_id_function, + ) + + def post( + self, + path: Annotated[ + str, + Doc( + """ + The URL path to be used for this *path operation*. + + For example, in `http://example.com/items`, the path is `/items`. + """ + ), + ], + *, + response_model: Annotated[ + Any, + Doc( + """ + The type to use for the response. + + It could be any valid Pydantic *field* type. So, it doesn't have to + be a Pydantic model, it could be other things, like a `list`, `dict`, + etc. + + It will be used for: + + * Documentation: the generated OpenAPI (and the UI at `/docs`) will + show it as the response (JSON Schema). + * Serialization: you could return an arbitrary object and the + `response_model` would be used to serialize that object into the + corresponding JSON. + * Filtering: the JSON sent to the client will only contain the data + (fields) defined in the `response_model`. If you returned an object + that contains an attribute `password` but the `response_model` does + not include that field, the JSON sent to the client would not have + that `password`. + * Validation: whatever you return will be serialized with the + `response_model`, converting any data as necessary to generate the + corresponding JSON. But if the data in the object returned is not + valid, that would mean a violation of the contract with the client, + so it's an error from the API developer. So, FastAPI will raise an + error and return a 500 error code (Internal Server Error). + + Read more about it in the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + """ + ), + ] = Default(None), + status_code: Annotated[ + Optional[int], + Doc( + """ + The default status code to be used for the response. + + You could override the status code by returning a response directly. + + Read more about it in the + [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). + """ + ), + ] = None, + tags: Annotated[ + Optional[List[Union[str, Enum]]], + Doc( + """ + A list of tags to be applied to the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). + """ + ), + ] = None, + dependencies: Annotated[ + Optional[Sequence[params.Depends]], + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to the + *path operation*. + + Read more about it in the + [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). + """ + ), + ] = None, + summary: Annotated[ + Optional[str], + Doc( + """ + A summary for the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + A description for the *path operation*. + + If not provided, it will be extracted automatically from the docstring + of the *path operation function*. + + It can contain Markdown. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + response_description: Annotated[ + str, + Doc( + """ + The description for the default response. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = "Successful Response", + responses: Annotated[ + Optional[Dict[Union[int, str], Dict[str, Any]]], + Doc( + """ + Additional responses that could be returned by this *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + deprecated: Annotated[ + Optional[bool], + Doc( + """ + Mark this *path operation* as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + operation_id: Annotated[ + Optional[str], + Doc( + """ + Custom operation ID to be used by this *path operation*. + + By default, it is generated automatically. + + If you provide a custom operation ID, you need to make sure it is + unique for the whole API. + + You can customize the + operation ID generation with the parameter + `generate_unique_id_function` in the `FastAPI` class. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = None, + response_model_include: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to include only certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_exclude: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to exclude certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_by_alias: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response model + should be serialized by alias when an alias is used. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = True, + response_model_exclude_unset: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that were not set and + have their default values. This is different from + `response_model_exclude_defaults` in that if the fields are set, + they will be included in the response, even if the value is the same + as the default. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_defaults: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that have the same value + as the default. This is different from `response_model_exclude_unset` + in that if the fields are set but contain the same default values, + they will be excluded from the response. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_none: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data should + exclude fields set to `None`. + + This is much simpler (less smart) than `response_model_exclude_unset` + and `response_model_exclude_defaults`. You probably want to use one of + those two instead of this one, as those allow returning `None` values + when it makes sense. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). + """ + ), + ] = False, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include this *path operation* in the generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi). + """ + ), + ] = True, + response_class: Annotated[ + Type[Response], + Doc( + """ + Response class to be used for this *path operation*. + + This will not be used if you return a response directly. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). + """ + ), + ] = Default(JSONResponse), + name: Annotated[ + Optional[str], + Doc( + """ + Name for this *path operation*. Only used internally. + """ + ), + ] = None, + callbacks: Annotated[ + Optional[List[BaseRoute]], + Doc( + """ + List of *path operations* that will be used as OpenAPI callbacks. + + This is only for OpenAPI documentation, the callbacks won't be used + directly. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + openapi_extra: Annotated[ + Optional[Dict[str, Any]], + Doc( + """ + Extra metadata to be included in the OpenAPI schema for this *path + operation*. + + Read more about it in the + [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP POST operation. + + ## Example + + ```python + from fastapi import APIRouter, FastAPI + from pydantic import BaseModel + + class Item(BaseModel): + name: str + description: str | None = None + + app = FastAPI() + router = APIRouter() + + @router.post("/items/") + def create_item(item: Item): + return {"message": "Item created"} + + app.include_router(router) + ``` + """ return self.api_route( path=path, response_model=response_model, @@ -1033,33 +2452,354 @@ def post( def delete( self, - path: str, + path: Annotated[ + str, + Doc( + """ + The URL path to be used for this *path operation*. + + For example, in `http://example.com/items`, the path is `/items`. + """ + ), + ], *, - response_model: Any = Default(None), - status_code: Optional[int] = None, - tags: Optional[List[Union[str, Enum]]] = None, - dependencies: Optional[Sequence[params.Depends]] = None, - summary: Optional[str] = None, - description: Optional[str] = None, - response_description: str = "Successful Response", - responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, - deprecated: Optional[bool] = None, - operation_id: Optional[str] = None, - response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, - response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, - response_model_by_alias: bool = True, - response_model_exclude_unset: bool = False, - response_model_exclude_defaults: bool = False, - response_model_exclude_none: bool = False, - include_in_schema: bool = True, - response_class: Type[Response] = Default(JSONResponse), - name: Optional[str] = None, - callbacks: Optional[List[BaseRoute]] = None, - openapi_extra: Optional[Dict[str, Any]] = None, - generate_unique_id_function: Callable[[APIRoute], str] = Default( - generate_unique_id - ), + response_model: Annotated[ + Any, + Doc( + """ + The type to use for the response. + + It could be any valid Pydantic *field* type. So, it doesn't have to + be a Pydantic model, it could be other things, like a `list`, `dict`, + etc. + + It will be used for: + + * Documentation: the generated OpenAPI (and the UI at `/docs`) will + show it as the response (JSON Schema). + * Serialization: you could return an arbitrary object and the + `response_model` would be used to serialize that object into the + corresponding JSON. + * Filtering: the JSON sent to the client will only contain the data + (fields) defined in the `response_model`. If you returned an object + that contains an attribute `password` but the `response_model` does + not include that field, the JSON sent to the client would not have + that `password`. + * Validation: whatever you return will be serialized with the + `response_model`, converting any data as necessary to generate the + corresponding JSON. But if the data in the object returned is not + valid, that would mean a violation of the contract with the client, + so it's an error from the API developer. So, FastAPI will raise an + error and return a 500 error code (Internal Server Error). + + Read more about it in the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + """ + ), + ] = Default(None), + status_code: Annotated[ + Optional[int], + Doc( + """ + The default status code to be used for the response. + + You could override the status code by returning a response directly. + + Read more about it in the + [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). + """ + ), + ] = None, + tags: Annotated[ + Optional[List[Union[str, Enum]]], + Doc( + """ + A list of tags to be applied to the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). + """ + ), + ] = None, + dependencies: Annotated[ + Optional[Sequence[params.Depends]], + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to the + *path operation*. + + Read more about it in the + [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). + """ + ), + ] = None, + summary: Annotated[ + Optional[str], + Doc( + """ + A summary for the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + A description for the *path operation*. + + If not provided, it will be extracted automatically from the docstring + of the *path operation function*. + + It can contain Markdown. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + response_description: Annotated[ + str, + Doc( + """ + The description for the default response. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = "Successful Response", + responses: Annotated[ + Optional[Dict[Union[int, str], Dict[str, Any]]], + Doc( + """ + Additional responses that could be returned by this *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + deprecated: Annotated[ + Optional[bool], + Doc( + """ + Mark this *path operation* as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + operation_id: Annotated[ + Optional[str], + Doc( + """ + Custom operation ID to be used by this *path operation*. + + By default, it is generated automatically. + + If you provide a custom operation ID, you need to make sure it is + unique for the whole API. + + You can customize the + operation ID generation with the parameter + `generate_unique_id_function` in the `FastAPI` class. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = None, + response_model_include: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to include only certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_exclude: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to exclude certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_by_alias: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response model + should be serialized by alias when an alias is used. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = True, + response_model_exclude_unset: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that were not set and + have their default values. This is different from + `response_model_exclude_defaults` in that if the fields are set, + they will be included in the response, even if the value is the same + as the default. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_defaults: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that have the same value + as the default. This is different from `response_model_exclude_unset` + in that if the fields are set but contain the same default values, + they will be excluded from the response. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_none: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data should + exclude fields set to `None`. + + This is much simpler (less smart) than `response_model_exclude_unset` + and `response_model_exclude_defaults`. You probably want to use one of + those two instead of this one, as those allow returning `None` values + when it makes sense. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). + """ + ), + ] = False, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include this *path operation* in the generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi). + """ + ), + ] = True, + response_class: Annotated[ + Type[Response], + Doc( + """ + Response class to be used for this *path operation*. + + This will not be used if you return a response directly. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). + """ + ), + ] = Default(JSONResponse), + name: Annotated[ + Optional[str], + Doc( + """ + Name for this *path operation*. Only used internally. + """ + ), + ] = None, + callbacks: Annotated[ + Optional[List[BaseRoute]], + Doc( + """ + List of *path operations* that will be used as OpenAPI callbacks. + + This is only for OpenAPI documentation, the callbacks won't be used + directly. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + openapi_extra: Annotated[ + Optional[Dict[str, Any]], + Doc( + """ + Extra metadata to be included in the OpenAPI schema for this *path + operation*. + + Read more about it in the + [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP DELETE operation. + + ## Example + + ```python + from fastapi import APIRouter, FastAPI + + app = FastAPI() + router = APIRouter() + + @router.delete("/items/{item_id}") + def delete_item(item_id: str): + return {"message": "Item deleted"} + + app.include_router(router) + ``` + """ return self.api_route( path=path, response_model=response_model, @@ -1089,33 +2829,354 @@ def delete( def options( self, - path: str, + path: Annotated[ + str, + Doc( + """ + The URL path to be used for this *path operation*. + + For example, in `http://example.com/items`, the path is `/items`. + """ + ), + ], *, - response_model: Any = Default(None), - status_code: Optional[int] = None, - tags: Optional[List[Union[str, Enum]]] = None, - dependencies: Optional[Sequence[params.Depends]] = None, - summary: Optional[str] = None, - description: Optional[str] = None, - response_description: str = "Successful Response", - responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, - deprecated: Optional[bool] = None, - operation_id: Optional[str] = None, - response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, - response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, - response_model_by_alias: bool = True, - response_model_exclude_unset: bool = False, - response_model_exclude_defaults: bool = False, - response_model_exclude_none: bool = False, - include_in_schema: bool = True, - response_class: Type[Response] = Default(JSONResponse), - name: Optional[str] = None, - callbacks: Optional[List[BaseRoute]] = None, - openapi_extra: Optional[Dict[str, Any]] = None, - generate_unique_id_function: Callable[[APIRoute], str] = Default( - generate_unique_id - ), + response_model: Annotated[ + Any, + Doc( + """ + The type to use for the response. + + It could be any valid Pydantic *field* type. So, it doesn't have to + be a Pydantic model, it could be other things, like a `list`, `dict`, + etc. + + It will be used for: + + * Documentation: the generated OpenAPI (and the UI at `/docs`) will + show it as the response (JSON Schema). + * Serialization: you could return an arbitrary object and the + `response_model` would be used to serialize that object into the + corresponding JSON. + * Filtering: the JSON sent to the client will only contain the data + (fields) defined in the `response_model`. If you returned an object + that contains an attribute `password` but the `response_model` does + not include that field, the JSON sent to the client would not have + that `password`. + * Validation: whatever you return will be serialized with the + `response_model`, converting any data as necessary to generate the + corresponding JSON. But if the data in the object returned is not + valid, that would mean a violation of the contract with the client, + so it's an error from the API developer. So, FastAPI will raise an + error and return a 500 error code (Internal Server Error). + + Read more about it in the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + """ + ), + ] = Default(None), + status_code: Annotated[ + Optional[int], + Doc( + """ + The default status code to be used for the response. + + You could override the status code by returning a response directly. + + Read more about it in the + [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). + """ + ), + ] = None, + tags: Annotated[ + Optional[List[Union[str, Enum]]], + Doc( + """ + A list of tags to be applied to the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). + """ + ), + ] = None, + dependencies: Annotated[ + Optional[Sequence[params.Depends]], + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to the + *path operation*. + + Read more about it in the + [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). + """ + ), + ] = None, + summary: Annotated[ + Optional[str], + Doc( + """ + A summary for the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + A description for the *path operation*. + + If not provided, it will be extracted automatically from the docstring + of the *path operation function*. + + It can contain Markdown. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + response_description: Annotated[ + str, + Doc( + """ + The description for the default response. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = "Successful Response", + responses: Annotated[ + Optional[Dict[Union[int, str], Dict[str, Any]]], + Doc( + """ + Additional responses that could be returned by this *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + deprecated: Annotated[ + Optional[bool], + Doc( + """ + Mark this *path operation* as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + operation_id: Annotated[ + Optional[str], + Doc( + """ + Custom operation ID to be used by this *path operation*. + + By default, it is generated automatically. + + If you provide a custom operation ID, you need to make sure it is + unique for the whole API. + + You can customize the + operation ID generation with the parameter + `generate_unique_id_function` in the `FastAPI` class. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = None, + response_model_include: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to include only certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_exclude: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to exclude certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_by_alias: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response model + should be serialized by alias when an alias is used. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = True, + response_model_exclude_unset: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that were not set and + have their default values. This is different from + `response_model_exclude_defaults` in that if the fields are set, + they will be included in the response, even if the value is the same + as the default. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_defaults: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that have the same value + as the default. This is different from `response_model_exclude_unset` + in that if the fields are set but contain the same default values, + they will be excluded from the response. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_none: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data should + exclude fields set to `None`. + + This is much simpler (less smart) than `response_model_exclude_unset` + and `response_model_exclude_defaults`. You probably want to use one of + those two instead of this one, as those allow returning `None` values + when it makes sense. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). + """ + ), + ] = False, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include this *path operation* in the generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi). + """ + ), + ] = True, + response_class: Annotated[ + Type[Response], + Doc( + """ + Response class to be used for this *path operation*. + + This will not be used if you return a response directly. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). + """ + ), + ] = Default(JSONResponse), + name: Annotated[ + Optional[str], + Doc( + """ + Name for this *path operation*. Only used internally. + """ + ), + ] = None, + callbacks: Annotated[ + Optional[List[BaseRoute]], + Doc( + """ + List of *path operations* that will be used as OpenAPI callbacks. + + This is only for OpenAPI documentation, the callbacks won't be used + directly. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + openapi_extra: Annotated[ + Optional[Dict[str, Any]], + Doc( + """ + Extra metadata to be included in the OpenAPI schema for this *path + operation*. + + Read more about it in the + [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP OPTIONS operation. + + ## Example + + ```python + from fastapi import APIRouter, FastAPI + + app = FastAPI() + router = APIRouter() + + @router.options("/items/") + def get_item_options(): + return {"additions": ["Aji", "Guacamole"]} + + app.include_router(router) + ``` + """ return self.api_route( path=path, response_model=response_model, @@ -1145,33 +3206,359 @@ def options( def head( self, - path: str, + path: Annotated[ + str, + Doc( + """ + The URL path to be used for this *path operation*. + + For example, in `http://example.com/items`, the path is `/items`. + """ + ), + ], *, - response_model: Any = Default(None), - status_code: Optional[int] = None, - tags: Optional[List[Union[str, Enum]]] = None, - dependencies: Optional[Sequence[params.Depends]] = None, - summary: Optional[str] = None, - description: Optional[str] = None, - response_description: str = "Successful Response", - responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, - deprecated: Optional[bool] = None, - operation_id: Optional[str] = None, - response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, - response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, - response_model_by_alias: bool = True, - response_model_exclude_unset: bool = False, - response_model_exclude_defaults: bool = False, - response_model_exclude_none: bool = False, - include_in_schema: bool = True, - response_class: Type[Response] = Default(JSONResponse), - name: Optional[str] = None, - callbacks: Optional[List[BaseRoute]] = None, - openapi_extra: Optional[Dict[str, Any]] = None, - generate_unique_id_function: Callable[[APIRoute], str] = Default( - generate_unique_id - ), + response_model: Annotated[ + Any, + Doc( + """ + The type to use for the response. + + It could be any valid Pydantic *field* type. So, it doesn't have to + be a Pydantic model, it could be other things, like a `list`, `dict`, + etc. + + It will be used for: + + * Documentation: the generated OpenAPI (and the UI at `/docs`) will + show it as the response (JSON Schema). + * Serialization: you could return an arbitrary object and the + `response_model` would be used to serialize that object into the + corresponding JSON. + * Filtering: the JSON sent to the client will only contain the data + (fields) defined in the `response_model`. If you returned an object + that contains an attribute `password` but the `response_model` does + not include that field, the JSON sent to the client would not have + that `password`. + * Validation: whatever you return will be serialized with the + `response_model`, converting any data as necessary to generate the + corresponding JSON. But if the data in the object returned is not + valid, that would mean a violation of the contract with the client, + so it's an error from the API developer. So, FastAPI will raise an + error and return a 500 error code (Internal Server Error). + + Read more about it in the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + """ + ), + ] = Default(None), + status_code: Annotated[ + Optional[int], + Doc( + """ + The default status code to be used for the response. + + You could override the status code by returning a response directly. + + Read more about it in the + [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). + """ + ), + ] = None, + tags: Annotated[ + Optional[List[Union[str, Enum]]], + Doc( + """ + A list of tags to be applied to the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). + """ + ), + ] = None, + dependencies: Annotated[ + Optional[Sequence[params.Depends]], + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to the + *path operation*. + + Read more about it in the + [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). + """ + ), + ] = None, + summary: Annotated[ + Optional[str], + Doc( + """ + A summary for the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + A description for the *path operation*. + + If not provided, it will be extracted automatically from the docstring + of the *path operation function*. + + It can contain Markdown. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + response_description: Annotated[ + str, + Doc( + """ + The description for the default response. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = "Successful Response", + responses: Annotated[ + Optional[Dict[Union[int, str], Dict[str, Any]]], + Doc( + """ + Additional responses that could be returned by this *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + deprecated: Annotated[ + Optional[bool], + Doc( + """ + Mark this *path operation* as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + operation_id: Annotated[ + Optional[str], + Doc( + """ + Custom operation ID to be used by this *path operation*. + + By default, it is generated automatically. + + If you provide a custom operation ID, you need to make sure it is + unique for the whole API. + + You can customize the + operation ID generation with the parameter + `generate_unique_id_function` in the `FastAPI` class. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = None, + response_model_include: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to include only certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_exclude: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to exclude certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_by_alias: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response model + should be serialized by alias when an alias is used. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = True, + response_model_exclude_unset: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that were not set and + have their default values. This is different from + `response_model_exclude_defaults` in that if the fields are set, + they will be included in the response, even if the value is the same + as the default. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_defaults: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that have the same value + as the default. This is different from `response_model_exclude_unset` + in that if the fields are set but contain the same default values, + they will be excluded from the response. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_none: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data should + exclude fields set to `None`. + + This is much simpler (less smart) than `response_model_exclude_unset` + and `response_model_exclude_defaults`. You probably want to use one of + those two instead of this one, as those allow returning `None` values + when it makes sense. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). + """ + ), + ] = False, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include this *path operation* in the generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi). + """ + ), + ] = True, + response_class: Annotated[ + Type[Response], + Doc( + """ + Response class to be used for this *path operation*. + + This will not be used if you return a response directly. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). + """ + ), + ] = Default(JSONResponse), + name: Annotated[ + Optional[str], + Doc( + """ + Name for this *path operation*. Only used internally. + """ + ), + ] = None, + callbacks: Annotated[ + Optional[List[BaseRoute]], + Doc( + """ + List of *path operations* that will be used as OpenAPI callbacks. + + This is only for OpenAPI documentation, the callbacks won't be used + directly. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + openapi_extra: Annotated[ + Optional[Dict[str, Any]], + Doc( + """ + Extra metadata to be included in the OpenAPI schema for this *path + operation*. + + Read more about it in the + [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP HEAD operation. + + ## Example + + ```python + from fastapi import APIRouter, FastAPI + from pydantic import BaseModel + + class Item(BaseModel): + name: str + description: str | None = None + + app = FastAPI() + router = APIRouter() + + @router.head("/items/", status_code=204) + def get_items_headers(response: Response): + response.headers["X-Cat-Dog"] = "Alone in the world" + + app.include_router(router) + ``` + """ return self.api_route( path=path, response_model=response_model, @@ -1201,33 +3588,359 @@ def head( def patch( self, - path: str, + path: Annotated[ + str, + Doc( + """ + The URL path to be used for this *path operation*. + + For example, in `http://example.com/items`, the path is `/items`. + """ + ), + ], *, - response_model: Any = Default(None), - status_code: Optional[int] = None, - tags: Optional[List[Union[str, Enum]]] = None, - dependencies: Optional[Sequence[params.Depends]] = None, - summary: Optional[str] = None, - description: Optional[str] = None, - response_description: str = "Successful Response", - responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, - deprecated: Optional[bool] = None, - operation_id: Optional[str] = None, - response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, - response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, - response_model_by_alias: bool = True, - response_model_exclude_unset: bool = False, - response_model_exclude_defaults: bool = False, - response_model_exclude_none: bool = False, - include_in_schema: bool = True, - response_class: Type[Response] = Default(JSONResponse), - name: Optional[str] = None, - callbacks: Optional[List[BaseRoute]] = None, - openapi_extra: Optional[Dict[str, Any]] = None, - generate_unique_id_function: Callable[[APIRoute], str] = Default( - generate_unique_id - ), + response_model: Annotated[ + Any, + Doc( + """ + The type to use for the response. + + It could be any valid Pydantic *field* type. So, it doesn't have to + be a Pydantic model, it could be other things, like a `list`, `dict`, + etc. + + It will be used for: + + * Documentation: the generated OpenAPI (and the UI at `/docs`) will + show it as the response (JSON Schema). + * Serialization: you could return an arbitrary object and the + `response_model` would be used to serialize that object into the + corresponding JSON. + * Filtering: the JSON sent to the client will only contain the data + (fields) defined in the `response_model`. If you returned an object + that contains an attribute `password` but the `response_model` does + not include that field, the JSON sent to the client would not have + that `password`. + * Validation: whatever you return will be serialized with the + `response_model`, converting any data as necessary to generate the + corresponding JSON. But if the data in the object returned is not + valid, that would mean a violation of the contract with the client, + so it's an error from the API developer. So, FastAPI will raise an + error and return a 500 error code (Internal Server Error). + + Read more about it in the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + """ + ), + ] = Default(None), + status_code: Annotated[ + Optional[int], + Doc( + """ + The default status code to be used for the response. + + You could override the status code by returning a response directly. + + Read more about it in the + [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). + """ + ), + ] = None, + tags: Annotated[ + Optional[List[Union[str, Enum]]], + Doc( + """ + A list of tags to be applied to the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). + """ + ), + ] = None, + dependencies: Annotated[ + Optional[Sequence[params.Depends]], + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to the + *path operation*. + + Read more about it in the + [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). + """ + ), + ] = None, + summary: Annotated[ + Optional[str], + Doc( + """ + A summary for the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + A description for the *path operation*. + + If not provided, it will be extracted automatically from the docstring + of the *path operation function*. + + It can contain Markdown. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + response_description: Annotated[ + str, + Doc( + """ + The description for the default response. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = "Successful Response", + responses: Annotated[ + Optional[Dict[Union[int, str], Dict[str, Any]]], + Doc( + """ + Additional responses that could be returned by this *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + deprecated: Annotated[ + Optional[bool], + Doc( + """ + Mark this *path operation* as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + operation_id: Annotated[ + Optional[str], + Doc( + """ + Custom operation ID to be used by this *path operation*. + + By default, it is generated automatically. + + If you provide a custom operation ID, you need to make sure it is + unique for the whole API. + + You can customize the + operation ID generation with the parameter + `generate_unique_id_function` in the `FastAPI` class. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = None, + response_model_include: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to include only certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_exclude: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to exclude certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_by_alias: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response model + should be serialized by alias when an alias is used. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = True, + response_model_exclude_unset: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that were not set and + have their default values. This is different from + `response_model_exclude_defaults` in that if the fields are set, + they will be included in the response, even if the value is the same + as the default. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_defaults: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that have the same value + as the default. This is different from `response_model_exclude_unset` + in that if the fields are set but contain the same default values, + they will be excluded from the response. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_none: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data should + exclude fields set to `None`. + + This is much simpler (less smart) than `response_model_exclude_unset` + and `response_model_exclude_defaults`. You probably want to use one of + those two instead of this one, as those allow returning `None` values + when it makes sense. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). + """ + ), + ] = False, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include this *path operation* in the generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi). + """ + ), + ] = True, + response_class: Annotated[ + Type[Response], + Doc( + """ + Response class to be used for this *path operation*. + + This will not be used if you return a response directly. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). + """ + ), + ] = Default(JSONResponse), + name: Annotated[ + Optional[str], + Doc( + """ + Name for this *path operation*. Only used internally. + """ + ), + ] = None, + callbacks: Annotated[ + Optional[List[BaseRoute]], + Doc( + """ + List of *path operations* that will be used as OpenAPI callbacks. + + This is only for OpenAPI documentation, the callbacks won't be used + directly. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + openapi_extra: Annotated[ + Optional[Dict[str, Any]], + Doc( + """ + Extra metadata to be included in the OpenAPI schema for this *path + operation*. + + Read more about it in the + [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP PATCH operation. + + ## Example + + ```python + from fastapi import APIRouter, FastAPI + from pydantic import BaseModel + + class Item(BaseModel): + name: str + description: str | None = None + + app = FastAPI() + router = APIRouter() + + @router.patch("/items/") + def update_item(item: Item): + return {"message": "Item updated in place"} + + app.include_router(router) + ``` + """ return self.api_route( path=path, response_model=response_model, @@ -1257,33 +3970,359 @@ def patch( def trace( self, - path: str, + path: Annotated[ + str, + Doc( + """ + The URL path to be used for this *path operation*. + + For example, in `http://example.com/items`, the path is `/items`. + """ + ), + ], *, - response_model: Any = Default(None), - status_code: Optional[int] = None, - tags: Optional[List[Union[str, Enum]]] = None, - dependencies: Optional[Sequence[params.Depends]] = None, - summary: Optional[str] = None, - description: Optional[str] = None, - response_description: str = "Successful Response", - responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, - deprecated: Optional[bool] = None, - operation_id: Optional[str] = None, - response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, - response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, - response_model_by_alias: bool = True, - response_model_exclude_unset: bool = False, - response_model_exclude_defaults: bool = False, - response_model_exclude_none: bool = False, - include_in_schema: bool = True, - response_class: Type[Response] = Default(JSONResponse), - name: Optional[str] = None, - callbacks: Optional[List[BaseRoute]] = None, - openapi_extra: Optional[Dict[str, Any]] = None, - generate_unique_id_function: Callable[[APIRoute], str] = Default( - generate_unique_id - ), + response_model: Annotated[ + Any, + Doc( + """ + The type to use for the response. + + It could be any valid Pydantic *field* type. So, it doesn't have to + be a Pydantic model, it could be other things, like a `list`, `dict`, + etc. + + It will be used for: + + * Documentation: the generated OpenAPI (and the UI at `/docs`) will + show it as the response (JSON Schema). + * Serialization: you could return an arbitrary object and the + `response_model` would be used to serialize that object into the + corresponding JSON. + * Filtering: the JSON sent to the client will only contain the data + (fields) defined in the `response_model`. If you returned an object + that contains an attribute `password` but the `response_model` does + not include that field, the JSON sent to the client would not have + that `password`. + * Validation: whatever you return will be serialized with the + `response_model`, converting any data as necessary to generate the + corresponding JSON. But if the data in the object returned is not + valid, that would mean a violation of the contract with the client, + so it's an error from the API developer. So, FastAPI will raise an + error and return a 500 error code (Internal Server Error). + + Read more about it in the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + """ + ), + ] = Default(None), + status_code: Annotated[ + Optional[int], + Doc( + """ + The default status code to be used for the response. + + You could override the status code by returning a response directly. + + Read more about it in the + [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). + """ + ), + ] = None, + tags: Annotated[ + Optional[List[Union[str, Enum]]], + Doc( + """ + A list of tags to be applied to the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). + """ + ), + ] = None, + dependencies: Annotated[ + Optional[Sequence[params.Depends]], + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to the + *path operation*. + + Read more about it in the + [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). + """ + ), + ] = None, + summary: Annotated[ + Optional[str], + Doc( + """ + A summary for the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + A description for the *path operation*. + + If not provided, it will be extracted automatically from the docstring + of the *path operation function*. + + It can contain Markdown. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + response_description: Annotated[ + str, + Doc( + """ + The description for the default response. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = "Successful Response", + responses: Annotated[ + Optional[Dict[Union[int, str], Dict[str, Any]]], + Doc( + """ + Additional responses that could be returned by this *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + deprecated: Annotated[ + Optional[bool], + Doc( + """ + Mark this *path operation* as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + operation_id: Annotated[ + Optional[str], + Doc( + """ + Custom operation ID to be used by this *path operation*. + + By default, it is generated automatically. + + If you provide a custom operation ID, you need to make sure it is + unique for the whole API. + + You can customize the + operation ID generation with the parameter + `generate_unique_id_function` in the `FastAPI` class. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = None, + response_model_include: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to include only certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_exclude: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to exclude certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_by_alias: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response model + should be serialized by alias when an alias is used. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = True, + response_model_exclude_unset: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that were not set and + have their default values. This is different from + `response_model_exclude_defaults` in that if the fields are set, + they will be included in the response, even if the value is the same + as the default. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_defaults: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that have the same value + as the default. This is different from `response_model_exclude_unset` + in that if the fields are set but contain the same default values, + they will be excluded from the response. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_none: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data should + exclude fields set to `None`. + + This is much simpler (less smart) than `response_model_exclude_unset` + and `response_model_exclude_defaults`. You probably want to use one of + those two instead of this one, as those allow returning `None` values + when it makes sense. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). + """ + ), + ] = False, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include this *path operation* in the generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi). + """ + ), + ] = True, + response_class: Annotated[ + Type[Response], + Doc( + """ + Response class to be used for this *path operation*. + + This will not be used if you return a response directly. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). + """ + ), + ] = Default(JSONResponse), + name: Annotated[ + Optional[str], + Doc( + """ + Name for this *path operation*. Only used internally. + """ + ), + ] = None, + callbacks: Annotated[ + Optional[List[BaseRoute]], + Doc( + """ + List of *path operations* that will be used as OpenAPI callbacks. + + This is only for OpenAPI documentation, the callbacks won't be used + directly. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + openapi_extra: Annotated[ + Optional[Dict[str, Any]], + Doc( + """ + Extra metadata to be included in the OpenAPI schema for this *path + operation*. + + Read more about it in the + [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP TRACE operation. + + ## Example + + ```python + from fastapi import APIRouter, FastAPI + from pydantic import BaseModel + + class Item(BaseModel): + name: str + description: str | None = None + + app = FastAPI() + router = APIRouter() + + @router.trace("/items/{item_id}") + def trace_item(item_id: str): + return None + + app.include_router(router) + ``` + """ return self.api_route( path=path, response_model=response_model, @@ -1311,9 +4350,34 @@ def trace( generate_unique_id_function=generate_unique_id_function, ) + @deprecated( + """ + on_event is deprecated, use lifespan event handlers instead. + + Read more about it in the + [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). + """ + ) def on_event( - self, event_type: str + self, + event_type: Annotated[ + str, + Doc( + """ + The type of event. `startup` or `shutdown`. + """ + ), + ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add an event handler for the router. + + `on_event` is deprecated, use `lifespan` event handlers instead. + + Read more about it in the + [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). + """ + def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func diff --git a/fastapi/security/api_key.py b/fastapi/security/api_key.py index 8b2c5c08059fc..b1a6b4f94b4dd 100644 --- a/fastapi/security/api_key.py +++ b/fastapi/security/api_key.py @@ -5,6 +5,7 @@ from starlette.exceptions import HTTPException from starlette.requests import Request from starlette.status import HTTP_403_FORBIDDEN +from typing_extensions import Annotated, Doc # type: ignore [attr-defined] class APIKeyBase(SecurityBase): @@ -12,13 +13,83 @@ class APIKeyBase(SecurityBase): class APIKeyQuery(APIKeyBase): + """ + API key authentication using a query parameter. + + This defines the name of the query parameter that should be provided in the request + with the API key and integrates that into the OpenAPI documentation. It extracts + the key value sent in the query parameter automatically and provides it as the + dependency result. But it doesn't define how to send that API key to the client. + + ## Usage + + Create an instance object and use that object as the dependency in `Depends()`. + + The dependency result will be a string containing the key value. + + ## Example + + ```python + from fastapi import Depends, FastAPI + from fastapi.security import APIKeyQuery + + app = FastAPI() + + query_scheme = APIKeyQuery(name="api_key") + + + @app.get("/items/") + async def read_items(api_key: str = Depends(query_scheme)): + return {"api_key": api_key} + ``` + """ + def __init__( self, *, - name: str, - scheme_name: Optional[str] = None, - description: Optional[str] = None, - auto_error: bool = True, + name: Annotated[ + str, + Doc("Query parameter name."), + ], + scheme_name: Annotated[ + Optional[str], + Doc( + """ + Security scheme name. + + It will be included in the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + Security scheme description. + + It will be included in the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + auto_error: Annotated[ + bool, + Doc( + """ + By default, if the query parameter is not provided, `APIKeyQuery` will + automatically cancel the request and sebd the client an error. + + If `auto_error` is set to `False`, when the query parameter is not + available, instead of erroring out, the dependency result will be + `None`. + + This is useful when you want to have optional authentication. + + It is also useful when you want to have authentication that can be + provided in one of multiple optional ways (for example, in a query + parameter or in an HTTP Bearer token). + """ + ), + ] = True, ): self.model: APIKey = APIKey( **{"in": APIKeyIn.query}, # type: ignore[arg-type] @@ -41,13 +112,79 @@ async def __call__(self, request: Request) -> Optional[str]: class APIKeyHeader(APIKeyBase): + """ + API key authentication using a header. + + This defines the name of the header that should be provided in the request with + the API key and integrates that into the OpenAPI documentation. It extracts + the key value sent in the header automatically and provides it as the dependency + result. But it doesn't define how to send that key to the client. + + ## Usage + + Create an instance object and use that object as the dependency in `Depends()`. + + The dependency result will be a string containing the key value. + + ## Example + + ```python + from fastapi import Depends, FastAPI + from fastapi.security import APIKeyHeader + + app = FastAPI() + + header_scheme = APIKeyHeader(name="x-key") + + + @app.get("/items/") + async def read_items(key: str = Depends(header_scheme)): + return {"key": key} + ``` + """ + def __init__( self, *, - name: str, - scheme_name: Optional[str] = None, - description: Optional[str] = None, - auto_error: bool = True, + name: Annotated[str, Doc("Header name.")], + scheme_name: Annotated[ + Optional[str], + Doc( + """ + Security scheme name. + + It will be included in the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + Security scheme description. + + It will be included in the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + auto_error: Annotated[ + bool, + Doc( + """ + By default, if the header is not provided, `APIKeyHeader` will + automatically cancel the request and send the client an error. + + If `auto_error` is set to `False`, when the header is not available, + instead of erroring out, the dependency result will be `None`. + + This is useful when you want to have optional authentication. + + It is also useful when you want to have authentication that can be + provided in one of multiple optional ways (for example, in a header or + in an HTTP Bearer token). + """ + ), + ] = True, ): self.model: APIKey = APIKey( **{"in": APIKeyIn.header}, # type: ignore[arg-type] @@ -70,13 +207,79 @@ async def __call__(self, request: Request) -> Optional[str]: class APIKeyCookie(APIKeyBase): + """ + API key authentication using a cookie. + + This defines the name of the cookie that should be provided in the request with + the API key and integrates that into the OpenAPI documentation. It extracts + the key value sent in the cookie automatically and provides it as the dependency + result. But it doesn't define how to set that cookie. + + ## Usage + + Create an instance object and use that object as the dependency in `Depends()`. + + The dependency result will be a string containing the key value. + + ## Example + + ```python + from fastapi import Depends, FastAPI + from fastapi.security import APIKeyCookie + + app = FastAPI() + + cookie_scheme = APIKeyCookie(name="session") + + + @app.get("/items/") + async def read_items(session: str = Depends(cookie_scheme)): + return {"session": session} + ``` + """ + def __init__( self, *, - name: str, - scheme_name: Optional[str] = None, - description: Optional[str] = None, - auto_error: bool = True, + name: Annotated[str, Doc("Cookie name.")], + scheme_name: Annotated[ + Optional[str], + Doc( + """ + Security scheme name. + + It will be included in the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + Security scheme description. + + It will be included in the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + auto_error: Annotated[ + bool, + Doc( + """ + By default, if the cookie is not provided, `APIKeyCookie` will + automatically cancel the request and send the client an error. + + If `auto_error` is set to `False`, when the cookie is not available, + instead of erroring out, the dependency result will be `None`. + + This is useful when you want to have optional authentication. + + It is also useful when you want to have authentication that can be + provided in one of multiple optional ways (for example, in a cookie or + in an HTTP Bearer token). + """ + ), + ] = True, ): self.model: APIKey = APIKey( **{"in": APIKeyIn.cookie}, # type: ignore[arg-type] diff --git a/fastapi/security/http.py b/fastapi/security/http.py index 8fc0aafd9fb1c..738455de38103 100644 --- a/fastapi/security/http.py +++ b/fastapi/security/http.py @@ -10,16 +10,60 @@ from pydantic import BaseModel from starlette.requests import Request from starlette.status import HTTP_401_UNAUTHORIZED, HTTP_403_FORBIDDEN +from typing_extensions import Annotated, Doc # type: ignore [attr-defined] class HTTPBasicCredentials(BaseModel): - username: str - password: str + """ + The HTTP Basic credendials given as the result of using `HTTPBasic` in a + dependency. + + Read more about it in the + [FastAPI docs for HTTP Basic Auth](https://fastapi.tiangolo.com/advanced/security/http-basic-auth/). + """ + + username: Annotated[str, Doc("The HTTP Basic username.")] + password: Annotated[str, Doc("The HTTP Basic password.")] class HTTPAuthorizationCredentials(BaseModel): - scheme: str - credentials: str + """ + The HTTP authorization credentials in the result of using `HTTPBearer` or + `HTTPDigest` in a dependency. + + The HTTP authorization header value is split by the first space. + + The first part is the `scheme`, the second part is the `credentials`. + + For example, in an HTTP Bearer token scheme, the client will send a header + like: + + ``` + Authorization: Bearer deadbeef12346 + ``` + + In this case: + + * `scheme` will have the value `"Bearer"` + * `credentials` will have the value `"deadbeef12346"` + """ + + scheme: Annotated[ + str, + Doc( + """ + The HTTP authorization scheme extracted from the header value. + """ + ), + ] + credentials: Annotated[ + str, + Doc( + """ + The HTTP authorization credentials extracted from the header value. + """ + ), + ] class HTTPBase(SecurityBase): @@ -51,13 +95,89 @@ async def __call__( class HTTPBasic(HTTPBase): + """ + HTTP Basic authentication. + + ## Usage + + Create an instance object and use that object as the dependency in `Depends()`. + + The dependency result will be an `HTTPBasicCredentials` object containing the + `username` and the `password`. + + Read more about it in the + [FastAPI docs for HTTP Basic Auth](https://fastapi.tiangolo.com/advanced/security/http-basic-auth/). + + ## Example + + ```python + from typing import Annotated + + from fastapi import Depends, FastAPI + from fastapi.security import HTTPBasic, HTTPBasicCredentials + + app = FastAPI() + + security = HTTPBasic() + + + @app.get("/users/me") + def read_current_user(credentials: Annotated[HTTPBasicCredentials, Depends(security)]): + return {"username": credentials.username, "password": credentials.password} + ``` + """ + def __init__( self, *, - scheme_name: Optional[str] = None, - realm: Optional[str] = None, - description: Optional[str] = None, - auto_error: bool = True, + scheme_name: Annotated[ + Optional[str], + Doc( + """ + Security scheme name. + + It will be included in the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + realm: Annotated[ + Optional[str], + Doc( + """ + HTTP Basic authentication realm. + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + Security scheme description. + + It will be included in the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + auto_error: Annotated[ + bool, + Doc( + """ + By default, if the HTTP Basic authentication is not provided (a + header), `HTTPBasic` will automatically cancel the request and send the + client an error. + + If `auto_error` is set to `False`, when the HTTP Basic authentication + is not available, instead of erroring out, the dependency result will + be `None`. + + This is useful when you want to have optional authentication. + + It is also useful when you want to have authentication that can be + provided in one of multiple optional ways (for example, in HTTP Basic + authentication or in an HTTP Bearer token). + """ + ), + ] = True, ): self.model = HTTPBaseModel(scheme="basic", description=description) self.scheme_name = scheme_name or self.__class__.__name__ @@ -90,7 +210,7 @@ async def __call__( # type: ignore try: data = b64decode(param).decode("ascii") except (ValueError, UnicodeDecodeError, binascii.Error): - raise invalid_user_credentials_exc + raise invalid_user_credentials_exc # noqa: B904 username, separator, password = data.partition(":") if not separator: raise invalid_user_credentials_exc @@ -98,13 +218,81 @@ async def __call__( # type: ignore class HTTPBearer(HTTPBase): + """ + HTTP Bearer token authentication. + + ## Usage + + Create an instance object and use that object as the dependency in `Depends()`. + + The dependency result will be an `HTTPAuthorizationCredentials` object containing + the `scheme` and the `credentials`. + + ## Example + + ```python + from typing import Annotated + + from fastapi import Depends, FastAPI + from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer + + app = FastAPI() + + security = HTTPBearer() + + + @app.get("/users/me") + def read_current_user( + credentials: Annotated[HTTPAuthorizationCredentials, Depends(security)] + ): + return {"scheme": credentials.scheme, "credentials": credentials.credentials} + ``` + """ + def __init__( self, *, - bearerFormat: Optional[str] = None, - scheme_name: Optional[str] = None, - description: Optional[str] = None, - auto_error: bool = True, + bearerFormat: Annotated[Optional[str], Doc("Bearer token format.")] = None, + scheme_name: Annotated[ + Optional[str], + Doc( + """ + Security scheme name. + + It will be included in the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + Security scheme description. + + It will be included in the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + auto_error: Annotated[ + bool, + Doc( + """ + By default, if the HTTP Bearer token not provided (in an + `Authorization` header), `HTTPBearer` will automatically cancel the + request and send the client an error. + + If `auto_error` is set to `False`, when the HTTP Bearer token + is not available, instead of erroring out, the dependency result will + be `None`. + + This is useful when you want to have optional authentication. + + It is also useful when you want to have authentication that can be + provided in one of multiple optional ways (for example, in an HTTP + Bearer token or in a cookie). + """ + ), + ] = True, ): self.model = HTTPBearerModel(bearerFormat=bearerFormat, description=description) self.scheme_name = scheme_name or self.__class__.__name__ @@ -134,12 +322,79 @@ async def __call__( class HTTPDigest(HTTPBase): + """ + HTTP Digest authentication. + + ## Usage + + Create an instance object and use that object as the dependency in `Depends()`. + + The dependency result will be an `HTTPAuthorizationCredentials` object containing + the `scheme` and the `credentials`. + + ## Example + + ```python + from typing import Annotated + + from fastapi import Depends, FastAPI + from fastapi.security import HTTPAuthorizationCredentials, HTTPDigest + + app = FastAPI() + + security = HTTPDigest() + + + @app.get("/users/me") + def read_current_user( + credentials: Annotated[HTTPAuthorizationCredentials, Depends(security)] + ): + return {"scheme": credentials.scheme, "credentials": credentials.credentials} + ``` + """ + def __init__( self, *, - scheme_name: Optional[str] = None, - description: Optional[str] = None, - auto_error: bool = True, + scheme_name: Annotated[ + Optional[str], + Doc( + """ + Security scheme name. + + It will be included in the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + Security scheme description. + + It will be included in the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + auto_error: Annotated[ + bool, + Doc( + """ + By default, if the HTTP Digest not provided, `HTTPDigest` will + automatically cancel the request and send the client an error. + + If `auto_error` is set to `False`, when the HTTP Digest is not + available, instead of erroring out, the dependency result will + be `None`. + + This is useful when you want to have optional authentication. + + It is also useful when you want to have authentication that can be + provided in one of multiple optional ways (for example, in HTTP + Digest or in a cookie). + """ + ), + ] = True, ): self.model = HTTPBaseModel(scheme="digest", description=description) self.scheme_name = scheme_name or self.__class__.__name__ diff --git a/fastapi/security/oauth2.py b/fastapi/security/oauth2.py index 938dec37cd677..d7ba44bcea857 100644 --- a/fastapi/security/oauth2.py +++ b/fastapi/security/oauth2.py @@ -9,48 +9,137 @@ from starlette.requests import Request from starlette.status import HTTP_401_UNAUTHORIZED, HTTP_403_FORBIDDEN +# TODO: import from typing when deprecating Python 3.9 +from typing_extensions import Annotated, Doc # type: ignore [attr-defined] + class OAuth2PasswordRequestForm: """ - This is a dependency class, use it like: + This is a dependency class to collect the `username` and `password` as form data + for an OAuth2 password flow. - @app.post("/login") - def login(form_data: OAuth2PasswordRequestForm = Depends()): - data = form_data.parse() - print(data.username) - print(data.password) - for scope in data.scopes: - print(scope) - if data.client_id: - print(data.client_id) - if data.client_secret: - print(data.client_secret) - return data + The OAuth2 specification dictates that for a password flow the data should be + collected using form data (instead of JSON) and that it should have the specific + fields `username` and `password`. + All the initialization parameters are extracted from the request. - It creates the following Form request parameters in your endpoint: + Read more about it in the + [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/). - grant_type: the OAuth2 spec says it is required and MUST be the fixed string "password". - Nevertheless, this dependency class is permissive and allows not passing it. If you want to enforce it, - use instead the OAuth2PasswordRequestFormStrict dependency. - username: username string. The OAuth2 spec requires the exact field name "username". - password: password string. The OAuth2 spec requires the exact field name "password". - scope: Optional string. Several scopes (each one a string) separated by spaces. E.g. - "items:read items:write users:read profile openid" - client_id: optional string. OAuth2 recommends sending the client_id and client_secret (if any) - using HTTP Basic auth, as: client_id:client_secret - client_secret: optional string. OAuth2 recommends sending the client_id and client_secret (if any) - using HTTP Basic auth, as: client_id:client_secret + ## Example + + ```python + from typing import Annotated + + from fastapi import Depends, FastAPI + from fastapi.security import OAuth2PasswordRequestForm + + app = FastAPI() + + + @app.post("/login") + def login(form_data: Annotated[OAuth2PasswordRequestForm, Depends()]): + data = {} + data["scopes"] = [] + for scope in form_data.scopes: + data["scopes"].append(scope) + if form_data.client_id: + data["client_id"] = form_data.client_id + if form_data.client_secret: + data["client_secret"] = form_data.client_secret + return data + ``` + + Note that for OAuth2 the scope `items:read` is a single scope in an opaque string. + You could have custom internal logic to separate it by colon caracters (`:`) or + similar, and get the two parts `items` and `read`. Many applications do that to + group and organize permissions, you could do it as well in your application, just + know that that it is application specific, it's not part of the specification. """ def __init__( self, - grant_type: str = Form(default=None, regex="password"), - username: str = Form(), - password: str = Form(), - scope: str = Form(default=""), - client_id: Optional[str] = Form(default=None), - client_secret: Optional[str] = Form(default=None), + *, + grant_type: Annotated[ + Union[str, None], + Form(pattern="password"), + Doc( + """ + The OAuth2 spec says it is required and MUST be the fixed string + "password". Nevertheless, this dependency class is permissive and + allows not passing it. If you want to enforce it, use instead the + `OAuth2PasswordRequestFormStrict` dependency. + """ + ), + ] = None, + username: Annotated[ + str, + Form(), + Doc( + """ + `username` string. The OAuth2 spec requires the exact field name + `username`. + """ + ), + ], + password: Annotated[ + str, + Form(), + Doc( + """ + `password` string. The OAuth2 spec requires the exact field name + `password". + """ + ), + ], + scope: Annotated[ + str, + Form(), + Doc( + """ + A single string with actually several scopes separated by spaces. Each + scope is also a string. + + For example, a single string with: + + ```python + "items:read items:write users:read profile openid" + ```` + + would represent the scopes: + + * `items:read` + * `items:write` + * `users:read` + * `profile` + * `openid` + """ + ), + ] = "", + client_id: Annotated[ + Union[str, None], + Form(), + Doc( + """ + If there's a `client_id`, it can be sent as part of the form fields. + But the OAuth2 specification recommends sending the `client_id` and + `client_secret` (if any) using HTTP Basic auth. + """ + ), + ] = None, + client_secret: Annotated[ + Union[str, None], + Form(), + Doc( + """ + If there's a `client_password` (and a `client_id`), they can be sent + as part of the form fields. But the OAuth2 specification recommends + sending the `client_id` and `client_secret` (if any) using HTTP Basic + auth. + """ + ), + ] = None, ): self.grant_type = grant_type self.username = username @@ -62,23 +151,54 @@ def __init__( class OAuth2PasswordRequestFormStrict(OAuth2PasswordRequestForm): """ - This is a dependency class, use it like: + This is a dependency class to collect the `username` and `password` as form data + for an OAuth2 password flow. + + The OAuth2 specification dictates that for a password flow the data should be + collected using form data (instead of JSON) and that it should have the specific + fields `username` and `password`. + + All the initialization parameters are extracted from the request. + + The only difference between `OAuth2PasswordRequestFormStrict` and + `OAuth2PasswordRequestForm` is that `OAuth2PasswordRequestFormStrict` requires the + client to send the form field `grant_type` with the value `"password"`, which + is required in the OAuth2 specification (it seems that for no particular reason), + while for `OAuth2PasswordRequestForm` `grant_type` is optional. + + Read more about it in the + [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/). + + ## Example + + ```python + from typing import Annotated - @app.post("/login") - def login(form_data: OAuth2PasswordRequestFormStrict = Depends()): - data = form_data.parse() - print(data.username) - print(data.password) - for scope in data.scopes: - print(scope) - if data.client_id: - print(data.client_id) - if data.client_secret: - print(data.client_secret) - return data + from fastapi import Depends, FastAPI + from fastapi.security import OAuth2PasswordRequestForm + app = FastAPI() + + + @app.post("/login") + def login(form_data: Annotated[OAuth2PasswordRequestFormStrict, Depends()]): + data = {} + data["scopes"] = [] + for scope in form_data.scopes: + data["scopes"].append(scope) + if form_data.client_id: + data["client_id"] = form_data.client_id + if form_data.client_secret: + data["client_secret"] = form_data.client_secret + return data + ``` + + Note that for OAuth2 the scope `items:read` is a single scope in an opaque string. + You could have custom internal logic to separate it by colon caracters (`:`) or + similar, and get the two parts `items` and `read`. Many applications do that to + group and organize permissions, you could do it as well in your application, just + know that that it is application specific, it's not part of the specification. - It creates the following Form request parameters in your endpoint: grant_type: the OAuth2 spec says it is required and MUST be the fixed string "password". This dependency is strict about it. If you want to be permissive, use instead the @@ -95,12 +215,85 @@ def login(form_data: OAuth2PasswordRequestFormStrict = Depends()): def __init__( self, - grant_type: str = Form(regex="password"), - username: str = Form(), - password: str = Form(), - scope: str = Form(default=""), - client_id: Optional[str] = Form(default=None), - client_secret: Optional[str] = Form(default=None), + grant_type: Annotated[ + str, + Form(pattern="password"), + Doc( + """ + The OAuth2 spec says it is required and MUST be the fixed string + "password". This dependency is strict about it. If you want to be + permissive, use instead the `OAuth2PasswordRequestForm` dependency + class. + """ + ), + ], + username: Annotated[ + str, + Form(), + Doc( + """ + `username` string. The OAuth2 spec requires the exact field name + `username`. + """ + ), + ], + password: Annotated[ + str, + Form(), + Doc( + """ + `password` string. The OAuth2 spec requires the exact field name + `password". + """ + ), + ], + scope: Annotated[ + str, + Form(), + Doc( + """ + A single string with actually several scopes separated by spaces. Each + scope is also a string. + + For example, a single string with: + + ```python + "items:read items:write users:read profile openid" + ```` + + would represent the scopes: + + * `items:read` + * `items:write` + * `users:read` + * `profile` + * `openid` + """ + ), + ] = "", + client_id: Annotated[ + Union[str, None], + Form(), + Doc( + """ + If there's a `client_id`, it can be sent as part of the form fields. + But the OAuth2 specification recommends sending the `client_id` and + `client_secret` (if any) using HTTP Basic auth. + """ + ), + ] = None, + client_secret: Annotated[ + Union[str, None], + Form(), + Doc( + """ + If there's a `client_password` (and a `client_id`), they can be sent + as part of the form fields. But the OAuth2 specification recommends + sending the `client_id` and `client_secret` (if any) using HTTP Basic + auth. + """ + ), + ] = None, ): super().__init__( grant_type=grant_type, @@ -113,13 +306,69 @@ def __init__( class OAuth2(SecurityBase): + """ + This is the base class for OAuth2 authentication, an instance of it would be used + as a dependency. All other OAuth2 classes inherit from it and customize it for + each OAuth2 flow. + + You normally would not create a new class inheriting from it but use one of the + existing subclasses, and maybe compose them if you want to support multiple flows. + + Read more about it in the + [FastAPI docs for Security](https://fastapi.tiangolo.com/tutorial/security/). + """ + def __init__( self, *, - flows: Union[OAuthFlowsModel, Dict[str, Dict[str, Any]]] = OAuthFlowsModel(), - scheme_name: Optional[str] = None, - description: Optional[str] = None, - auto_error: bool = True, + flows: Annotated[ + Union[OAuthFlowsModel, Dict[str, Dict[str, Any]]], + Doc( + """ + The dictionary of OAuth2 flows. + """ + ), + ] = OAuthFlowsModel(), + scheme_name: Annotated[ + Optional[str], + Doc( + """ + Security scheme name. + + It will be included in the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + Security scheme description. + + It will be included in the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + auto_error: Annotated[ + bool, + Doc( + """ + By default, if no HTTP Authorization header is provided, required for + OAuth2 authentication, it will automatically cancel the request and + send the client an error. + + If `auto_error` is set to `False`, when the HTTP Authorization header + is not available, instead of erroring out, the dependency result will + be `None`. + + This is useful when you want to have optional authentication. + + It is also useful when you want to have authentication that can be + provided in one of multiple optional ways (for example, with OAuth2 + or in a cookie). + """ + ), + ] = True, ): self.model = OAuth2Model( flows=cast(OAuthFlowsModel, flows), description=description @@ -140,13 +389,74 @@ async def __call__(self, request: Request) -> Optional[str]: class OAuth2PasswordBearer(OAuth2): + """ + OAuth2 flow for authentication using a bearer token obtained with a password. + An instance of it would be used as a dependency. + + Read more about it in the + [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/). + """ + def __init__( self, - tokenUrl: str, - scheme_name: Optional[str] = None, - scopes: Optional[Dict[str, str]] = None, - description: Optional[str] = None, - auto_error: bool = True, + tokenUrl: Annotated[ + str, + Doc( + """ + The URL to obtain the OAuth2 token. This would be the *path operation* + that has `OAuth2PasswordRequestForm` as a dependency. + """ + ), + ], + scheme_name: Annotated[ + Optional[str], + Doc( + """ + Security scheme name. + + It will be included in the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + scopes: Annotated[ + Optional[Dict[str, str]], + Doc( + """ + The OAuth2 scopes that would be required by the *path operations* that + use this dependency. + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + Security scheme description. + + It will be included in the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + auto_error: Annotated[ + bool, + Doc( + """ + By default, if no HTTP Authorization header is provided, required for + OAuth2 authentication, it will automatically cancel the request and + send the client an error. + + If `auto_error` is set to `False`, when the HTTP Authorization header + is not available, instead of erroring out, the dependency result will + be `None`. + + This is useful when you want to have optional authentication. + + It is also useful when you want to have authentication that can be + provided in one of multiple optional ways (for example, with OAuth2 + or in a cookie). + """ + ), + ] = True, ): if not scopes: scopes = {} @@ -176,15 +486,79 @@ async def __call__(self, request: Request) -> Optional[str]: class OAuth2AuthorizationCodeBearer(OAuth2): + """ + OAuth2 flow for authentication using a bearer token obtained with an OAuth2 code + flow. An instance of it would be used as a dependency. + """ + def __init__( self, authorizationUrl: str, - tokenUrl: str, - refreshUrl: Optional[str] = None, - scheme_name: Optional[str] = None, - scopes: Optional[Dict[str, str]] = None, - description: Optional[str] = None, - auto_error: bool = True, + tokenUrl: Annotated[ + str, + Doc( + """ + The URL to obtain the OAuth2 token. + """ + ), + ], + refreshUrl: Annotated[ + Optional[str], + Doc( + """ + The URL to refresh the token and obtain a new one. + """ + ), + ] = None, + scheme_name: Annotated[ + Optional[str], + Doc( + """ + Security scheme name. + + It will be included in the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + scopes: Annotated[ + Optional[Dict[str, str]], + Doc( + """ + The OAuth2 scopes that would be required by the *path operations* that + use this dependency. + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + Security scheme description. + + It will be included in the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + auto_error: Annotated[ + bool, + Doc( + """ + By default, if no HTTP Authorization header is provided, required for + OAuth2 authentication, it will automatically cancel the request and + send the client an error. + + If `auto_error` is set to `False`, when the HTTP Authorization header + is not available, instead of erroring out, the dependency result will + be `None`. + + This is useful when you want to have optional authentication. + + It is also useful when you want to have authentication that can be + provided in one of multiple optional ways (for example, with OAuth2 + or in a cookie). + """ + ), + ] = True, ): if not scopes: scopes = {} @@ -222,6 +596,43 @@ async def __call__(self, request: Request) -> Optional[str]: class SecurityScopes: - def __init__(self, scopes: Optional[List[str]] = None): - self.scopes = scopes or [] - self.scope_str = " ".join(self.scopes) + """ + This is a special class that you can define in a parameter in a dependency to + obtain the OAuth2 scopes required by all the dependencies in the same chain. + + This way, multiple dependencies can have different scopes, even when used in the + same *path operation*. And with this, you can access all the scopes required in + all those dependencies in a single place. + + Read more about it in the + [FastAPI docs for OAuth2 scopes](https://fastapi.tiangolo.com/advanced/security/oauth2-scopes/). + """ + + def __init__( + self, + scopes: Annotated[ + Optional[List[str]], + Doc( + """ + This will be filled by FastAPI. + """ + ), + ] = None, + ): + self.scopes: Annotated[ + List[str], + Doc( + """ + The list of all the scopes required by dependencies. + """ + ), + ] = scopes or [] + self.scope_str: Annotated[ + str, + Doc( + """ + All the scopes required by all the dependencies in a single string + separated by spaces, as defined in the OAuth2 specification. + """ + ), + ] = " ".join(self.scopes) diff --git a/fastapi/security/open_id_connect_url.py b/fastapi/security/open_id_connect_url.py index 4e65f1f6c486f..1d255877dbd02 100644 --- a/fastapi/security/open_id_connect_url.py +++ b/fastapi/security/open_id_connect_url.py @@ -5,16 +5,66 @@ from starlette.exceptions import HTTPException from starlette.requests import Request from starlette.status import HTTP_403_FORBIDDEN +from typing_extensions import Annotated, Doc # type: ignore [attr-defined] class OpenIdConnect(SecurityBase): + """ + OpenID Connect authentication class. An instance of it would be used as a + dependency. + """ + def __init__( self, *, - openIdConnectUrl: str, - scheme_name: Optional[str] = None, - description: Optional[str] = None, - auto_error: bool = True, + openIdConnectUrl: Annotated[ + str, + Doc( + """ + The OpenID Connect URL. + """ + ), + ], + scheme_name: Annotated[ + Optional[str], + Doc( + """ + Security scheme name. + + It will be included in the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + Security scheme description. + + It will be included in the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + auto_error: Annotated[ + bool, + Doc( + """ + By default, if no HTTP Authorization header is provided, required for + OpenID Connect authentication, it will automatically cancel the request + and send the client an error. + + If `auto_error` is set to `False`, when the HTTP Authorization header + is not available, instead of erroring out, the dependency result will + be `None`. + + This is useful when you want to have optional authentication. + + It is also useful when you want to have authentication that can be + provided in one of multiple optional ways (for example, with OpenID + Connect or in a cookie). + """ + ), + ] = True, ): self.model = OpenIdConnectModel( openIdConnectUrl=openIdConnectUrl, description=description diff --git a/fastapi/types.py b/fastapi/types.py index e0bca46320b23..3205654c73b65 100644 --- a/fastapi/types.py +++ b/fastapi/types.py @@ -1,3 +1,10 @@ -from typing import Any, Callable, TypeVar +import types +from enum import Enum +from typing import Any, Callable, Dict, Set, Type, TypeVar, Union + +from pydantic import BaseModel DecoratedCallable = TypeVar("DecoratedCallable", bound=Callable[..., Any]) +UnionType = getattr(types, "UnionType", Union) +ModelNameMap = Dict[Union[Type[BaseModel], Type[Enum]], str] +IncEx = Union[Set[int], Set[str], Dict[int, Any], Dict[str, Any]] diff --git a/fastapi/utils.py b/fastapi/utils.py index 9b9ebcb852ee0..53b2fa0c36ba6 100644 --- a/fastapi/utils.py +++ b/fastapi/utils.py @@ -1,7 +1,6 @@ import re import warnings from dataclasses import is_dataclass -from enum import Enum from typing import ( TYPE_CHECKING, Any, @@ -16,13 +15,20 @@ from weakref import WeakKeyDictionary import fastapi +from fastapi._compat import ( + PYDANTIC_V2, + BaseConfig, + ModelField, + PydanticSchemaGenerationError, + Undefined, + UndefinedType, + Validator, + lenient_issubclass, +) from fastapi.datastructures import DefaultPlaceholder, DefaultType -from fastapi.openapi.constants import REF_PREFIX -from pydantic import BaseConfig, BaseModel, create_model -from pydantic.class_validators import Validator -from pydantic.fields import FieldInfo, ModelField, UndefinedType -from pydantic.schema import model_process_schema -from pydantic.utils import lenient_issubclass +from pydantic import BaseModel, create_model +from pydantic.fields import FieldInfo +from typing_extensions import Literal if TYPE_CHECKING: # pragma: nocover from .routing import APIRoute @@ -47,25 +53,7 @@ def is_body_allowed_for_status_code(status_code: Union[int, str, None]) -> bool: }: return True current_status_code = int(status_code) - return not (current_status_code < 200 or current_status_code in {204, 304}) - - -def get_model_definitions( - *, - flat_models: Set[Union[Type[BaseModel], Type[Enum]]], - model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], -) -> Dict[str, Any]: - definitions: Dict[str, Dict[str, Any]] = {} - for model in flat_models: - m_schema, m_definitions, m_nested_models = model_process_schema( - model, model_name_map=model_name_map, ref_prefix=REF_PREFIX - ) - definitions.update(m_definitions) - model_name = model_name_map[model] - if "description" in m_schema: - m_schema["description"] = m_schema["description"].split("\f")[0] - definitions[model_name] = m_schema - return definitions + return not (current_status_code < 200 or current_status_code in {204, 205, 304}) def get_path_param_names(path: str) -> Set[str]: @@ -76,30 +64,40 @@ def create_response_field( name: str, type_: Type[Any], class_validators: Optional[Dict[str, Validator]] = None, - default: Optional[Any] = None, - required: Union[bool, UndefinedType] = True, + default: Optional[Any] = Undefined, + required: Union[bool, UndefinedType] = Undefined, model_config: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, + mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: """ Create a new response field. Raises if type_ is invalid. """ class_validators = class_validators or {} - field_info = field_info or FieldInfo() - - try: - return ModelField( - name=name, - type_=type_, - class_validators=class_validators, - default=default, - required=required, - model_config=model_config, - alias=alias, - field_info=field_info, + if PYDANTIC_V2: + field_info = field_info or FieldInfo( + annotation=type_, default=default, alias=alias + ) + else: + field_info = field_info or FieldInfo() + kwargs = {"name": name, "field_info": field_info} + if PYDANTIC_V2: + kwargs.update({"mode": mode}) + else: + kwargs.update( + { + "type_": type_, + "class_validators": class_validators, + "default": default, + "required": required, + "model_config": model_config, + "alias": alias, + } ) - except RuntimeError: + try: + return ModelField(**kwargs) # type: ignore[arg-type] + except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"check that {type_} is a valid Pydantic field type. " @@ -116,8 +114,10 @@ def create_cloned_field( *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: + if PYDANTIC_V2: + return field # cloned_types caches already cloned types to support recursive models and improve - # performance by avoiding unecessary cloning + # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE @@ -136,30 +136,31 @@ def create_cloned_field( f, cloned_types=cloned_types ) new_field = create_response_field(name=field.name, type_=use_type) - new_field.has_alias = field.has_alias - new_field.alias = field.alias - new_field.class_validators = field.class_validators - new_field.default = field.default - new_field.required = field.required - new_field.model_config = field.model_config + new_field.has_alias = field.has_alias # type: ignore[attr-defined] + new_field.alias = field.alias # type: ignore[misc] + new_field.class_validators = field.class_validators # type: ignore[attr-defined] + new_field.default = field.default # type: ignore[misc] + new_field.required = field.required # type: ignore[misc] + new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info - new_field.allow_none = field.allow_none - new_field.validate_always = field.validate_always - if field.sub_fields: - new_field.sub_fields = [ + new_field.allow_none = field.allow_none # type: ignore[attr-defined] + new_field.validate_always = field.validate_always # type: ignore[attr-defined] + if field.sub_fields: # type: ignore[attr-defined] + new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) - for sub_field in field.sub_fields + for sub_field in field.sub_fields # type: ignore[attr-defined] ] - if field.key_field: - new_field.key_field = create_cloned_field( - field.key_field, cloned_types=cloned_types + if field.key_field: # type: ignore[attr-defined] + new_field.key_field = create_cloned_field( # type: ignore[attr-defined] + field.key_field, # type: ignore[attr-defined] + cloned_types=cloned_types, ) - new_field.validators = field.validators - new_field.pre_validators = field.pre_validators - new_field.post_validators = field.post_validators - new_field.parse_json = field.parse_json - new_field.shape = field.shape - new_field.populate_validators() + new_field.validators = field.validators # type: ignore[attr-defined] + new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] + new_field.post_validators = field.post_validators # type: ignore[attr-defined] + new_field.parse_json = field.parse_json # type: ignore[attr-defined] + new_field.shape = field.shape # type: ignore[attr-defined] + new_field.populate_validators() # type: ignore[attr-defined] return new_field @@ -172,17 +173,17 @@ def generate_operation_id_for_path( DeprecationWarning, stacklevel=2, ) - operation_id = name + path + operation_id = f"{name}{path}" operation_id = re.sub(r"\W", "_", operation_id) - operation_id = operation_id + "_" + method.lower() + operation_id = f"{operation_id}_{method.lower()}" return operation_id def generate_unique_id(route: "APIRoute") -> str: - operation_id = route.name + route.path_format + operation_id = f"{route.name}{route.path_format}" operation_id = re.sub(r"\W", "_", operation_id) assert route.methods - operation_id = operation_id + "_" + list(route.methods)[0].lower() + operation_id = f"{operation_id}_{list(route.methods)[0].lower()}" return operation_id @@ -220,3 +221,9 @@ def get_value_or_default( if not isinstance(item, DefaultPlaceholder): return item return first_item + + +def match_pydantic_error_url(error_type: str) -> Any: + from dirty_equals import IsStr + + return IsStr(regex=rf"^https://errors\.pydantic\.dev/.*/v/{error_type}") diff --git a/pyproject.toml b/pyproject.toml index 5c0d3c48ecfd9..c3801600a16d4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,7 +6,7 @@ build-backend = "hatchling.build" name = "fastapi" description = "FastAPI framework, high performance, easy to learn, fast to code, ready for production" readme = "README.md" -requires-python = ">=3.7" +requires-python = ">=3.8" license = "MIT" authors = [ { name = "Sebastián Ramírez", email = "tiangolo@gmail.com" }, @@ -32,17 +32,18 @@ classifiers = [ "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3 :: Only", - "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", "Topic :: Internet :: WWW/HTTP :: HTTP Servers", "Topic :: Internet :: WWW/HTTP", ] dependencies = [ - "starlette>=0.27.0,<0.28.0", - "pydantic>=1.7.4,!=1.8,!=1.8.1,<2.0.0", + "starlette>=0.36.3,<0.37.0", + "pydantic>=1.7.4,!=1.8,!=1.8.1,!=2.0.0,!=2.0.1,!=2.1.0,<3.0.0", + "typing-extensions>=4.8.0", ] dynamic = ["version"] @@ -55,13 +56,15 @@ Repository = "https://github.com/tiangolo/fastapi" all = [ "httpx >=0.23.0", "jinja2 >=2.11.2", - "python-multipart >=0.0.5", + "python-multipart >=0.0.7", "itsdangerous >=1.1.0", "pyyaml >=5.3.1", "ujson >=4.0.1,!=4.0.2,!=4.1.0,!=4.2.0,!=4.3.0,!=5.0.0,!=5.1.0", "orjson >=3.2.1", - "email_validator >=1.1.1", + "email_validator >=2.0.0", "uvicorn[standard] >=0.12.0", + "pydantic-settings >=2.0.0", + "pydantic-extra-types >=2.0.0", ] [tool.hatch.version] @@ -80,10 +83,17 @@ module = "fastapi.tests.*" ignore_missing_imports = true check_untyped_defs = true +[[tool.mypy.overrides]] +module = "docs_src.*" +disallow_incomplete_defs = false +disallow_untyped_defs = false +disallow_untyped_calls = false + [tool.pytest.ini_options] addopts = [ "--strict-config", "--strict-markers", + "--ignore=docs_src", ] xfail_strict = true junit_family = "xunit2" @@ -102,6 +112,18 @@ filterwarnings = [ "ignore::trio.TrioDeprecationWarning", # TODO remove pytest-cov 'ignore::pytest.PytestDeprecationWarning:pytest_cov', + # TODO: remove after upgrading SQLAlchemy to a version that includes the following changes + # https://github.com/sqlalchemy/sqlalchemy/commit/59521abcc0676e936b31a523bd968fc157fef0c2 + 'ignore:datetime\.datetime\.utcfromtimestamp\(\) is deprecated and scheduled for removal in a future version\..*:DeprecationWarning:sqlalchemy', + # TODO: remove after upgrading python-jose to a version that explicitly supports Python 3.12 + # also, if it won't receive an update, consider replacing python-jose with some alternative + # related issues: + # - https://github.com/mpdavis/python-jose/issues/332 + # - https://github.com/mpdavis/python-jose/issues/334 + 'ignore:datetime\.datetime\.utcnow\(\) is deprecated and scheduled for removal in a future version\..*:DeprecationWarning:jose', + # TODO: remove after upgrading Starlette to a version including https://github.com/encode/starlette/pull/2406 + # Probably Starlette 0.36.0 + "ignore: The 'method' parameter is not used, and it will be removed.:DeprecationWarning:starlette", ] [tool.coverage.run] @@ -117,22 +139,24 @@ omit = [ "docs_src/response_model/tutorial003_04_py310.py", ] -[tool.ruff] +[tool.ruff.lint] select = [ "E", # pycodestyle errors "W", # pycodestyle warnings "F", # pyflakes "I", # isort - "C", # flake8-comprehensions "B", # flake8-bugbear + "C4", # flake8-comprehensions + "UP", # pyupgrade ] ignore = [ "E501", # line too long, handled by black "B008", # do not perform function calls in argument defaults "C901", # too complex + "W191", # indentation contains tabs ] -[tool.ruff.per-file-ignores] +[tool.ruff.lint.per-file-ignores] "__init__.py" = ["F401"] "docs_src/dependencies/tutorial007.py" = ["F821"] "docs_src/dependencies/tutorial008.py" = ["F821"] @@ -141,6 +165,7 @@ ignore = [ "docs_src/custom_response/tutorial007.py" = ["B007"] "docs_src/dataclasses/tutorial003.py" = ["I001"] "docs_src/path_operation_advanced_configuration/tutorial007.py" = ["B904"] +"docs_src/path_operation_advanced_configuration/tutorial007_pv1.py" = ["B904"] "docs_src/custom_request_and_route/tutorial002.py" = ["B904"] "docs_src/dependencies/tutorial008_an.py" = ["F821"] "docs_src/dependencies/tutorial008_an_py39.py" = ["F821"] @@ -148,6 +173,25 @@ ignore = [ "docs_src/query_params_str_validations/tutorial012_an_py39.py" = ["B006"] "docs_src/query_params_str_validations/tutorial013_an.py" = ["B006"] "docs_src/query_params_str_validations/tutorial013_an_py39.py" = ["B006"] +"docs_src/security/tutorial004.py" = ["B904"] +"docs_src/security/tutorial004_an.py" = ["B904"] +"docs_src/security/tutorial004_an_py310.py" = ["B904"] +"docs_src/security/tutorial004_an_py39.py" = ["B904"] +"docs_src/security/tutorial004_py310.py" = ["B904"] +"docs_src/security/tutorial005.py" = ["B904"] +"docs_src/security/tutorial005_an.py" = ["B904"] +"docs_src/security/tutorial005_an_py310.py" = ["B904"] +"docs_src/security/tutorial005_an_py39.py" = ["B904"] +"docs_src/security/tutorial005_py310.py" = ["B904"] +"docs_src/security/tutorial005_py39.py" = ["B904"] +"docs_src/dependencies/tutorial008b.py" = ["B904"] +"docs_src/dependencies/tutorial008b_an.py" = ["B904"] +"docs_src/dependencies/tutorial008b_an_py39.py" = ["B904"] -[tool.ruff.isort] + +[tool.ruff.lint.isort] known-third-party = ["fastapi", "pydantic", "starlette"] + +[tool.ruff.lint.pyupgrade] +# Preserve types, even if a file imports `from __future__ import annotations`. +keep-runtime-typing = true diff --git a/requirements-docs-tests.txt b/requirements-docs-tests.txt new file mode 100644 index 0000000000000..b82df49338a1b --- /dev/null +++ b/requirements-docs-tests.txt @@ -0,0 +1,2 @@ +# For mkdocstrings and tests +httpx >=0.23.0,<0.25.0 diff --git a/requirements-docs.txt b/requirements-docs.txt index 2c5f71ec04973..28408a9f1b295 100644 --- a/requirements-docs.txt +++ b/requirements-docs.txt @@ -1,14 +1,19 @@ -e . -mkdocs==1.4.3 -mkdocs-material==9.1.16 +-r requirements-docs-tests.txt +mkdocs-material==9.4.7 mdx-include >=1.4.1,<2.0.0 mkdocs-markdownextradata-plugin >=0.1.7,<0.3.0 +mkdocs-redirects>=1.2.1,<1.3.0 typer-cli >=0.0.13,<0.0.14 typer[all] >=0.6.1,<0.8.0 pyyaml >=5.3.1,<7.0.0 # For Material for MkDocs, Chinese search jieba==0.42.1 # For image processing by Material for MkDocs -pillow==9.5.0 +pillow==10.1.0 # For image processing by Material for MkDocs cairosvg==2.7.0 +mkdocstrings[python]==0.23.0 +griffe-typingdoc==0.2.2 +# For griffe, it formats with black +black==23.3.0 diff --git a/requirements-tests.txt b/requirements-tests.txt index 5cedde84d445e..09ca9cb52cdbc 100644 --- a/requirements-tests.txt +++ b/requirements-tests.txt @@ -1,19 +1,19 @@ -e . +-r requirements-docs-tests.txt +pydantic-settings >=2.0.0 pytest >=7.1.3,<8.0.0 coverage[toml] >= 6.5.0,< 8.0 -mypy ==1.4.0 -ruff ==0.0.275 -black == 23.3.0 -httpx >=0.23.0,<0.24.0 -email_validator >=1.1.1,<2.0.0 +mypy ==1.4.1 +ruff ==0.2.0 +email_validator >=1.1.1,<3.0.0 +dirty-equals ==0.6.0 # TODO: once removing databases from tutorial, upgrade SQLAlchemy # probably when including SQLModel sqlalchemy >=1.3.18,<1.4.43 -peewee >=3.13.3,<4.0.0 databases[sqlite] >=0.3.2,<0.7.0 orjson >=3.2.1,<4.0.0 ujson >=4.0.1,!=4.0.2,!=4.1.0,!=4.2.0,!=4.3.0,!=5.0.0,!=5.1.0,<6.0.0 -python-multipart >=0.0.5,<0.0.7 +python-multipart >=0.0.7,<0.1.0 flask >=1.1.2,<3.0.0 anyio[trio] >=3.2.1,<4.0.0 python-jose[cryptography] >=3.3.0,<4.0.0 diff --git a/requirements.txt b/requirements.txt index 7e746016a42de..ef25ec483fccb 100644 --- a/requirements.txt +++ b/requirements.txt @@ -3,3 +3,5 @@ -r requirements-docs.txt uvicorn[standard] >=0.12.0,<0.23.0 pre-commit >=2.17.0,<4.0.0 +# For generating screenshots +playwright diff --git a/scripts/build-docs.sh b/scripts/build-docs.sh index ebf864afa3dac..7aa0a9a47f830 100755 --- a/scripts/build-docs.sh +++ b/scripts/build-docs.sh @@ -4,5 +4,5 @@ set -e set -x # Check README.md is up to date -python ./scripts/docs.py verify-readme +python ./scripts/docs.py verify-docs python ./scripts/docs.py build-all diff --git a/scripts/docs.py b/scripts/docs.py index 20838be6a716a..59578a820ce6c 100644 --- a/scripts/docs.py +++ b/scripts/docs.py @@ -36,7 +36,7 @@ build_site_path = Path("site_build").absolute() -@lru_cache() +@lru_cache def is_mkdocs_insiders() -> bool: version = metadata.version("mkdocs-material") return "insiders" in version @@ -53,9 +53,6 @@ def get_lang_paths() -> List[Path]: def lang_callback(lang: Optional[str]) -> Union[str, None]: if lang is None: return None - if not lang.isalpha() or len(lang) != 2: - typer.echo("Use a 2 letter language code, like: es") - raise typer.Abort() lang = lang.lower() return lang @@ -79,8 +76,6 @@ def callback() -> None: def new_lang(lang: str = typer.Argument(..., callback=lang_callback)): """ Generate a new docs translation directory for the language LANG. - - LANG should be a 2-letter language code, like: en, es, de, pt, etc. """ new_path: Path = Path("docs") / lang if new_path.exists(): @@ -104,7 +99,7 @@ def new_lang(lang: str = typer.Argument(..., callback=lang_callback)): def build_lang( lang: str = typer.Argument( ..., callback=lang_callback, autocompletion=complete_existing_lang - ) + ), ) -> None: """ Build the docs for a language. @@ -153,17 +148,21 @@ def build_lang( def generate_readme_content() -> str: en_index = en_docs_path / "docs" / "index.md" content = en_index.read_text("utf-8") + match_pre = re.search(r"</style>\n\n", content) match_start = re.search(r"<!-- sponsors -->", content) match_end = re.search(r"<!-- /sponsors -->", content) sponsors_data_path = en_docs_path / "data" / "sponsors.yml" sponsors = mkdocs.utils.yaml_load(sponsors_data_path.read_text(encoding="utf-8")) if not (match_start and match_end): raise RuntimeError("Couldn't auto-generate sponsors section") + if not match_pre: + raise RuntimeError("Couldn't find pre section (<style>) in index.md") + frontmatter_end = match_pre.end() pre_end = match_start.end() post_start = match_end.start() template = Template(index_sponsors_template) message = template.render(sponsors=sponsors) - pre_content = content[:pre_end] + pre_content = content[frontmatter_end:pre_end] post_content = content[post_start:] new_content = pre_content + message + post_content return new_content @@ -247,7 +246,7 @@ def serve() -> None: def live( lang: str = typer.Argument( None, callback=lang_callback, autocompletion=complete_existing_lang - ) + ), ) -> None: """ Serve with livereload a docs site for a specific language. @@ -258,6 +257,8 @@ def live( Takes an optional LANG argument with the name of the language to serve, by default en. """ + # Enable line numbers during local development to make it easier to highlight + os.environ["LINENUMS"] = "true" if lang is None: lang = "en" lang_path: Path = docs_path / lang @@ -265,33 +266,70 @@ def live( mkdocs.commands.serve.serve(dev_addr="127.0.0.1:8008") -def update_config() -> None: +def get_updated_config_content() -> Dict[str, Any]: config = get_en_config() languages = [{"en": "/"}] - alternate: List[Dict[str, str]] = config["extra"].get("alternate", []) - alternate_dict = {alt["link"]: alt["name"] for alt in alternate} new_alternate: List[Dict[str, str]] = [] + # Language names sourced from https://quickref.me/iso-639-1 + # Contributors may wish to update or change these, e.g. to fix capitalization. + language_names_path = Path(__file__).parent / "../docs/language_names.yml" + local_language_names: Dict[str, str] = mkdocs.utils.yaml_load( + language_names_path.read_text(encoding="utf-8") + ) for lang_path in get_lang_paths(): - if lang_path.name == "en" or not lang_path.is_dir(): + if lang_path.name in {"en", "em"} or not lang_path.is_dir(): continue - name = lang_path.name - languages.append({name: f"/{name}/"}) + code = lang_path.name + languages.append({code: f"/{code}/"}) for lang_dict in languages: - name = list(lang_dict.keys())[0] - url = lang_dict[name] - if url not in alternate_dict: - new_alternate.append({"link": url, "name": name}) - else: - use_name = alternate_dict[url] - new_alternate.append({"link": url, "name": use_name}) - config["nav"][1] = {"Languages": languages} + code = list(lang_dict.keys())[0] + url = lang_dict[code] + if code not in local_language_names: + print( + f"Missing language name for: {code}, " + "update it in docs/language_names.yml" + ) + raise typer.Abort() + use_name = f"{code} - {local_language_names[code]}" + new_alternate.append({"link": url, "name": use_name}) + new_alternate.append({"link": "/em/", "name": "😉"}) config["extra"]["alternate"] = new_alternate + return config + + +def update_config() -> None: + config = get_updated_config_content() en_config_path.write_text( yaml.dump(config, sort_keys=False, width=200, allow_unicode=True), encoding="utf-8", ) +@app.command() +def verify_config() -> None: + """ + Verify main mkdocs.yml content to make sure it uses the latest language names. + """ + typer.echo("Verifying mkdocs.yml") + config = get_en_config() + updated_config = get_updated_config_content() + if config != updated_config: + typer.secho( + "docs/en/mkdocs.yml outdated from docs/language_names.yml, " + "update language_names.yml and run " + "python ./scripts/docs.py update-languages", + color=typer.colors.RED, + ) + raise typer.Abort() + typer.echo("Valid mkdocs.yml ✅") + + +@app.command() +def verify_docs(): + verify_readme() + verify_config() + + @app.command() def langs_json(): langs = [] diff --git a/scripts/format.sh b/scripts/format.sh index 3fb3eb4f19df9..11f25f1ce8a83 100755 --- a/scripts/format.sh +++ b/scripts/format.sh @@ -2,4 +2,4 @@ set -x ruff fastapi tests docs_src scripts --fix -black fastapi tests docs_src scripts +ruff format fastapi tests docs_src scripts diff --git a/scripts/gitter_releases_bot.py b/scripts/gitter_releases_bot.py deleted file mode 100644 index a033d0d69ec9b..0000000000000 --- a/scripts/gitter_releases_bot.py +++ /dev/null @@ -1,67 +0,0 @@ -import inspect -import os - -import requests - -room_id = "5c9c9540d73408ce4fbc1403" # FastAPI -# room_id = "5cc46398d73408ce4fbed233" # Gitter development - -gitter_token = os.getenv("GITTER_TOKEN") -assert gitter_token -github_token = os.getenv("GITHUB_TOKEN") -assert github_token -tag_name = os.getenv("TAG") -assert tag_name - - -def get_github_graphql(tag_name: str): - github_graphql = """ - { - repository(owner: "tiangolo", name: "fastapi") { - release (tagName: "{{tag_name}}" ) { - description - } - } - } - """ - github_graphql = github_graphql.replace("{{tag_name}}", tag_name) - return github_graphql - - -def get_github_release_text(tag_name: str): - url = "https://api.github.com/graphql" - headers = {"Authorization": f"Bearer {github_token}"} - github_graphql = get_github_graphql(tag_name=tag_name) - response = requests.post(url, json={"query": github_graphql}, headers=headers) - assert response.status_code == 200 - data = response.json() - return data["data"]["repository"]["release"]["description"] - - -def get_gitter_message(release_text: str): - text = f""" - New release! :tada: :rocket: - (by FastAPI bot) - - ## {tag_name} - """ - text = inspect.cleandoc(text) + "\n\n" + release_text - return text - - -def send_gitter_message(text: str): - headers = {"Authorization": f"Bearer {gitter_token}"} - url = f"https://api.gitter.im/v1/rooms/{room_id}/chatMessages" - data = {"text": text} - response = requests.post(url, headers=headers, json=data) - assert response.status_code == 200 - - -def main(): - release_text = get_github_release_text(tag_name=tag_name) - text = get_gitter_message(release_text=release_text) - send_gitter_message(text=text) - - -if __name__ == "__main__": - main() diff --git a/scripts/lint.sh b/scripts/lint.sh index 4db5caa9627ea..c0e24db9f64ba 100755 --- a/scripts/lint.sh +++ b/scripts/lint.sh @@ -5,4 +5,4 @@ set -x mypy fastapi ruff fastapi tests docs_src scripts -black fastapi tests --check +ruff format fastapi tests --check diff --git a/scripts/mkdocs_hooks.py b/scripts/mkdocs_hooks.py index 008751f8acb1f..8335a13f62914 100644 --- a/scripts/mkdocs_hooks.py +++ b/scripts/mkdocs_hooks.py @@ -8,18 +8,23 @@ from mkdocs.structure.nav import Link, Navigation, Section from mkdocs.structure.pages import Page +non_traslated_sections = [ + "reference/", + "release-notes.md", +] -@lru_cache() + +@lru_cache def get_missing_translation_content(docs_dir: str) -> str: docs_dir_path = Path(docs_dir) missing_translation_path = docs_dir_path.parent.parent / "missing-translation.md" return missing_translation_path.read_text(encoding="utf-8") -@lru_cache() +@lru_cache def get_mkdocs_material_langs() -> List[str]: material_path = Path(material.__file__).parent - material_langs_path = material_path / "partials" / "languages" + material_langs_path = material_path / "templates" / "partials" / "languages" langs = [file.stem for file in material_langs_path.glob("*.html")] return langs @@ -123,6 +128,9 @@ def on_page_markdown( markdown: str, *, page: Page, config: MkDocsConfig, files: Files ) -> str: if isinstance(page.file, EnFile): + for excluded_section in non_traslated_sections: + if page.file.src_path.startswith(excluded_section): + return markdown missing_translation_content = get_missing_translation_content(config.docs_dir) header = "" body = markdown diff --git a/scripts/notify.sh b/scripts/notify.sh deleted file mode 100755 index 8ce550026abdc..0000000000000 --- a/scripts/notify.sh +++ /dev/null @@ -1,5 +0,0 @@ -#!/usr/bin/env bash - -set -e - -python scripts/gitter_releases_bot.py diff --git a/scripts/playwright/separate_openapi_schemas/image01.py b/scripts/playwright/separate_openapi_schemas/image01.py new file mode 100644 index 0000000000000..0b40f3bbcf1c7 --- /dev/null +++ b/scripts/playwright/separate_openapi_schemas/image01.py @@ -0,0 +1,29 @@ +import subprocess + +from playwright.sync_api import Playwright, sync_playwright + + +def run(playwright: Playwright) -> None: + browser = playwright.chromium.launch(headless=False) + context = browser.new_context(viewport={"width": 960, "height": 1080}) + page = context.new_page() + page.goto("http://localhost:8000/docs") + page.get_by_text("POST/items/Create Item").click() + page.get_by_role("tab", name="Schema").first.click() + page.screenshot( + path="docs/en/docs/img/tutorial/separate-openapi-schemas/image01.png" + ) + + # --------------------- + context.close() + browser.close() + + +process = subprocess.Popen( + ["uvicorn", "docs_src.separate_openapi_schemas.tutorial001:app"] +) +try: + with sync_playwright() as playwright: + run(playwright) +finally: + process.terminate() diff --git a/scripts/playwright/separate_openapi_schemas/image02.py b/scripts/playwright/separate_openapi_schemas/image02.py new file mode 100644 index 0000000000000..f76af7ee22177 --- /dev/null +++ b/scripts/playwright/separate_openapi_schemas/image02.py @@ -0,0 +1,30 @@ +import subprocess + +from playwright.sync_api import Playwright, sync_playwright + + +def run(playwright: Playwright) -> None: + browser = playwright.chromium.launch(headless=False) + context = browser.new_context(viewport={"width": 960, "height": 1080}) + page = context.new_page() + page.goto("http://localhost:8000/docs") + page.get_by_text("GET/items/Read Items").click() + page.get_by_role("button", name="Try it out").click() + page.get_by_role("button", name="Execute").click() + page.screenshot( + path="docs/en/docs/img/tutorial/separate-openapi-schemas/image02.png" + ) + + # --------------------- + context.close() + browser.close() + + +process = subprocess.Popen( + ["uvicorn", "docs_src.separate_openapi_schemas.tutorial001:app"] +) +try: + with sync_playwright() as playwright: + run(playwright) +finally: + process.terminate() diff --git a/scripts/playwright/separate_openapi_schemas/image03.py b/scripts/playwright/separate_openapi_schemas/image03.py new file mode 100644 index 0000000000000..127f5c428e86e --- /dev/null +++ b/scripts/playwright/separate_openapi_schemas/image03.py @@ -0,0 +1,30 @@ +import subprocess + +from playwright.sync_api import Playwright, sync_playwright + + +def run(playwright: Playwright) -> None: + browser = playwright.chromium.launch(headless=False) + context = browser.new_context(viewport={"width": 960, "height": 1080}) + page = context.new_page() + page.goto("http://localhost:8000/docs") + page.get_by_text("GET/items/Read Items").click() + page.get_by_role("tab", name="Schema").click() + page.get_by_label("Schema").get_by_role("button", name="Expand all").click() + page.screenshot( + path="docs/en/docs/img/tutorial/separate-openapi-schemas/image03.png" + ) + + # --------------------- + context.close() + browser.close() + + +process = subprocess.Popen( + ["uvicorn", "docs_src.separate_openapi_schemas.tutorial001:app"] +) +try: + with sync_playwright() as playwright: + run(playwright) +finally: + process.terminate() diff --git a/scripts/playwright/separate_openapi_schemas/image04.py b/scripts/playwright/separate_openapi_schemas/image04.py new file mode 100644 index 0000000000000..208eaf8a0c781 --- /dev/null +++ b/scripts/playwright/separate_openapi_schemas/image04.py @@ -0,0 +1,29 @@ +import subprocess + +from playwright.sync_api import Playwright, sync_playwright + + +def run(playwright: Playwright) -> None: + browser = playwright.chromium.launch(headless=False) + context = browser.new_context(viewport={"width": 960, "height": 1080}) + page = context.new_page() + page.goto("http://localhost:8000/docs") + page.get_by_role("button", name="Item-Input").click() + page.get_by_role("button", name="Item-Output").click() + page.set_viewport_size({"width": 960, "height": 820}) + page.screenshot( + path="docs/en/docs/img/tutorial/separate-openapi-schemas/image04.png" + ) + # --------------------- + context.close() + browser.close() + + +process = subprocess.Popen( + ["uvicorn", "docs_src.separate_openapi_schemas.tutorial001:app"] +) +try: + with sync_playwright() as playwright: + run(playwright) +finally: + process.terminate() diff --git a/scripts/playwright/separate_openapi_schemas/image05.py b/scripts/playwright/separate_openapi_schemas/image05.py new file mode 100644 index 0000000000000..83966b4498cac --- /dev/null +++ b/scripts/playwright/separate_openapi_schemas/image05.py @@ -0,0 +1,29 @@ +import subprocess + +from playwright.sync_api import Playwright, sync_playwright + + +def run(playwright: Playwright) -> None: + browser = playwright.chromium.launch(headless=False) + context = browser.new_context(viewport={"width": 960, "height": 1080}) + page = context.new_page() + page.goto("http://localhost:8000/docs") + page.get_by_role("button", name="Item", exact=True).click() + page.set_viewport_size({"width": 960, "height": 700}) + page.screenshot( + path="docs/en/docs/img/tutorial/separate-openapi-schemas/image05.png" + ) + + # --------------------- + context.close() + browser.close() + + +process = subprocess.Popen( + ["uvicorn", "docs_src.separate_openapi_schemas.tutorial002:app"] +) +try: + with sync_playwright() as playwright: + run(playwright) +finally: + process.terminate() diff --git a/tests/test_additional_properties.py b/tests/test_additional_properties.py index 516a569e4250d..be14d10edc66e 100644 --- a/tests/test_additional_properties.py +++ b/tests/test_additional_properties.py @@ -29,7 +29,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/foo": { diff --git a/tests/test_additional_properties_bool.py b/tests/test_additional_properties_bool.py new file mode 100644 index 0000000000000..de59e48ce7493 --- /dev/null +++ b/tests/test_additional_properties_bool.py @@ -0,0 +1,133 @@ +from typing import Union + +from dirty_equals import IsDict +from fastapi import FastAPI +from fastapi._compat import PYDANTIC_V2 +from fastapi.testclient import TestClient +from pydantic import BaseModel, ConfigDict + + +class FooBaseModel(BaseModel): + if PYDANTIC_V2: + model_config = ConfigDict(extra="forbid") + else: + + class Config: + extra = "forbid" + + +class Foo(FooBaseModel): + pass + + +app = FastAPI() + + +@app.post("/") +async def post( + foo: Union[Foo, None] = None, +): + return foo + + +client = TestClient(app) + + +def test_call_invalid(): + response = client.post("/", json={"foo": {"bar": "baz"}}) + assert response.status_code == 422 + + +def test_call_valid(): + response = client.post("/", json={}) + assert response.status_code == 200 + assert response.json() == {} + + +def test_openapi_schema(): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/": { + "post": { + "summary": "Post", + "operationId": "post__post", + "requestBody": { + "content": { + "application/json": { + "schema": IsDict( + { + "anyOf": [ + {"$ref": "#/components/schemas/Foo"}, + {"type": "null"}, + ], + "title": "Foo", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"$ref": "#/components/schemas/Foo"} + ) + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + } + }, + "components": { + "schemas": { + "Foo": { + "properties": {}, + "additionalProperties": False, + "type": "object", + "title": "Foo", + }, + "HTTPValidationError": { + "properties": { + "detail": { + "items": {"$ref": "#/components/schemas/ValidationError"}, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + } + }, + } diff --git a/tests/test_additional_response_extra.py b/tests/test_additional_response_extra.py index d62638c8fa3cd..55be19bad25a8 100644 --- a/tests/test_additional_response_extra.py +++ b/tests/test_additional_response_extra.py @@ -30,7 +30,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { diff --git a/tests/test_additional_responses_bad.py b/tests/test_additional_responses_bad.py index d2eb4d7a1942a..36df07f4683f6 100644 --- a/tests/test_additional_responses_bad.py +++ b/tests/test_additional_responses_bad.py @@ -11,7 +11,7 @@ async def a(): openapi_schema = { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/a": { diff --git a/tests/test_additional_responses_custom_model_in_callback.py b/tests/test_additional_responses_custom_model_in_callback.py index 5c08eaa6d2662..2ad57545510a7 100644 --- a/tests/test_additional_responses_custom_model_in_callback.py +++ b/tests/test_additional_responses_custom_model_in_callback.py @@ -1,3 +1,4 @@ +from dirty_equals import IsDict from fastapi import APIRouter, FastAPI from fastapi.testclient import TestClient from pydantic import BaseModel, HttpUrl @@ -32,7 +33,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/": { @@ -42,13 +43,24 @@ def test_openapi_schema(): "parameters": [ { "required": True, - "schema": { - "title": "Callback Url", - "maxLength": 2083, - "minLength": 1, - "type": "string", - "format": "uri", - }, + "schema": IsDict( + { + "title": "Callback Url", + "minLength": 1, + "type": "string", + "format": "uri", + } + ) + # TODO: remove when deprecating Pydantic v1 + | IsDict( + { + "title": "Callback Url", + "maxLength": 2083, + "minLength": 1, + "type": "string", + "format": "uri", + } + ), "name": "callback_url", "in": "query", } diff --git a/tests/test_additional_responses_custom_validationerror.py b/tests/test_additional_responses_custom_validationerror.py index 05260276856cc..9fec5c96d4e17 100644 --- a/tests/test_additional_responses_custom_validationerror.py +++ b/tests/test_additional_responses_custom_validationerror.py @@ -37,7 +37,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/a/{id}": { diff --git a/tests/test_additional_responses_default_validationerror.py b/tests/test_additional_responses_default_validationerror.py index 58de46ff60157..153f04f579880 100644 --- a/tests/test_additional_responses_default_validationerror.py +++ b/tests/test_additional_responses_default_validationerror.py @@ -16,7 +16,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/a/{id}": { diff --git a/tests/test_additional_responses_response_class.py b/tests/test_additional_responses_response_class.py index 6746760f0e295..68753561c9ecc 100644 --- a/tests/test_additional_responses_response_class.py +++ b/tests/test_additional_responses_response_class.py @@ -42,7 +42,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/a": { diff --git a/tests/test_additional_responses_router.py b/tests/test_additional_responses_router.py index 58d54b733e763..71cabc7c3d114 100644 --- a/tests/test_additional_responses_router.py +++ b/tests/test_additional_responses_router.py @@ -85,7 +85,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/a": { diff --git a/tests/test_ambiguous_params.py b/tests/test_ambiguous_params.py index 42bcc27a1df8f..8a31442eb0ca3 100644 --- a/tests/test_ambiguous_params.py +++ b/tests/test_ambiguous_params.py @@ -1,6 +1,8 @@ import pytest from fastapi import Depends, FastAPI, Path from fastapi.param_functions import Query +from fastapi.testclient import TestClient +from fastapi.utils import PYDANTIC_V2 from typing_extensions import Annotated app = FastAPI() @@ -28,18 +30,13 @@ async def get(item_id: Annotated[int, Query(default=1)]): pass # pragma: nocover -def test_no_multiple_annotations(): +def test_multiple_annotations(): async def dep(): pass # pragma: nocover - with pytest.raises( - AssertionError, - match="Cannot specify multiple `Annotated` FastAPI arguments for 'foo'", - ): - - @app.get("/") - async def get(foo: Annotated[int, Query(min_length=1), Query()]): - pass # pragma: nocover + @app.get("/multi-query") + async def get(foo: Annotated[int, Query(gt=2), Query(lt=10)]): + return foo with pytest.raises( AssertionError, @@ -64,3 +61,15 @@ async def get2(foo: Annotated[int, Depends(dep)] = Depends(dep)): @app.get("/") async def get3(foo: Annotated[int, Query(min_length=1)] = Depends(dep)): pass # pragma: nocover + + client = TestClient(app) + response = client.get("/multi-query", params={"foo": "5"}) + assert response.status_code == 200 + assert response.json() == 5 + + response = client.get("/multi-query", params={"foo": "123"}) + assert response.status_code == 422 + + if PYDANTIC_V2: + response = client.get("/multi-query", params={"foo": "1"}) + assert response.status_code == 422 diff --git a/tests/test_annotated.py b/tests/test_annotated.py index a4f42b038f476..2222be9783c08 100644 --- a/tests/test_annotated.py +++ b/tests/test_annotated.py @@ -1,6 +1,8 @@ import pytest +from dirty_equals import IsDict from fastapi import APIRouter, FastAPI, Query from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url from typing_extensions import Annotated app = FastAPI() @@ -30,21 +32,46 @@ async def unrelated(foo: Annotated[str, object()]): foo_is_missing = { "detail": [ - { - "loc": ["query", "foo"], - "msg": "field required", - "type": "value_error.missing", - } + IsDict( + { + "loc": ["query", "foo"], + "msg": "Field required", + "type": "missing", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ) + # TODO: remove when deprecating Pydantic v1 + | IsDict( + { + "loc": ["query", "foo"], + "msg": "field required", + "type": "value_error.missing", + } + ) ] } foo_is_short = { "detail": [ - { - "ctx": {"limit_value": 1}, - "loc": ["query", "foo"], - "msg": "ensure this value has at least 1 characters", - "type": "value_error.any_str.min_length", - } + IsDict( + { + "ctx": {"min_length": 1}, + "loc": ["query", "foo"], + "msg": "String should have at least 1 character", + "type": "string_too_short", + "input": "", + "url": match_pydantic_error_url("string_too_short"), + } + ) + # TODO: remove when deprecating Pydantic v1 + | IsDict( + { + "ctx": {"limit_value": 1}, + "loc": ["query", "foo"], + "msg": "ensure this value has at least 1 characters", + "type": "value_error.any_str.min_length", + } + ) ] } @@ -118,7 +145,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200 assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/default": { diff --git a/tests/test_application.py b/tests/test_application.py index e5f2f43878b6f..ea7a80128fd68 100644 --- a/tests/test_application.py +++ b/tests/test_application.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient from .main import app @@ -55,7 +56,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/api_route": { @@ -266,10 +267,17 @@ def test_openapi_schema(): "operationId": "get_path_param_id_path_param__item_id__get", "parameters": [ { - "required": True, - "schema": {"title": "Item Id", "type": "string"}, "name": "item_id", "in": "path", + "required": True, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Item Id", + } + ) + # TODO: remove when deprecating Pydantic v1 + | IsDict({"title": "Item Id", "type": "string"}), } ], } @@ -969,10 +977,17 @@ def test_openapi_schema(): "operationId": "get_query_type_optional_query_int_optional_get", "parameters": [ { - "required": False, - "schema": {"title": "Query", "type": "integer"}, "name": "query", "in": "query", + "required": False, + "schema": IsDict( + { + "anyOf": [{"type": "integer"}, {"type": "null"}], + "title": "Query", + } + ) + # TODO: remove when deprecating Pydantic v1 + | IsDict({"title": "Query", "type": "integer"}), } ], } diff --git a/tests/test_compat.py b/tests/test_compat.py new file mode 100644 index 0000000000000..bf268b860b1dc --- /dev/null +++ b/tests/test_compat.py @@ -0,0 +1,93 @@ +from typing import List, Union + +from fastapi import FastAPI, UploadFile +from fastapi._compat import ( + ModelField, + Undefined, + _get_model_config, + is_bytes_sequence_annotation, + is_uploadfile_sequence_annotation, +) +from fastapi.testclient import TestClient +from pydantic import BaseConfig, BaseModel, ConfigDict +from pydantic.fields import FieldInfo + +from .utils import needs_pydanticv1, needs_pydanticv2 + + +@needs_pydanticv2 +def test_model_field_default_required(): + # For coverage + field_info = FieldInfo(annotation=str) + field = ModelField(name="foo", field_info=field_info) + assert field.default is Undefined + + +@needs_pydanticv1 +def test_upload_file_dummy_with_info_plain_validator_function(): + # For coverage + assert UploadFile.__get_pydantic_core_schema__(str, lambda x: None) == {} + + +@needs_pydanticv1 +def test_union_scalar_list(): + # For coverage + # TODO: there might not be a current valid code path that uses this, it would + # potentially enable query parameters defined as both a scalar and a list + # but that would require more refactors, also not sure it's really useful + from fastapi._compat import is_pv1_scalar_field + + field_info = FieldInfo() + field = ModelField( + name="foo", + field_info=field_info, + type_=Union[str, List[int]], + class_validators={}, + model_config=BaseConfig, + ) + assert not is_pv1_scalar_field(field) + + +@needs_pydanticv2 +def test_get_model_config(): + # For coverage in Pydantic v2 + class Foo(BaseModel): + model_config = ConfigDict(from_attributes=True) + + foo = Foo() + config = _get_model_config(foo) + assert config == {"from_attributes": True} + + +def test_complex(): + app = FastAPI() + + @app.post("/") + def foo(foo: Union[str, List[int]]): + return foo + + client = TestClient(app) + + response = client.post("/", json="bar") + assert response.status_code == 200, response.text + assert response.json() == "bar" + + response2 = client.post("/", json=[1, 2]) + assert response2.status_code == 200, response2.text + assert response2.json() == [1, 2] + + +def test_is_bytes_sequence_annotation_union(): + # For coverage + # TODO: in theory this would allow declaring types that could be lists of bytes + # to be read from files and other types, but I'm not even sure it's a good idea + # to support it as a first class "feature" + assert is_bytes_sequence_annotation(Union[List[str], List[bytes]]) + + +def test_is_uploadfile_sequence_annotation(): + # For coverage + # TODO: in theory this would allow declaring types that could be lists of UploadFile + # and other types, but I'm not even sure it's a good idea to support it as a first + # class "feature" + assert is_uploadfile_sequence_annotation(Union[List[str], List[UploadFile]]) diff --git a/tests/test_computed_fields.py b/tests/test_computed_fields.py new file mode 100644 index 0000000000000..5286507b2d348 --- /dev/null +++ b/tests/test_computed_fields.py @@ -0,0 +1,77 @@ +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient + +from .utils import needs_pydanticv2 + + +@pytest.fixture(name="client") +def get_client(): + app = FastAPI() + + from pydantic import BaseModel, computed_field + + class Rectangle(BaseModel): + width: int + length: int + + @computed_field + @property + def area(self) -> int: + return self.width * self.length + + @app.get("/") + def read_root() -> Rectangle: + return Rectangle(width=3, length=4) + + client = TestClient(app) + return client + + +@needs_pydanticv2 +def test_get(client: TestClient): + response = client.get("/") + assert response.status_code == 200, response.text + assert response.json() == {"width": 3, "length": 4, "area": 12} + + +@needs_pydanticv2 +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/": { + "get": { + "summary": "Read Root", + "operationId": "read_root__get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Rectangle"} + } + }, + } + }, + } + } + }, + "components": { + "schemas": { + "Rectangle": { + "properties": { + "width": {"type": "integer", "title": "Width"}, + "length": {"type": "integer", "title": "Length"}, + "area": {"type": "integer", "title": "Area", "readOnly": True}, + }, + "type": "object", + "required": ["width", "length", "area"], + "title": "Rectangle", + } + } + }, + } diff --git a/tests/test_custom_route_class.py b/tests/test_custom_route_class.py index d1b18ef1d2f55..55374584b095a 100644 --- a/tests/test_custom_route_class.py +++ b/tests/test_custom_route_class.py @@ -75,7 +75,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/a/": { diff --git a/tests/test_custom_schema_fields.py b/tests/test_custom_schema_fields.py index 10b02608c3ee4..ee51fc7ff5e9b 100644 --- a/tests/test_custom_schema_fields.py +++ b/tests/test_custom_schema_fields.py @@ -1,4 +1,5 @@ from fastapi import FastAPI +from fastapi._compat import PYDANTIC_V2 from fastapi.testclient import TestClient from pydantic import BaseModel @@ -8,10 +9,18 @@ class Item(BaseModel): name: str - class Config: - schema_extra = { - "x-something-internal": {"level": 4}, + if PYDANTIC_V2: + model_config = { + "json_schema_extra": { + "x-something-internal": {"level": 4}, + } } + else: + + class Config: + schema_extra = { + "x-something-internal": {"level": 4}, + } @app.get("/foo", response_model=Item) diff --git a/tests/test_datastructures.py b/tests/test_datastructures.py index 2e6217d34eb08..7e57d525ce800 100644 --- a/tests/test_datastructures.py +++ b/tests/test_datastructures.py @@ -1,3 +1,4 @@ +import io from pathlib import Path from typing import List @@ -7,11 +8,17 @@ from fastapi.testclient import TestClient +# TODO: remove when deprecating Pydantic v1 def test_upload_file_invalid(): with pytest.raises(ValueError): UploadFile.validate("not a Starlette UploadFile") +def test_upload_file_invalid_pydantic_v2(): + with pytest.raises(ValueError): + UploadFile._validate("not a Starlette UploadFile", {}) + + def test_default_placeholder_equals(): placeholder_1 = Default("a") placeholder_2 = Default("a") @@ -46,3 +53,20 @@ def create_upload_file(file: UploadFile): assert testing_file_store assert testing_file_store[0].file.closed + + +# For UploadFile coverage, segments copied from Starlette tests + + +@pytest.mark.anyio +async def test_upload_file(): + stream = io.BytesIO(b"data") + file = UploadFile(filename="file", file=stream, size=4) + assert await file.read() == b"data" + assert file.size == 4 + await file.write(b" and more data!") + assert await file.read() == b"" + assert file.size == 19 + await file.seek(0) + assert await file.read() == b"data and more data!" + await file.close() diff --git a/tests/test_datetime_custom_encoder.py b/tests/test_datetime_custom_encoder.py index 5c1833eb4cea6..3aa77c0b1db47 100644 --- a/tests/test_datetime_custom_encoder.py +++ b/tests/test_datetime_custom_encoder.py @@ -4,31 +4,54 @@ from fastapi.testclient import TestClient from pydantic import BaseModel +from .utils import needs_pydanticv1, needs_pydanticv2 -class ModelWithDatetimeField(BaseModel): - dt_field: datetime - class Config: - json_encoders = { - datetime: lambda dt: dt.replace( - microsecond=0, tzinfo=timezone.utc - ).isoformat() - } +@needs_pydanticv2 +def test_pydanticv2(): + from pydantic import field_serializer + class ModelWithDatetimeField(BaseModel): + dt_field: datetime -app = FastAPI() -model = ModelWithDatetimeField(dt_field=datetime(2019, 1, 1, 8)) + @field_serializer("dt_field") + def serialize_datetime(self, dt_field: datetime): + return dt_field.replace(microsecond=0, tzinfo=timezone.utc).isoformat() + app = FastAPI() + model = ModelWithDatetimeField(dt_field=datetime(2019, 1, 1, 8)) -@app.get("/model", response_model=ModelWithDatetimeField) -def get_model(): - return model + @app.get("/model", response_model=ModelWithDatetimeField) + def get_model(): + return model + client = TestClient(app) + with client: + response = client.get("/model") + assert response.json() == {"dt_field": "2019-01-01T08:00:00+00:00"} + + +# TODO: remove when deprecating Pydantic v1 +@needs_pydanticv1 +def test_pydanticv1(): + class ModelWithDatetimeField(BaseModel): + dt_field: datetime + + class Config: + json_encoders = { + datetime: lambda dt: dt.replace( + microsecond=0, tzinfo=timezone.utc + ).isoformat() + } -client = TestClient(app) + app = FastAPI() + model = ModelWithDatetimeField(dt_field=datetime(2019, 1, 1, 8)) + @app.get("/model", response_model=ModelWithDatetimeField) + def get_model(): + return model -def test_dt(): + client = TestClient(app) with client: response = client.get("/model") assert response.json() == {"dt_field": "2019-01-01T08:00:00+00:00"} diff --git a/tests/test_dependency_contextmanager.py b/tests/test_dependency_contextmanager.py index 03ef56c4d7e5b..008dab7bc74cb 100644 --- a/tests/test_dependency_contextmanager.py +++ b/tests/test_dependency_contextmanager.py @@ -1,7 +1,9 @@ +import json from typing import Dict import pytest from fastapi import BackgroundTasks, Depends, FastAPI +from fastapi.responses import StreamingResponse from fastapi.testclient import TestClient app = FastAPI() @@ -53,6 +55,7 @@ async def asyncgen_state_try(state: Dict[str, str] = Depends(get_state)): yield state["/async_raise"] except AsyncDependencyError: errors.append("/async_raise") + raise finally: state["/async_raise"] = "asyncgen raise finalized" @@ -63,6 +66,7 @@ def generator_state_try(state: Dict[str, str] = Depends(get_state)): yield state["/sync_raise"] except SyncDependencyError: errors.append("/sync_raise") + raise finally: state["/sync_raise"] = "generator raise finalized" @@ -200,6 +204,13 @@ async def bg(state: dict): return state +@app.middleware("http") +async def middleware(request, call_next): + response: StreamingResponse = await call_next(request) + response.headers["x-state"] = json.dumps(state.copy()) + return response + + client = TestClient(app) @@ -274,9 +285,13 @@ def test_background_tasks(): assert data["context_b"] == "started b" assert data["context_a"] == "started a" assert data["bg"] == "not set" + middleware_state = json.loads(response.headers["x-state"]) + assert middleware_state["context_b"] == "finished b with a: started a" + assert middleware_state["context_a"] == "finished a" + assert middleware_state["bg"] == "not set" assert state["context_b"] == "finished b with a: started a" assert state["context_a"] == "finished a" - assert state["bg"] == "bg set - b: started b - a: started a" + assert state["bg"] == "bg set - b: finished b with a: started a - a: finished a" def test_sync_raise_raises(): @@ -382,4 +397,7 @@ def test_sync_background_tasks(): assert data["sync_bg"] == "not set" assert state["context_b"] == "finished b with a: started a" assert state["context_a"] == "finished a" - assert state["sync_bg"] == "sync_bg set - b: started b - a: started a" + assert ( + state["sync_bg"] + == "sync_bg set - b: finished b with a: started a - a: finished a" + ) diff --git a/tests/test_dependency_duplicates.py b/tests/test_dependency_duplicates.py index 285fdf1ab717e..0882cc41d7abf 100644 --- a/tests/test_dependency_duplicates.py +++ b/tests/test_dependency_duplicates.py @@ -1,7 +1,9 @@ from typing import List +from dirty_equals import IsDict from fastapi import Depends, FastAPI from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url from pydantic import BaseModel app = FastAPI() @@ -47,15 +49,30 @@ async def no_duplicates_sub( def test_no_duplicates_invalid(): response = client.post("/no-duplicates", json={"item": {"data": "myitem"}}) assert response.status_code == 422, response.text - assert response.json() == { - "detail": [ - { - "loc": ["body", "item2"], - "msg": "field required", - "type": "value_error.missing", - } - ] - } + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "item2"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "item2"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) def test_no_duplicates(): @@ -86,7 +103,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/with-duplicates": { diff --git a/tests/test_dependency_normal_exceptions.py b/tests/test_dependency_normal_exceptions.py index 23c366d5d7a6f..326f8fd88b832 100644 --- a/tests/test_dependency_normal_exceptions.py +++ b/tests/test_dependency_normal_exceptions.py @@ -20,6 +20,7 @@ async def get_database(): fake_database.update(temp_database) except HTTPException: state["except"] = True + raise finally: state["finally"] = True diff --git a/tests/test_dependency_overrides.py b/tests/test_dependency_overrides.py index 8bb307971bd55..21cff998d18c4 100644 --- a/tests/test_dependency_overrides.py +++ b/tests/test_dependency_overrides.py @@ -1,8 +1,10 @@ from typing import Optional import pytest +from dirty_equals import IsDict from fastapi import APIRouter, Depends, FastAPI from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url app = FastAPI() @@ -50,99 +52,180 @@ async def overrider_dependency_with_sub(msg: dict = Depends(overrider_sub_depend return msg -@pytest.mark.parametrize( - "url,status_code,expected", - [ - ( - "/main-depends/", - 422, - { - "detail": [ - { - "loc": ["query", "q"], - "msg": "field required", - "type": "value_error.missing", - } - ] - }, - ), - ( - "/main-depends/?q=foo", - 200, - {"in": "main-depends", "params": {"q": "foo", "skip": 0, "limit": 100}}, - ), - ( - "/main-depends/?q=foo&skip=100&limit=200", - 200, - {"in": "main-depends", "params": {"q": "foo", "skip": 100, "limit": 200}}, - ), - ( - "/decorator-depends/", - 422, - { - "detail": [ - { - "loc": ["query", "q"], - "msg": "field required", - "type": "value_error.missing", - } - ] - }, - ), - ("/decorator-depends/?q=foo", 200, {"in": "decorator-depends"}), - ( - "/decorator-depends/?q=foo&skip=100&limit=200", - 200, - {"in": "decorator-depends"}, - ), - ( - "/router-depends/", - 422, - { - "detail": [ - { - "loc": ["query", "q"], - "msg": "field required", - "type": "value_error.missing", - } - ] - }, - ), - ( - "/router-depends/?q=foo", - 200, - {"in": "router-depends", "params": {"q": "foo", "skip": 0, "limit": 100}}, - ), - ( - "/router-depends/?q=foo&skip=100&limit=200", - 200, - {"in": "router-depends", "params": {"q": "foo", "skip": 100, "limit": 200}}, - ), - ( - "/router-decorator-depends/", - 422, - { - "detail": [ - { - "loc": ["query", "q"], - "msg": "field required", - "type": "value_error.missing", - } - ] - }, - ), - ("/router-decorator-depends/?q=foo", 200, {"in": "router-decorator-depends"}), - ( - "/router-decorator-depends/?q=foo&skip=100&limit=200", - 200, - {"in": "router-decorator-depends"}, - ), - ], -) -def test_normal_app(url, status_code, expected): - response = client.get(url) - assert response.status_code == status_code - assert response.json() == expected +def test_main_depends(): + response = client.get("/main-depends/") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["query", "q"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["query", "q"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) + + +def test_main_depends_q_foo(): + response = client.get("/main-depends/?q=foo") + assert response.status_code == 200 + assert response.json() == { + "in": "main-depends", + "params": {"q": "foo", "skip": 0, "limit": 100}, + } + + +def test_main_depends_q_foo_skip_100_limit_200(): + response = client.get("/main-depends/?q=foo&skip=100&limit=200") + assert response.status_code == 200 + assert response.json() == { + "in": "main-depends", + "params": {"q": "foo", "skip": 100, "limit": 200}, + } + + +def test_decorator_depends(): + response = client.get("/decorator-depends/") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["query", "q"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["query", "q"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) + + +def test_decorator_depends_q_foo(): + response = client.get("/decorator-depends/?q=foo") + assert response.status_code == 200 + assert response.json() == {"in": "decorator-depends"} + + +def test_decorator_depends_q_foo_skip_100_limit_200(): + response = client.get("/decorator-depends/?q=foo&skip=100&limit=200") + assert response.status_code == 200 + assert response.json() == {"in": "decorator-depends"} + + +def test_router_depends(): + response = client.get("/router-depends/") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["query", "q"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["query", "q"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) + + +def test_router_depends_q_foo(): + response = client.get("/router-depends/?q=foo") + assert response.status_code == 200 + assert response.json() == { + "in": "router-depends", + "params": {"q": "foo", "skip": 0, "limit": 100}, + } + + +def test_router_depends_q_foo_skip_100_limit_200(): + response = client.get("/router-depends/?q=foo&skip=100&limit=200") + assert response.status_code == 200 + assert response.json() == { + "in": "router-depends", + "params": {"q": "foo", "skip": 100, "limit": 200}, + } + + +def test_router_decorator_depends(): + response = client.get("/router-decorator-depends/") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["query", "q"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["query", "q"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) + + +def test_router_decorator_depends_q_foo(): + response = client.get("/router-decorator-depends/?q=foo") + assert response.status_code == 200 + assert response.json() == {"in": "router-decorator-depends"} + + +def test_router_decorator_depends_q_foo_skip_100_limit_200(): + response = client.get("/router-decorator-depends/?q=foo&skip=100&limit=200") + assert response.status_code == 200 + assert response.json() == {"in": "router-decorator-depends"} @pytest.mark.parametrize( @@ -190,126 +273,281 @@ def test_override_simple(url, status_code, expected): app.dependency_overrides = {} -@pytest.mark.parametrize( - "url,status_code,expected", - [ - ( - "/main-depends/", - 422, - { - "detail": [ - { - "loc": ["query", "k"], - "msg": "field required", - "type": "value_error.missing", - } - ] - }, - ), - ( - "/main-depends/?q=foo", - 422, - { - "detail": [ - { - "loc": ["query", "k"], - "msg": "field required", - "type": "value_error.missing", - } - ] - }, - ), - ("/main-depends/?k=bar", 200, {"in": "main-depends", "params": {"k": "bar"}}), - ( - "/decorator-depends/", - 422, - { - "detail": [ - { - "loc": ["query", "k"], - "msg": "field required", - "type": "value_error.missing", - } - ] - }, - ), - ( - "/decorator-depends/?q=foo", - 422, - { - "detail": [ - { - "loc": ["query", "k"], - "msg": "field required", - "type": "value_error.missing", - } - ] - }, - ), - ("/decorator-depends/?k=bar", 200, {"in": "decorator-depends"}), - ( - "/router-depends/", - 422, - { - "detail": [ - { - "loc": ["query", "k"], - "msg": "field required", - "type": "value_error.missing", - } - ] - }, - ), - ( - "/router-depends/?q=foo", - 422, - { - "detail": [ - { - "loc": ["query", "k"], - "msg": "field required", - "type": "value_error.missing", - } - ] - }, - ), - ( - "/router-depends/?k=bar", - 200, - {"in": "router-depends", "params": {"k": "bar"}}, - ), - ( - "/router-decorator-depends/", - 422, - { - "detail": [ - { - "loc": ["query", "k"], - "msg": "field required", - "type": "value_error.missing", - } - ] - }, - ), - ( - "/router-decorator-depends/?q=foo", - 422, - { - "detail": [ - { - "loc": ["query", "k"], - "msg": "field required", - "type": "value_error.missing", - } - ] - }, - ), - ("/router-decorator-depends/?k=bar", 200, {"in": "router-decorator-depends"}), - ], -) -def test_override_with_sub(url, status_code, expected): +def test_override_with_sub_main_depends(): app.dependency_overrides[common_parameters] = overrider_dependency_with_sub - response = client.get(url) - assert response.status_code == status_code - assert response.json() == expected + response = client.get("/main-depends/") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["query", "k"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["query", "k"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) + app.dependency_overrides = {} + + +def test_override_with_sub__main_depends_q_foo(): + app.dependency_overrides[common_parameters] = overrider_dependency_with_sub + response = client.get("/main-depends/?q=foo") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["query", "k"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["query", "k"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) + app.dependency_overrides = {} + + +def test_override_with_sub_main_depends_k_bar(): + app.dependency_overrides[common_parameters] = overrider_dependency_with_sub + response = client.get("/main-depends/?k=bar") + assert response.status_code == 200 + assert response.json() == {"in": "main-depends", "params": {"k": "bar"}} + app.dependency_overrides = {} + + +def test_override_with_sub_decorator_depends(): + app.dependency_overrides[common_parameters] = overrider_dependency_with_sub + response = client.get("/decorator-depends/") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["query", "k"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["query", "k"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) + app.dependency_overrides = {} + + +def test_override_with_sub_decorator_depends_q_foo(): + app.dependency_overrides[common_parameters] = overrider_dependency_with_sub + response = client.get("/decorator-depends/?q=foo") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["query", "k"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["query", "k"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) + app.dependency_overrides = {} + + +def test_override_with_sub_decorator_depends_k_bar(): + app.dependency_overrides[common_parameters] = overrider_dependency_with_sub + response = client.get("/decorator-depends/?k=bar") + assert response.status_code == 200 + assert response.json() == {"in": "decorator-depends"} + app.dependency_overrides = {} + + +def test_override_with_sub_router_depends(): + app.dependency_overrides[common_parameters] = overrider_dependency_with_sub + response = client.get("/router-depends/") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["query", "k"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["query", "k"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) + app.dependency_overrides = {} + + +def test_override_with_sub_router_depends_q_foo(): + app.dependency_overrides[common_parameters] = overrider_dependency_with_sub + response = client.get("/router-depends/?q=foo") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["query", "k"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["query", "k"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) + app.dependency_overrides = {} + + +def test_override_with_sub_router_depends_k_bar(): + app.dependency_overrides[common_parameters] = overrider_dependency_with_sub + response = client.get("/router-depends/?k=bar") + assert response.status_code == 200 + assert response.json() == {"in": "router-depends", "params": {"k": "bar"}} + app.dependency_overrides = {} + + +def test_override_with_sub_router_decorator_depends(): + app.dependency_overrides[common_parameters] = overrider_dependency_with_sub + response = client.get("/router-decorator-depends/") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["query", "k"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["query", "k"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) + app.dependency_overrides = {} + + +def test_override_with_sub_router_decorator_depends_q_foo(): + app.dependency_overrides[common_parameters] = overrider_dependency_with_sub + response = client.get("/router-decorator-depends/?q=foo") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["query", "k"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["query", "k"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) + app.dependency_overrides = {} + + +def test_override_with_sub_router_decorator_depends_k_bar(): + app.dependency_overrides[common_parameters] = overrider_dependency_with_sub + response = client.get("/router-decorator-depends/?k=bar") + assert response.status_code == 200 + assert response.json() == {"in": "router-decorator-depends"} app.dependency_overrides = {} diff --git a/tests/test_deprecated_openapi_prefix.py b/tests/test_deprecated_openapi_prefix.py index 688b9837f2d05..ec7366d2af702 100644 --- a/tests/test_deprecated_openapi_prefix.py +++ b/tests/test_deprecated_openapi_prefix.py @@ -22,7 +22,7 @@ def test_openapi(): response = client.get("/openapi.json") assert response.status_code == 200 assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/app": { diff --git a/tests/test_duplicate_models_openapi.py b/tests/test_duplicate_models_openapi.py index 116b2006a04a2..83e86d231a6f9 100644 --- a/tests/test_duplicate_models_openapi.py +++ b/tests/test_duplicate_models_openapi.py @@ -36,7 +36,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/": { diff --git a/tests/test_enforce_once_required_parameter.py b/tests/test_enforce_once_required_parameter.py index bf05aa5852ac9..b64f8341b8c1f 100644 --- a/tests/test_enforce_once_required_parameter.py +++ b/tests/test_enforce_once_required_parameter.py @@ -57,7 +57,7 @@ def foo_handler( } }, "info": {"title": "FastAPI", "version": "0.1.0"}, - "openapi": "3.0.2", + "openapi": "3.1.0", "paths": { "/foo": { "get": { diff --git a/tests/test_extra_routes.py b/tests/test_extra_routes.py index c0db62c19d40c..bd16fe9254cc3 100644 --- a/tests/test_extra_routes.py +++ b/tests/test_extra_routes.py @@ -1,5 +1,6 @@ from typing import Optional +from dirty_equals import IsDict from fastapi import FastAPI from fastapi.responses import JSONResponse from fastapi.testclient import TestClient @@ -99,7 +100,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { @@ -327,7 +328,14 @@ def test_openapi_schema(): "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, - "price": {"title": "Price", "type": "number"}, + "price": IsDict( + { + "title": "Price", + "anyOf": [{"type": "number"}, {"type": "null"}], + } + ) + # TODO: remove when deprecating Pydantic v1 + | IsDict({"title": "Price", "type": "number"}), }, }, "ValidationError": { diff --git a/docs_src/sql_databases_peewee/__init__.py b/tests/test_filter_pydantic_sub_model/__init__.py similarity index 100% rename from docs_src/sql_databases_peewee/__init__.py rename to tests/test_filter_pydantic_sub_model/__init__.py diff --git a/tests/test_filter_pydantic_sub_model/app_pv1.py b/tests/test_filter_pydantic_sub_model/app_pv1.py new file mode 100644 index 0000000000000..657e8c5d12624 --- /dev/null +++ b/tests/test_filter_pydantic_sub_model/app_pv1.py @@ -0,0 +1,35 @@ +from typing import Optional + +from fastapi import Depends, FastAPI +from pydantic import BaseModel, validator + +app = FastAPI() + + +class ModelB(BaseModel): + username: str + + +class ModelC(ModelB): + password: str + + +class ModelA(BaseModel): + name: str + description: Optional[str] = None + model_b: ModelB + + @validator("name") + def lower_username(cls, name: str, values): + if not name.endswith("A"): + raise ValueError("name must end in A") + return name + + +async def get_model_c() -> ModelC: + return ModelC(username="test-user", password="test-password") + + +@app.get("/model/{name}", response_model=ModelA) +async def get_model_a(name: str, model_c=Depends(get_model_c)): + return {"name": name, "description": "model-a-desc", "model_b": model_c} diff --git a/tests/test_filter_pydantic_sub_model.py b/tests/test_filter_pydantic_sub_model/test_filter_pydantic_sub_model_pv1.py similarity index 80% rename from tests/test_filter_pydantic_sub_model.py rename to tests/test_filter_pydantic_sub_model/test_filter_pydantic_sub_model_pv1.py index 15b15f8624498..48732dbf06ea5 100644 --- a/tests/test_filter_pydantic_sub_model.py +++ b/tests/test_filter_pydantic_sub_model/test_filter_pydantic_sub_model_pv1.py @@ -1,46 +1,20 @@ -from typing import Optional - import pytest -from fastapi import Depends, FastAPI +from fastapi.exceptions import ResponseValidationError from fastapi.testclient import TestClient -from pydantic import BaseModel, ValidationError, validator - -app = FastAPI() - - -class ModelB(BaseModel): - username: str - - -class ModelC(ModelB): - password: str - - -class ModelA(BaseModel): - name: str - description: Optional[str] = None - model_b: ModelB - - @validator("name") - def lower_username(cls, name: str, values): - if not name.endswith("A"): - raise ValueError("name must end in A") - return name - - -async def get_model_c() -> ModelC: - return ModelC(username="test-user", password="test-password") +from ..utils import needs_pydanticv1 -@app.get("/model/{name}", response_model=ModelA) -async def get_model_a(name: str, model_c=Depends(get_model_c)): - return {"name": name, "description": "model-a-desc", "model_b": model_c} +@pytest.fixture(name="client") +def get_client(): + from .app_pv1 import app -client = TestClient(app) + client = TestClient(app) + return client -def test_filter_sub_model(): +@needs_pydanticv1 +def test_filter_sub_model(client: TestClient): response = client.get("/model/modelA") assert response.status_code == 200, response.text assert response.json() == { @@ -50,8 +24,9 @@ def test_filter_sub_model(): } -def test_validator_is_cloned(): - with pytest.raises(ValidationError) as err: +@needs_pydanticv1 +def test_validator_is_cloned(client: TestClient): + with pytest.raises(ResponseValidationError) as err: client.get("/model/modelX") assert err.value.errors() == [ { @@ -62,11 +37,12 @@ def test_validator_is_cloned(): ] -def test_openapi_schema(): +@needs_pydanticv1 +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/model/{name}": { diff --git a/tests/test_filter_pydantic_sub_model_pv2.py b/tests/test_filter_pydantic_sub_model_pv2.py new file mode 100644 index 0000000000000..9097d2ce52e01 --- /dev/null +++ b/tests/test_filter_pydantic_sub_model_pv2.py @@ -0,0 +1,186 @@ +from typing import Optional + +import pytest +from dirty_equals import HasRepr, IsDict, IsOneOf +from fastapi import Depends, FastAPI +from fastapi.exceptions import ResponseValidationError +from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url + +from .utils import needs_pydanticv2 + + +@pytest.fixture(name="client") +def get_client(): + from pydantic import BaseModel, ValidationInfo, field_validator + + app = FastAPI() + + class ModelB(BaseModel): + username: str + + class ModelC(ModelB): + password: str + + class ModelA(BaseModel): + name: str + description: Optional[str] = None + foo: ModelB + + @field_validator("name") + def lower_username(cls, name: str, info: ValidationInfo): + if not name.endswith("A"): + raise ValueError("name must end in A") + return name + + async def get_model_c() -> ModelC: + return ModelC(username="test-user", password="test-password") + + @app.get("/model/{name}", response_model=ModelA) + async def get_model_a(name: str, model_c=Depends(get_model_c)): + return {"name": name, "description": "model-a-desc", "foo": model_c} + + client = TestClient(app) + return client + + +@needs_pydanticv2 +def test_filter_sub_model(client: TestClient): + response = client.get("/model/modelA") + assert response.status_code == 200, response.text + assert response.json() == { + "name": "modelA", + "description": "model-a-desc", + "foo": {"username": "test-user"}, + } + + +@needs_pydanticv2 +def test_validator_is_cloned(client: TestClient): + with pytest.raises(ResponseValidationError) as err: + client.get("/model/modelX") + assert err.value.errors() == [ + IsDict( + { + "type": "value_error", + "loc": ("response", "name"), + "msg": "Value error, name must end in A", + "input": "modelX", + "ctx": {"error": HasRepr("ValueError('name must end in A')")}, + "url": match_pydantic_error_url("value_error"), + } + ) + | IsDict( + # TODO remove when deprecating Pydantic v1 + { + "loc": ("response", "name"), + "msg": "name must end in A", + "type": "value_error", + } + ) + ] + + +@needs_pydanticv2 +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/model/{name}": { + "get": { + "summary": "Get Model A", + "operationId": "get_model_a_model__name__get", + "parameters": [ + { + "required": True, + "schema": {"title": "Name", "type": "string"}, + "name": "name", + "in": "path", + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/ModelA"} + } + }, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + } + }, + "components": { + "schemas": { + "HTTPValidationError": { + "title": "HTTPValidationError", + "type": "object", + "properties": { + "detail": { + "title": "Detail", + "type": "array", + "items": {"$ref": "#/components/schemas/ValidationError"}, + } + }, + }, + "ModelA": { + "title": "ModelA", + "required": IsOneOf( + ["name", "description", "foo"], + # TODO remove when deprecating Pydantic v1 + ["name", "foo"], + ), + "type": "object", + "properties": { + "name": {"title": "Name", "type": "string"}, + "description": IsDict( + { + "title": "Description", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | + # TODO remove when deprecating Pydantic v1 + IsDict({"title": "Description", "type": "string"}), + "foo": {"$ref": "#/components/schemas/ModelB"}, + }, + }, + "ModelB": { + "title": "ModelB", + "required": ["username"], + "type": "object", + "properties": {"username": {"title": "Username", "type": "string"}}, + }, + "ValidationError": { + "title": "ValidationError", + "required": ["loc", "msg", "type"], + "type": "object", + "properties": { + "loc": { + "title": "Location", + "type": "array", + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + }, + "msg": {"title": "Message", "type": "string"}, + "type": {"title": "Error Type", "type": "string"}, + }, + }, + } + }, + } diff --git a/tests/test_generate_unique_id_function.py b/tests/test_generate_unique_id_function.py index 0b519f8596f5b..5aeec66367a7c 100644 --- a/tests/test_generate_unique_id_function.py +++ b/tests/test_generate_unique_id_function.py @@ -48,7 +48,7 @@ def post_router(item1: Item, item2: Item): response = client.get("/openapi.json") data = response.json() assert data == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/": { @@ -249,7 +249,7 @@ def post_router(item1: Item, item2: Item): response = client.get("/openapi.json") data = response.json() assert data == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/": { @@ -450,7 +450,7 @@ def post_router(item1: Item, item2: Item): response = client.get("/openapi.json") data = response.json() assert data == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/": { @@ -661,7 +661,7 @@ def post_subrouter(item1: Item, item2: Item): response = client.get("/openapi.json") data = response.json() assert data == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/": { @@ -928,7 +928,7 @@ def post_router(item1: Item, item2: Item): response = client.get("/openapi.json") data = response.json() assert data == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/": { @@ -1136,7 +1136,7 @@ def post_router(item1: Item, item2: Item): response = client.get("/openapi.json") data = response.json() assert data == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/": { @@ -1353,7 +1353,7 @@ def post_with_callback(item1: Item, item2: Item): response = client.get("/openapi.json") data = response.json() assert data == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/": { @@ -1626,6 +1626,9 @@ def post_third(item1: Item): with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") client.get("/openapi.json") - assert len(w) == 2 - assert issubclass(w[-1].category, UserWarning) - assert "Duplicate Operation ID" in str(w[-1].message) + assert len(w) >= 2 + duplicate_warnings = [ + warning for warning in w if issubclass(warning.category, UserWarning) + ] + assert len(duplicate_warnings) > 0 + assert "Duplicate Operation ID" in str(duplicate_warnings[0].message) diff --git a/tests/test_get_request_body.py b/tests/test_get_request_body.py index 541147fa8f123..cc567b88f6f68 100644 --- a/tests/test_get_request_body.py +++ b/tests/test_get_request_body.py @@ -29,7 +29,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/product": { diff --git a/tests/test_include_router_defaults_overrides.py b/tests/test_include_router_defaults_overrides.py index ced56c84d30fd..33baa25e6a798 100644 --- a/tests/test_include_router_defaults_overrides.py +++ b/tests/test_include_router_defaults_overrides.py @@ -443,7 +443,7 @@ def test_openapi(): assert issubclass(w[-1].category, UserWarning) assert "Duplicate Operation ID" in str(w[-1].message) assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/override1": { diff --git a/tests/test_infer_param_optionality.py b/tests/test_infer_param_optionality.py index 5e673d9c4d796..e3d57bb428bf2 100644 --- a/tests/test_infer_param_optionality.py +++ b/tests/test_infer_param_optionality.py @@ -1,5 +1,6 @@ from typing import Optional +from dirty_equals import IsDict from fastapi import APIRouter, FastAPI from fastapi.testclient import TestClient @@ -104,35 +105,253 @@ def test_get_users_item(): assert response.json() == {"item_id": "item01", "user_id": "abc123"} -def test_schema_1(): - """Check that the user_id is a required path parameter under /users""" +def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text - r = response.json() - - d = { - "required": True, - "schema": {"title": "User Id", "type": "string"}, - "name": "user_id", - "in": "path", + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/users/": { + "get": { + "summary": "Get Users", + "operationId": "get_users_users__get", + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + } + }, + } + }, + "/users/{user_id}": { + "get": { + "summary": "Get User", + "operationId": "get_user_users__user_id__get", + "parameters": [ + { + "required": True, + "schema": {"title": "User Id", "type": "string"}, + "name": "user_id", + "in": "path", + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + }, + "/items/": { + "get": { + "summary": "Get Items", + "operationId": "get_items_items__get", + "parameters": [ + { + "required": False, + "name": "user_id", + "in": "query", + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "User Id", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "User Id", "type": "string"} + ), + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + }, + "/items/{item_id}": { + "get": { + "summary": "Get Item", + "operationId": "get_item_items__item_id__get", + "parameters": [ + { + "required": True, + "schema": {"title": "Item Id", "type": "string"}, + "name": "item_id", + "in": "path", + }, + { + "required": False, + "name": "user_id", + "in": "query", + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "User Id", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "User Id", "type": "string"} + ), + }, + ], + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + }, + "/users/{user_id}/items/": { + "get": { + "summary": "Get Items", + "operationId": "get_items_users__user_id__items__get", + "parameters": [ + { + "required": True, + "name": "user_id", + "in": "path", + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "User Id", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "User Id", "type": "string"} + ), + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + }, + "/users/{user_id}/items/{item_id}": { + "get": { + "summary": "Get Item", + "operationId": "get_item_users__user_id__items__item_id__get", + "parameters": [ + { + "required": True, + "schema": {"title": "Item Id", "type": "string"}, + "name": "item_id", + "in": "path", + }, + { + "required": True, + "name": "user_id", + "in": "path", + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "User Id", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "User Id", "type": "string"} + ), + }, + ], + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + }, + }, + "components": { + "schemas": { + "HTTPValidationError": { + "title": "HTTPValidationError", + "type": "object", + "properties": { + "detail": { + "title": "Detail", + "type": "array", + "items": {"$ref": "#/components/schemas/ValidationError"}, + } + }, + }, + "ValidationError": { + "title": "ValidationError", + "required": ["loc", "msg", "type"], + "type": "object", + "properties": { + "loc": { + "title": "Location", + "type": "array", + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + }, + "msg": {"title": "Message", "type": "string"}, + "type": {"title": "Error Type", "type": "string"}, + }, + }, + } + }, } - - assert d in r["paths"]["/users/{user_id}"]["get"]["parameters"] - assert d in r["paths"]["/users/{user_id}/items/"]["get"]["parameters"] - - -def test_schema_2(): - """Check that the user_id is an optional query parameter under /items""" - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - r = response.json() - - d = { - "required": False, - "schema": {"title": "User Id", "type": "string"}, - "name": "user_id", - "in": "query", - } - - assert d in r["paths"]["/items/{item_id}"]["get"]["parameters"] - assert d in r["paths"]["/items/"]["get"]["parameters"] diff --git a/tests/test_inherited_custom_class.py b/tests/test_inherited_custom_class.py index bac7eec1b0886..42b249211ddc9 100644 --- a/tests/test_inherited_custom_class.py +++ b/tests/test_inherited_custom_class.py @@ -5,7 +5,7 @@ from fastapi.testclient import TestClient from pydantic import BaseModel -app = FastAPI() +from .utils import needs_pydanticv1, needs_pydanticv2 class MyUuid: @@ -26,40 +26,78 @@ def __dict__(self): raise TypeError("vars() argument must have __dict__ attribute") -@app.get("/fast_uuid") -def return_fast_uuid(): - # I don't want to import asyncpg for this test so I made my own UUID - # Import asyncpg and uncomment the two lines below for the actual bug +@needs_pydanticv2 +def test_pydanticv2(): + from pydantic import field_serializer - # from asyncpg.pgproto import pgproto - # asyncpg_uuid = pgproto.UUID("a10ff360-3b1e-4984-a26f-d3ab460bdb51") + app = FastAPI() - asyncpg_uuid = MyUuid("a10ff360-3b1e-4984-a26f-d3ab460bdb51") - assert isinstance(asyncpg_uuid, uuid.UUID) - assert type(asyncpg_uuid) != uuid.UUID - with pytest.raises(TypeError): - vars(asyncpg_uuid) - return {"fast_uuid": asyncpg_uuid} + @app.get("/fast_uuid") + def return_fast_uuid(): + asyncpg_uuid = MyUuid("a10ff360-3b1e-4984-a26f-d3ab460bdb51") + assert isinstance(asyncpg_uuid, uuid.UUID) + assert type(asyncpg_uuid) != uuid.UUID + with pytest.raises(TypeError): + vars(asyncpg_uuid) + return {"fast_uuid": asyncpg_uuid} + class SomeCustomClass(BaseModel): + model_config = {"arbitrary_types_allowed": True} -class SomeCustomClass(BaseModel): - class Config: - arbitrary_types_allowed = True - json_encoders = {uuid.UUID: str} + a_uuid: MyUuid - a_uuid: MyUuid + @field_serializer("a_uuid") + def serialize_a_uuid(self, v): + return str(v) + @app.get("/get_custom_class") + def return_some_user(): + # Test that the fix also works for custom pydantic classes + return SomeCustomClass(a_uuid=MyUuid("b8799909-f914-42de-91bc-95c819218d01")) -@app.get("/get_custom_class") -def return_some_user(): - # Test that the fix also works for custom pydantic classes - return SomeCustomClass(a_uuid=MyUuid("b8799909-f914-42de-91bc-95c819218d01")) + client = TestClient(app) + with client: + response_simple = client.get("/fast_uuid") + response_pydantic = client.get("/get_custom_class") + + assert response_simple.json() == { + "fast_uuid": "a10ff360-3b1e-4984-a26f-d3ab460bdb51" + } + + assert response_pydantic.json() == { + "a_uuid": "b8799909-f914-42de-91bc-95c819218d01" + } + + +# TODO: remove when deprecating Pydantic v1 +@needs_pydanticv1 +def test_pydanticv1(): + app = FastAPI() + + @app.get("/fast_uuid") + def return_fast_uuid(): + asyncpg_uuid = MyUuid("a10ff360-3b1e-4984-a26f-d3ab460bdb51") + assert isinstance(asyncpg_uuid, uuid.UUID) + assert type(asyncpg_uuid) != uuid.UUID + with pytest.raises(TypeError): + vars(asyncpg_uuid) + return {"fast_uuid": asyncpg_uuid} + + class SomeCustomClass(BaseModel): + class Config: + arbitrary_types_allowed = True + json_encoders = {uuid.UUID: str} + + a_uuid: MyUuid -client = TestClient(app) + @app.get("/get_custom_class") + def return_some_user(): + # Test that the fix also works for custom pydantic classes + return SomeCustomClass(a_uuid=MyUuid("b8799909-f914-42de-91bc-95c819218d01")) + client = TestClient(app) -def test_dt(): with client: response_simple = client.get("/fast_uuid") response_pydantic = client.get("/get_custom_class") diff --git a/tests/test_jsonable_encoder.py b/tests/test_jsonable_encoder.py index f4fdcf6014a43..7c8338ff376d0 100644 --- a/tests/test_jsonable_encoder.py +++ b/tests/test_jsonable_encoder.py @@ -1,12 +1,17 @@ +from collections import deque from dataclasses import dataclass from datetime import datetime, timezone +from decimal import Decimal from enum import Enum from pathlib import PurePath, PurePosixPath, PureWindowsPath from typing import Optional import pytest +from fastapi._compat import PYDANTIC_V2 from fastapi.encoders import jsonable_encoder -from pydantic import BaseModel, Field, ValidationError, create_model +from pydantic import BaseModel, Field, ValidationError + +from .utils import needs_pydanticv1, needs_pydanticv2 class Person: @@ -45,22 +50,6 @@ def __dict__(self): raise NotImplementedError() -class ModelWithCustomEncoder(BaseModel): - dt_field: datetime - - class Config: - json_encoders = { - datetime: lambda dt: dt.replace( - microsecond=0, tzinfo=timezone.utc - ).isoformat() - } - - -class ModelWithCustomEncoderSubclass(ModelWithCustomEncoder): - class Config: - pass - - class RoleEnum(Enum): admin = "admin" normal = "normal" @@ -69,8 +58,12 @@ class RoleEnum(Enum): class ModelWithConfig(BaseModel): role: Optional[RoleEnum] = None - class Config: - use_enum_values = True + if PYDANTIC_V2: + model_config = {"use_enum_values": True} + else: + + class Config: + use_enum_values = True class ModelWithAlias(BaseModel): @@ -83,23 +76,6 @@ class ModelWithDefault(BaseModel): bla: str = "bla" -class ModelWithRoot(BaseModel): - __root__: str - - -@pytest.fixture( - name="model_with_path", params=[PurePath, PurePosixPath, PureWindowsPath] -) -def fixture_model_with_path(request): - class Config: - arbitrary_types_allowed = True - - ModelWithPath = create_model( - "ModelWithPath", path=(request.param, ...), __config__=Config # type: ignore - ) - return ModelWithPath(path=request.param("/foo", "bar")) - - def test_encode_dict(): pet = {"name": "Firulais", "owner": {"name": "Foo"}} assert jsonable_encoder(pet) == {"name": "Firulais", "owner": {"name": "Foo"}} @@ -153,14 +129,47 @@ def test_encode_unsupported(): jsonable_encoder(unserializable) -def test_encode_custom_json_encoders_model(): +@needs_pydanticv2 +def test_encode_custom_json_encoders_model_pydanticv2(): + from pydantic import field_serializer + + class ModelWithCustomEncoder(BaseModel): + dt_field: datetime + + @field_serializer("dt_field") + def serialize_dt_field(self, dt): + return dt.replace(microsecond=0, tzinfo=timezone.utc).isoformat() + + class ModelWithCustomEncoderSubclass(ModelWithCustomEncoder): + pass + model = ModelWithCustomEncoder(dt_field=datetime(2019, 1, 1, 8)) assert jsonable_encoder(model) == {"dt_field": "2019-01-01T08:00:00+00:00"} + subclass_model = ModelWithCustomEncoderSubclass(dt_field=datetime(2019, 1, 1, 8)) + assert jsonable_encoder(subclass_model) == {"dt_field": "2019-01-01T08:00:00+00:00"} + +# TODO: remove when deprecating Pydantic v1 +@needs_pydanticv1 +def test_encode_custom_json_encoders_model_pydanticv1(): + class ModelWithCustomEncoder(BaseModel): + dt_field: datetime -def test_encode_custom_json_encoders_model_subclass(): - model = ModelWithCustomEncoderSubclass(dt_field=datetime(2019, 1, 1, 8)) + class Config: + json_encoders = { + datetime: lambda dt: dt.replace( + microsecond=0, tzinfo=timezone.utc + ).isoformat() + } + + class ModelWithCustomEncoderSubclass(ModelWithCustomEncoder): + class Config: + pass + + model = ModelWithCustomEncoder(dt_field=datetime(2019, 1, 1, 8)) assert jsonable_encoder(model) == {"dt_field": "2019-01-01T08:00:00+00:00"} + subclass_model = ModelWithCustomEncoderSubclass(dt_field=datetime(2019, 1, 1, 8)) + assert jsonable_encoder(subclass_model) == {"dt_field": "2019-01-01T08:00:00+00:00"} def test_encode_model_with_config(): @@ -196,6 +205,7 @@ def test_encode_model_with_default(): } +@needs_pydanticv1 def test_custom_encoders(): class safe_datetime(datetime): pass @@ -226,14 +236,77 @@ class MyEnum(Enum): assert encoded_instance == custom_enum_encoder(instance) -def test_encode_model_with_path(model_with_path): - if isinstance(model_with_path.path, PureWindowsPath): - expected = "\\foo\\bar" - else: - expected = "/foo/bar" - assert jsonable_encoder(model_with_path) == {"path": expected} +def test_encode_model_with_pure_path(): + class ModelWithPath(BaseModel): + path: PurePath + + if PYDANTIC_V2: + model_config = {"arbitrary_types_allowed": True} + else: + + class Config: + arbitrary_types_allowed = True + + test_path = PurePath("/foo", "bar") + obj = ModelWithPath(path=test_path) + assert jsonable_encoder(obj) == {"path": str(test_path)} + + +def test_encode_model_with_pure_posix_path(): + class ModelWithPath(BaseModel): + path: PurePosixPath + + if PYDANTIC_V2: + model_config = {"arbitrary_types_allowed": True} + else: + + class Config: + arbitrary_types_allowed = True + + obj = ModelWithPath(path=PurePosixPath("/foo", "bar")) + assert jsonable_encoder(obj) == {"path": "/foo/bar"} + + +def test_encode_model_with_pure_windows_path(): + class ModelWithPath(BaseModel): + path: PureWindowsPath + + if PYDANTIC_V2: + model_config = {"arbitrary_types_allowed": True} + else: + class Config: + arbitrary_types_allowed = True + obj = ModelWithPath(path=PureWindowsPath("/foo", "bar")) + assert jsonable_encoder(obj) == {"path": "\\foo\\bar"} + + +@needs_pydanticv1 def test_encode_root(): + class ModelWithRoot(BaseModel): + __root__: str + model = ModelWithRoot(__root__="Foo") assert jsonable_encoder(model) == "Foo" + + +@needs_pydanticv2 +def test_decimal_encoder_float(): + data = {"value": Decimal(1.23)} + assert jsonable_encoder(data) == {"value": 1.23} + + +@needs_pydanticv2 +def test_decimal_encoder_int(): + data = {"value": Decimal(2)} + assert jsonable_encoder(data) == {"value": 2} + + +def test_encode_deque_encodes_child_models(): + class Model(BaseModel): + test: str + + dq = deque([Model(test="test")]) + + assert jsonable_encoder(dq)[0]["test"] == "test" diff --git a/tests/test_modules_same_name_body/test_main.py b/tests/test_modules_same_name_body/test_main.py index 1ebcaee8cf264..cc165bdcaa258 100644 --- a/tests/test_modules_same_name_body/test_main.py +++ b/tests/test_modules_same_name_body/test_main.py @@ -35,7 +35,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/a/compute": { diff --git a/tests/test_multi_body_errors.py b/tests/test_multi_body_errors.py index 358684bc5cef8..a51ca7253f825 100644 --- a/tests/test_multi_body_errors.py +++ b/tests/test_multi_body_errors.py @@ -1,8 +1,10 @@ from decimal import Decimal from typing import List +from dirty_equals import IsDict, IsOneOf from fastapi import FastAPI from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url from pydantic import BaseModel, condecimal app = FastAPI() @@ -21,66 +23,124 @@ def save_item_no_body(item: List[Item]): client = TestClient(app) -single_error = { - "detail": [ - { - "ctx": {"limit_value": 0.0}, - "loc": ["body", 0, "age"], - "msg": "ensure this value is greater than 0", - "type": "value_error.number.not_gt", - } - ] -} - -multiple_errors = { - "detail": [ - { - "loc": ["body", 0, "name"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", 0, "age"], - "msg": "value is not a valid decimal", - "type": "type_error.decimal", - }, - { - "loc": ["body", 1, "name"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", 1, "age"], - "msg": "value is not a valid decimal", - "type": "type_error.decimal", - }, - ] -} - - def test_put_correct_body(): response = client.post("/items/", json=[{"name": "Foo", "age": 5}]) assert response.status_code == 200, response.text - assert response.json() == {"item": [{"name": "Foo", "age": 5}]} + assert response.json() == { + "item": [ + { + "name": "Foo", + "age": IsOneOf( + 5, + # TODO: remove when deprecating Pydantic v1 + "5", + ), + } + ] + } def test_jsonable_encoder_requiring_error(): response = client.post("/items/", json=[{"name": "Foo", "age": -1.0}]) assert response.status_code == 422, response.text - assert response.json() == single_error + assert response.json() == IsDict( + { + "detail": [ + { + "type": "greater_than", + "loc": ["body", 0, "age"], + "msg": "Input should be greater than 0", + "input": -1.0, + "ctx": {"gt": 0}, + "url": match_pydantic_error_url("greater_than"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "ctx": {"limit_value": 0.0}, + "loc": ["body", 0, "age"], + "msg": "ensure this value is greater than 0", + "type": "value_error.number.not_gt", + } + ] + } + ) def test_put_incorrect_body_multiple(): response = client.post("/items/", json=[{"age": "five"}, {"age": "six"}]) assert response.status_code == 422, response.text - assert response.json() == multiple_errors + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", 0, "name"], + "msg": "Field required", + "input": {"age": "five"}, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "decimal_parsing", + "loc": ["body", 0, "age"], + "msg": "Input should be a valid decimal", + "input": "five", + "url": match_pydantic_error_url("decimal_parsing"), + }, + { + "type": "missing", + "loc": ["body", 1, "name"], + "msg": "Field required", + "input": {"age": "six"}, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "decimal_parsing", + "loc": ["body", 1, "age"], + "msg": "Input should be a valid decimal", + "input": "six", + "url": match_pydantic_error_url("decimal_parsing"), + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", 0, "name"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", 0, "age"], + "msg": "value is not a valid decimal", + "type": "type_error.decimal", + }, + { + "loc": ["body", 1, "name"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", 1, "age"], + "msg": "value is not a valid decimal", + "type": "type_error.decimal", + }, + ] + } + ) def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { @@ -126,11 +186,23 @@ def test_openapi_schema(): "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, - "age": { - "title": "Age", - "exclusiveMinimum": 0.0, - "type": "number", - }, + "age": IsDict( + { + "title": "Age", + "anyOf": [ + {"exclusiveMinimum": 0.0, "type": "number"}, + {"type": "string"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "Age", + "exclusiveMinimum": 0.0, + "type": "number", + } + ), }, }, "ValidationError": { diff --git a/tests/test_multi_query_errors.py b/tests/test_multi_query_errors.py index e7a833f2baf03..470a358083468 100644 --- a/tests/test_multi_query_errors.py +++ b/tests/test_multi_query_errors.py @@ -1,7 +1,9 @@ from typing import List +from dirty_equals import IsDict from fastapi import FastAPI, Query from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url app = FastAPI() @@ -14,22 +16,6 @@ def read_items(q: List[int] = Query(default=None)): client = TestClient(app) -multiple_errors = { - "detail": [ - { - "loc": ["query", "q", 0], - "msg": "value is not a valid integer", - "type": "type_error.integer", - }, - { - "loc": ["query", "q", 1], - "msg": "value is not a valid integer", - "type": "type_error.integer", - }, - ] -} - - def test_multi_query(): response = client.get("/items/?q=5&q=6") assert response.status_code == 200, response.text @@ -39,14 +25,49 @@ def test_multi_query(): def test_multi_query_incorrect(): response = client.get("/items/?q=five&q=six") assert response.status_code == 422, response.text - assert response.json() == multiple_errors + assert response.json() == IsDict( + { + "detail": [ + { + "type": "int_parsing", + "loc": ["query", "q", 0], + "msg": "Input should be a valid integer, unable to parse string as an integer", + "input": "five", + "url": match_pydantic_error_url("int_parsing"), + }, + { + "type": "int_parsing", + "loc": ["query", "q", 1], + "msg": "Input should be a valid integer, unable to parse string as an integer", + "input": "six", + "url": match_pydantic_error_url("int_parsing"), + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["query", "q", 0], + "msg": "value is not a valid integer", + "type": "type_error.integer", + }, + { + "loc": ["query", "q", 1], + "msg": "value is not a valid integer", + "type": "type_error.integer", + }, + ] + } + ) def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { diff --git a/tests/test_openapi_examples.py b/tests/test_openapi_examples.py new file mode 100644 index 0000000000000..6597e5058bfed --- /dev/null +++ b/tests/test_openapi_examples.py @@ -0,0 +1,458 @@ +from typing import Union + +from dirty_equals import IsDict +from fastapi import Body, Cookie, FastAPI, Header, Path, Query +from fastapi.testclient import TestClient +from pydantic import BaseModel + +app = FastAPI() + + +class Item(BaseModel): + data: str + + +@app.post("/examples/") +def examples( + item: Item = Body( + examples=[ + {"data": "Data in Body examples, example1"}, + ], + openapi_examples={ + "Example One": { + "summary": "Example One Summary", + "description": "Example One Description", + "value": {"data": "Data in Body examples, example1"}, + }, + "Example Two": { + "value": {"data": "Data in Body examples, example2"}, + }, + }, + ), +): + return item + + +@app.get("/path_examples/{item_id}") +def path_examples( + item_id: str = Path( + examples=[ + "json_schema_item_1", + "json_schema_item_2", + ], + openapi_examples={ + "Path One": { + "summary": "Path One Summary", + "description": "Path One Description", + "value": "item_1", + }, + "Path Two": { + "value": "item_2", + }, + }, + ), +): + return item_id + + +@app.get("/query_examples/") +def query_examples( + data: Union[str, None] = Query( + default=None, + examples=[ + "json_schema_query1", + "json_schema_query2", + ], + openapi_examples={ + "Query One": { + "summary": "Query One Summary", + "description": "Query One Description", + "value": "query1", + }, + "Query Two": { + "value": "query2", + }, + }, + ), +): + return data + + +@app.get("/header_examples/") +def header_examples( + data: Union[str, None] = Header( + default=None, + examples=[ + "json_schema_header1", + "json_schema_header2", + ], + openapi_examples={ + "Header One": { + "summary": "Header One Summary", + "description": "Header One Description", + "value": "header1", + }, + "Header Two": { + "value": "header2", + }, + }, + ), +): + return data + + +@app.get("/cookie_examples/") +def cookie_examples( + data: Union[str, None] = Cookie( + default=None, + examples=["json_schema_cookie1", "json_schema_cookie2"], + openapi_examples={ + "Cookie One": { + "summary": "Cookie One Summary", + "description": "Cookie One Description", + "value": "cookie1", + }, + "Cookie Two": { + "value": "cookie2", + }, + }, + ), +): + return data + + +client = TestClient(app) + + +def test_call_api(): + response = client.post("/examples/", json={"data": "example1"}) + assert response.status_code == 200, response.text + + response = client.get("/path_examples/foo") + assert response.status_code == 200, response.text + + response = client.get("/query_examples/") + assert response.status_code == 200, response.text + + response = client.get("/header_examples/") + assert response.status_code == 200, response.text + + response = client.get("/cookie_examples/") + assert response.status_code == 200, response.text + + +def test_openapi_schema(): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/examples/": { + "post": { + "summary": "Examples", + "operationId": "examples_examples__post", + "requestBody": { + "content": { + "application/json": { + "schema": { + "allOf": [{"$ref": "#/components/schemas/Item"}], + "title": "Item", + "examples": [ + {"data": "Data in Body examples, example1"} + ], + }, + "examples": { + "Example One": { + "summary": "Example One Summary", + "description": "Example One Description", + "value": { + "data": "Data in Body examples, example1" + }, + }, + "Example Two": { + "value": { + "data": "Data in Body examples, example2" + } + }, + }, + } + }, + "required": True, + }, + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + }, + "/path_examples/{item_id}": { + "get": { + "summary": "Path Examples", + "operationId": "path_examples_path_examples__item_id__get", + "parameters": [ + { + "name": "item_id", + "in": "path", + "required": True, + "schema": { + "type": "string", + "examples": [ + "json_schema_item_1", + "json_schema_item_2", + ], + "title": "Item Id", + }, + "examples": { + "Path One": { + "summary": "Path One Summary", + "description": "Path One Description", + "value": "item_1", + }, + "Path Two": {"value": "item_2"}, + }, + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + }, + "/query_examples/": { + "get": { + "summary": "Query Examples", + "operationId": "query_examples_query_examples__get", + "parameters": [ + { + "name": "data", + "in": "query", + "required": False, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "examples": [ + "json_schema_query1", + "json_schema_query2", + ], + "title": "Data", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "examples": [ + "json_schema_query1", + "json_schema_query2", + ], + "type": "string", + "title": "Data", + } + ), + "examples": { + "Query One": { + "summary": "Query One Summary", + "description": "Query One Description", + "value": "query1", + }, + "Query Two": {"value": "query2"}, + }, + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + }, + "/header_examples/": { + "get": { + "summary": "Header Examples", + "operationId": "header_examples_header_examples__get", + "parameters": [ + { + "name": "data", + "in": "header", + "required": False, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "examples": [ + "json_schema_header1", + "json_schema_header2", + ], + "title": "Data", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "string", + "examples": [ + "json_schema_header1", + "json_schema_header2", + ], + "title": "Data", + } + ), + "examples": { + "Header One": { + "summary": "Header One Summary", + "description": "Header One Description", + "value": "header1", + }, + "Header Two": {"value": "header2"}, + }, + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + }, + "/cookie_examples/": { + "get": { + "summary": "Cookie Examples", + "operationId": "cookie_examples_cookie_examples__get", + "parameters": [ + { + "name": "data", + "in": "cookie", + "required": False, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "examples": [ + "json_schema_cookie1", + "json_schema_cookie2", + ], + "title": "Data", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "string", + "examples": [ + "json_schema_cookie1", + "json_schema_cookie2", + ], + "title": "Data", + } + ), + "examples": { + "Cookie One": { + "summary": "Cookie One Summary", + "description": "Cookie One Description", + "value": "cookie1", + }, + "Cookie Two": {"value": "cookie2"}, + }, + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + }, + }, + "components": { + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": {"$ref": "#/components/schemas/ValidationError"}, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "Item": { + "properties": {"data": {"type": "string", "title": "Data"}}, + "type": "object", + "required": ["data"], + "title": "Item", + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + } + }, + } diff --git a/tests/test_openapi_query_parameter_extension.py b/tests/test_openapi_query_parameter_extension.py index 8a9086ebe1dab..dc7147c712463 100644 --- a/tests/test_openapi_query_parameter_extension.py +++ b/tests/test_openapi_query_parameter_extension.py @@ -1,5 +1,6 @@ from typing import Optional +from dirty_equals import IsDict from fastapi import FastAPI from fastapi.testclient import TestClient @@ -42,7 +43,7 @@ def test_openapi(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/": { @@ -52,11 +53,21 @@ def test_openapi(): "parameters": [ { "required": False, - "schema": { - "title": "Standard Query Param", - "type": "integer", - "default": 50, - }, + "schema": IsDict( + { + "anyOf": [{"type": "integer"}, {"type": "null"}], + "default": 50, + "title": "Standard Query Param", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "Standard Query Param", + "type": "integer", + "default": 50, + } + ), "name": "standard_query_param", "in": "query", }, diff --git a/tests/test_openapi_route_extensions.py b/tests/test_openapi_route_extensions.py index 943dc43f2debd..3a3099436799c 100644 --- a/tests/test_openapi_route_extensions.py +++ b/tests/test_openapi_route_extensions.py @@ -22,7 +22,7 @@ def test_openapi(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/": { diff --git a/tests/test_openapi_separate_input_output_schemas.py b/tests/test_openapi_separate_input_output_schemas.py new file mode 100644 index 0000000000000..aeb85f735b666 --- /dev/null +++ b/tests/test_openapi_separate_input_output_schemas.py @@ -0,0 +1,494 @@ +from typing import List, Optional + +from fastapi import FastAPI +from fastapi.testclient import TestClient +from pydantic import BaseModel + +from .utils import PYDANTIC_V2, needs_pydanticv2 + + +class SubItem(BaseModel): + subname: str + sub_description: Optional[str] = None + tags: List[str] = [] + if PYDANTIC_V2: + model_config = {"json_schema_serialization_defaults_required": True} + + +class Item(BaseModel): + name: str + description: Optional[str] = None + sub: Optional[SubItem] = None + if PYDANTIC_V2: + model_config = {"json_schema_serialization_defaults_required": True} + + +def get_app_client(separate_input_output_schemas: bool = True) -> TestClient: + app = FastAPI(separate_input_output_schemas=separate_input_output_schemas) + + @app.post("/items/") + def create_item(item: Item): + return item + + @app.post("/items-list/") + def create_item_list(item: List[Item]): + return item + + @app.get("/items/") + def read_items() -> List[Item]: + return [ + Item( + name="Portal Gun", + description="Device to travel through the multi-rick-verse", + sub=SubItem(subname="subname"), + ), + Item(name="Plumbus"), + ] + + client = TestClient(app) + return client + + +def test_create_item(): + client = get_app_client() + client_no = get_app_client(separate_input_output_schemas=False) + response = client.post("/items/", json={"name": "Plumbus"}) + response2 = client_no.post("/items/", json={"name": "Plumbus"}) + assert response.status_code == response2.status_code == 200, response.text + assert ( + response.json() + == response2.json() + == {"name": "Plumbus", "description": None, "sub": None} + ) + + +def test_create_item_with_sub(): + client = get_app_client() + client_no = get_app_client(separate_input_output_schemas=False) + data = { + "name": "Plumbus", + "sub": {"subname": "SubPlumbus", "sub_description": "Sub WTF"}, + } + response = client.post("/items/", json=data) + response2 = client_no.post("/items/", json=data) + assert response.status_code == response2.status_code == 200, response.text + assert ( + response.json() + == response2.json() + == { + "name": "Plumbus", + "description": None, + "sub": {"subname": "SubPlumbus", "sub_description": "Sub WTF", "tags": []}, + } + ) + + +def test_create_item_list(): + client = get_app_client() + client_no = get_app_client(separate_input_output_schemas=False) + data = [ + {"name": "Plumbus"}, + { + "name": "Portal Gun", + "description": "Device to travel through the multi-rick-verse", + }, + ] + response = client.post("/items-list/", json=data) + response2 = client_no.post("/items-list/", json=data) + assert response.status_code == response2.status_code == 200, response.text + assert ( + response.json() + == response2.json() + == [ + {"name": "Plumbus", "description": None, "sub": None}, + { + "name": "Portal Gun", + "description": "Device to travel through the multi-rick-verse", + "sub": None, + }, + ] + ) + + +def test_read_items(): + client = get_app_client() + client_no = get_app_client(separate_input_output_schemas=False) + response = client.get("/items/") + response2 = client_no.get("/items/") + assert response.status_code == response2.status_code == 200, response.text + assert ( + response.json() + == response2.json() + == [ + { + "name": "Portal Gun", + "description": "Device to travel through the multi-rick-verse", + "sub": {"subname": "subname", "sub_description": None, "tags": []}, + }, + {"name": "Plumbus", "description": None, "sub": None}, + ] + ) + + +@needs_pydanticv2 +def test_openapi_schema(): + client = get_app_client() + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/items/": { + "get": { + "summary": "Read Items", + "operationId": "read_items_items__get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "items": { + "$ref": "#/components/schemas/Item-Output" + }, + "type": "array", + "title": "Response Read Items Items Get", + } + } + }, + } + }, + }, + "post": { + "summary": "Create Item", + "operationId": "create_item_items__post", + "requestBody": { + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Item-Input"} + } + }, + "required": True, + }, + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + }, + }, + "/items-list/": { + "post": { + "summary": "Create Item List", + "operationId": "create_item_list_items_list__post", + "requestBody": { + "content": { + "application/json": { + "schema": { + "items": { + "$ref": "#/components/schemas/Item-Input" + }, + "type": "array", + "title": "Item", + } + } + }, + "required": True, + }, + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + }, + }, + "components": { + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": {"$ref": "#/components/schemas/ValidationError"}, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "Item-Input": { + "properties": { + "name": {"type": "string", "title": "Name"}, + "description": { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Description", + }, + "sub": { + "anyOf": [ + {"$ref": "#/components/schemas/SubItem-Input"}, + {"type": "null"}, + ] + }, + }, + "type": "object", + "required": ["name"], + "title": "Item", + }, + "Item-Output": { + "properties": { + "name": {"type": "string", "title": "Name"}, + "description": { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Description", + }, + "sub": { + "anyOf": [ + {"$ref": "#/components/schemas/SubItem-Output"}, + {"type": "null"}, + ] + }, + }, + "type": "object", + "required": ["name", "description", "sub"], + "title": "Item", + }, + "SubItem-Input": { + "properties": { + "subname": {"type": "string", "title": "Subname"}, + "sub_description": { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Sub Description", + }, + "tags": { + "items": {"type": "string"}, + "type": "array", + "title": "Tags", + "default": [], + }, + }, + "type": "object", + "required": ["subname"], + "title": "SubItem", + }, + "SubItem-Output": { + "properties": { + "subname": {"type": "string", "title": "Subname"}, + "sub_description": { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Sub Description", + }, + "tags": { + "items": {"type": "string"}, + "type": "array", + "title": "Tags", + "default": [], + }, + }, + "type": "object", + "required": ["subname", "sub_description", "tags"], + "title": "SubItem", + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + } + }, + } + + +@needs_pydanticv2 +def test_openapi_schema_no_separate(): + client = get_app_client(separate_input_output_schemas=False) + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/items/": { + "get": { + "summary": "Read Items", + "operationId": "read_items_items__get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "items": {"$ref": "#/components/schemas/Item"}, + "type": "array", + "title": "Response Read Items Items Get", + } + } + }, + } + }, + }, + "post": { + "summary": "Create Item", + "operationId": "create_item_items__post", + "requestBody": { + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Item"} + } + }, + "required": True, + }, + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + }, + }, + "/items-list/": { + "post": { + "summary": "Create Item List", + "operationId": "create_item_list_items_list__post", + "requestBody": { + "content": { + "application/json": { + "schema": { + "items": {"$ref": "#/components/schemas/Item"}, + "type": "array", + "title": "Item", + } + } + }, + "required": True, + }, + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + }, + }, + "components": { + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": {"$ref": "#/components/schemas/ValidationError"}, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "Item": { + "properties": { + "name": {"type": "string", "title": "Name"}, + "description": { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Description", + }, + "sub": { + "anyOf": [ + {"$ref": "#/components/schemas/SubItem"}, + {"type": "null"}, + ] + }, + }, + "type": "object", + "required": ["name"], + "title": "Item", + }, + "SubItem": { + "properties": { + "subname": {"type": "string", "title": "Subname"}, + "sub_description": { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Sub Description", + }, + "tags": { + "items": {"type": "string"}, + "type": "array", + "title": "Tags", + "default": [], + }, + }, + "type": "object", + "required": ["subname"], + "title": "SubItem", + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + } + }, + } diff --git a/tests/test_openapi_servers.py b/tests/test_openapi_servers.py index 26abeaa12d68c..8697c8438b7c7 100644 --- a/tests/test_openapi_servers.py +++ b/tests/test_openapi_servers.py @@ -1,3 +1,4 @@ +from dirty_equals import IsOneOf from fastapi import FastAPI from fastapi.testclient import TestClient @@ -30,15 +31,25 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "servers": [ {"url": "/", "description": "Default, relative server"}, { - "url": "http://staging.localhost.tiangolo.com:8000", + "url": IsOneOf( + "http://staging.localhost.tiangolo.com:8000/", + # TODO: remove when deprecating Pydantic v1 + "http://staging.localhost.tiangolo.com:8000", + ), "description": "Staging but actually localhost still", }, - {"url": "https://prod.example.com"}, + { + "url": IsOneOf( + "https://prod.example.com/", + # TODO: remove when deprecating Pydantic v1 + "https://prod.example.com", + ) + }, ], "paths": { "/foo": { diff --git a/tests/test_param_in_path_and_dependency.py b/tests/test_param_in_path_and_dependency.py index 0aef7ac7bca04..08eb0f40f3d1f 100644 --- a/tests/test_param_in_path_and_dependency.py +++ b/tests/test_param_in_path_and_dependency.py @@ -25,7 +25,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") data = response.json() assert data == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/{user_id}": { diff --git a/tests/test_param_include_in_schema.py b/tests/test_param_include_in_schema.py index d0c29f7b2d2df..f461947c977a7 100644 --- a/tests/test_param_include_in_schema.py +++ b/tests/test_param_include_in_schema.py @@ -9,14 +9,14 @@ @app.get("/hidden_cookie") async def hidden_cookie( - hidden_cookie: Optional[str] = Cookie(default=None, include_in_schema=False) + hidden_cookie: Optional[str] = Cookie(default=None, include_in_schema=False), ): return {"hidden_cookie": hidden_cookie} @app.get("/hidden_header") async def hidden_header( - hidden_header: Optional[str] = Header(default=None, include_in_schema=False) + hidden_header: Optional[str] = Header(default=None, include_in_schema=False), ): return {"hidden_header": hidden_header} @@ -28,13 +28,13 @@ async def hidden_path(hidden_path: str = Path(include_in_schema=False)): @app.get("/hidden_query") async def hidden_query( - hidden_query: Optional[str] = Query(default=None, include_in_schema=False) + hidden_query: Optional[str] = Query(default=None, include_in_schema=False), ): return {"hidden_query": hidden_query} openapi_schema = { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/hidden_cookie": { diff --git a/tests/test_params_repr.py b/tests/test_params_repr.py index d8dca1ea42abd..bfc7bed0964ba 100644 --- a/tests/test_params_repr.py +++ b/tests/test_params_repr.py @@ -1,6 +1,6 @@ from typing import Any, List -import pytest +from dirty_equals import IsOneOf from fastapi.params import Body, Cookie, Depends, Header, Param, Path, Query test_data: List[Any] = ["teststr", None, ..., 1, []] @@ -10,34 +10,137 @@ def get_user(): return {} # pragma: no cover -@pytest.fixture(scope="function", params=test_data) -def params(request): - return request.param +def test_param_repr_str(): + assert repr(Param("teststr")) == "Param(teststr)" -def test_param_repr(params): - assert repr(Param(params)) == "Param(" + str(params) + ")" +def test_param_repr_none(): + assert repr(Param(None)) == "Param(None)" + + +def test_param_repr_ellipsis(): + assert repr(Param(...)) == IsOneOf( + "Param(PydanticUndefined)", + # TODO: remove when deprecating Pydantic v1 + "Param(Ellipsis)", + ) + + +def test_param_repr_number(): + assert repr(Param(1)) == "Param(1)" + + +def test_param_repr_list(): + assert repr(Param([])) == "Param([])" def test_path_repr(): - assert repr(Path()) == "Path(Ellipsis)" - assert repr(Path(...)) == "Path(Ellipsis)" + assert repr(Path()) == IsOneOf( + "Path(PydanticUndefined)", + # TODO: remove when deprecating Pydantic v1 + "Path(Ellipsis)", + ) + assert repr(Path(...)) == IsOneOf( + "Path(PydanticUndefined)", + # TODO: remove when deprecating Pydantic v1 + "Path(Ellipsis)", + ) -def test_query_repr(params): - assert repr(Query(params)) == "Query(" + str(params) + ")" +def test_query_repr_str(): + assert repr(Query("teststr")) == "Query(teststr)" -def test_header_repr(params): - assert repr(Header(params)) == "Header(" + str(params) + ")" +def test_query_repr_none(): + assert repr(Query(None)) == "Query(None)" + + +def test_query_repr_ellipsis(): + assert repr(Query(...)) == IsOneOf( + "Query(PydanticUndefined)", + # TODO: remove when deprecating Pydantic v1 + "Query(Ellipsis)", + ) + + +def test_query_repr_number(): + assert repr(Query(1)) == "Query(1)" + + +def test_query_repr_list(): + assert repr(Query([])) == "Query([])" + + +def test_header_repr_str(): + assert repr(Header("teststr")) == "Header(teststr)" + + +def test_header_repr_none(): + assert repr(Header(None)) == "Header(None)" + + +def test_header_repr_ellipsis(): + assert repr(Header(...)) == IsOneOf( + "Header(PydanticUndefined)", + # TODO: remove when deprecating Pydantic v1 + "Header(Ellipsis)", + ) + + +def test_header_repr_number(): + assert repr(Header(1)) == "Header(1)" + + +def test_header_repr_list(): + assert repr(Header([])) == "Header([])" + + +def test_cookie_repr_str(): + assert repr(Cookie("teststr")) == "Cookie(teststr)" + + +def test_cookie_repr_none(): + assert repr(Cookie(None)) == "Cookie(None)" + + +def test_cookie_repr_ellipsis(): + assert repr(Cookie(...)) == IsOneOf( + "Cookie(PydanticUndefined)", + # TODO: remove when deprecating Pydantic v1 + "Cookie(Ellipsis)", + ) + + +def test_cookie_repr_number(): + assert repr(Cookie(1)) == "Cookie(1)" + + +def test_cookie_repr_list(): + assert repr(Cookie([])) == "Cookie([])" + + +def test_body_repr_str(): + assert repr(Body("teststr")) == "Body(teststr)" + + +def test_body_repr_none(): + assert repr(Body(None)) == "Body(None)" + + +def test_body_repr_ellipsis(): + assert repr(Body(...)) == IsOneOf( + "Body(PydanticUndefined)", + # TODO: remove when deprecating Pydantic v1 + "Body(Ellipsis)", + ) -def test_cookie_repr(params): - assert repr(Cookie(params)) == "Cookie(" + str(params) + ")" +def test_body_repr_number(): + assert repr(Body(1)) == "Body(1)" -def test_body_repr(params): - assert repr(Body(params)) == "Body(" + str(params) + ")" +def test_body_repr_list(): + assert repr(Body([])) == "Body([])" def test_depends_repr(): diff --git a/tests/test_path.py b/tests/test_path.py index 03b93623a97e9..848b245e2c4d4 100644 --- a/tests/test_path.py +++ b/tests/test_path.py @@ -1,5 +1,6 @@ -import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url from .main import app @@ -18,235 +19,1259 @@ def test_nonexistent(): assert response.json() == {"detail": "Not Found"} -response_not_valid_bool = { - "detail": [ +def test_path_foobar(): + response = client.get("/path/foobar") + assert response.status_code == 200 + assert response.json() == "foobar" + + +def test_path_str_foobar(): + response = client.get("/path/str/foobar") + assert response.status_code == 200 + assert response.json() == "foobar" + + +def test_path_str_42(): + response = client.get("/path/str/42") + assert response.status_code == 200 + assert response.json() == "42" + + +def test_path_str_True(): + response = client.get("/path/str/True") + assert response.status_code == 200 + assert response.json() == "True" + + +def test_path_int_foobar(): + response = client.get("/path/int/foobar") + assert response.status_code == 422 + assert response.json() == IsDict( { - "loc": ["path", "item_id"], - "msg": "value could not be parsed to a boolean", - "type": "type_error.bool", + "detail": [ + { + "type": "int_parsing", + "loc": ["path", "item_id"], + "msg": "Input should be a valid integer, unable to parse string as an integer", + "input": "foobar", + "url": match_pydantic_error_url("int_parsing"), + } + ] } - ] -} + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["path", "item_id"], + "msg": "value is not a valid integer", + "type": "type_error.integer", + } + ] + } + ) -response_not_valid_int = { - "detail": [ + +def test_path_int_True(): + response = client.get("/path/int/True") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "int_parsing", + "loc": ["path", "item_id"], + "msg": "Input should be a valid integer, unable to parse string as an integer", + "input": "True", + "url": match_pydantic_error_url("int_parsing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 { - "loc": ["path", "item_id"], - "msg": "value is not a valid integer", - "type": "type_error.integer", + "detail": [ + { + "loc": ["path", "item_id"], + "msg": "value is not a valid integer", + "type": "type_error.integer", + } + ] } - ] -} + ) + + +def test_path_int_42(): + response = client.get("/path/int/42") + assert response.status_code == 200 + assert response.json() == 42 + -response_not_valid_float = { - "detail": [ +def test_path_int_42_5(): + response = client.get("/path/int/42.5") + assert response.status_code == 422 + assert response.json() == IsDict( { - "loc": ["path", "item_id"], - "msg": "value is not a valid float", - "type": "type_error.float", + "detail": [ + { + "type": "int_parsing", + "loc": ["path", "item_id"], + "msg": "Input should be a valid integer, unable to parse string as an integer", + "input": "42.5", + "url": match_pydantic_error_url("int_parsing"), + } + ] } - ] -} + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["path", "item_id"], + "msg": "value is not a valid integer", + "type": "type_error.integer", + } + ] + } + ) -response_at_least_3 = { - "detail": [ + +def test_path_float_foobar(): + response = client.get("/path/float/foobar") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "float_parsing", + "loc": ["path", "item_id"], + "msg": "Input should be a valid number, unable to parse string as a number", + "input": "foobar", + "url": match_pydantic_error_url("float_parsing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 { - "loc": ["path", "item_id"], - "msg": "ensure this value has at least 3 characters", - "type": "value_error.any_str.min_length", - "ctx": {"limit_value": 3}, + "detail": [ + { + "loc": ["path", "item_id"], + "msg": "value is not a valid float", + "type": "type_error.float", + } + ] } - ] -} + ) -response_at_least_2 = { - "detail": [ +def test_path_float_True(): + response = client.get("/path/float/True") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "float_parsing", + "loc": ["path", "item_id"], + "msg": "Input should be a valid number, unable to parse string as a number", + "input": "True", + "url": match_pydantic_error_url("float_parsing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 { - "loc": ["path", "item_id"], - "msg": "ensure this value has at least 2 characters", - "type": "value_error.any_str.min_length", - "ctx": {"limit_value": 2}, + "detail": [ + { + "loc": ["path", "item_id"], + "msg": "value is not a valid float", + "type": "type_error.float", + } + ] } - ] -} + ) + +def test_path_float_42(): + response = client.get("/path/float/42") + assert response.status_code == 200 + assert response.json() == 42 -response_maximum_3 = { - "detail": [ + +def test_path_float_42_5(): + response = client.get("/path/float/42.5") + assert response.status_code == 200 + assert response.json() == 42.5 + + +def test_path_bool_foobar(): + response = client.get("/path/bool/foobar") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "bool_parsing", + "loc": ["path", "item_id"], + "msg": "Input should be a valid boolean, unable to interpret input", + "input": "foobar", + "url": match_pydantic_error_url("bool_parsing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 { - "loc": ["path", "item_id"], - "msg": "ensure this value has at most 3 characters", - "type": "value_error.any_str.max_length", - "ctx": {"limit_value": 3}, + "detail": [ + { + "loc": ["path", "item_id"], + "msg": "value could not be parsed to a boolean", + "type": "type_error.bool", + } + ] } - ] -} + ) + +def test_path_bool_True(): + response = client.get("/path/bool/True") + assert response.status_code == 200 + assert response.json() is True -response_greater_than_3 = { - "detail": [ + +def test_path_bool_42(): + response = client.get("/path/bool/42") + assert response.status_code == 422 + assert response.json() == IsDict( { - "loc": ["path", "item_id"], - "msg": "ensure this value is greater than 3", - "type": "value_error.number.not_gt", - "ctx": {"limit_value": 3}, + "detail": [ + { + "type": "bool_parsing", + "loc": ["path", "item_id"], + "msg": "Input should be a valid boolean, unable to interpret input", + "input": "42", + "url": match_pydantic_error_url("bool_parsing"), + } + ] } - ] -} + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["path", "item_id"], + "msg": "value could not be parsed to a boolean", + "type": "type_error.bool", + } + ] + } + ) + + +def test_path_bool_42_5(): + response = client.get("/path/bool/42.5") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "bool_parsing", + "loc": ["path", "item_id"], + "msg": "Input should be a valid boolean, unable to interpret input", + "input": "42.5", + "url": match_pydantic_error_url("bool_parsing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["path", "item_id"], + "msg": "value could not be parsed to a boolean", + "type": "type_error.bool", + } + ] + } + ) + + +def test_path_bool_1(): + response = client.get("/path/bool/1") + assert response.status_code == 200 + assert response.json() is True + + +def test_path_bool_0(): + response = client.get("/path/bool/0") + assert response.status_code == 200 + assert response.json() is False + + +def test_path_bool_true(): + response = client.get("/path/bool/true") + assert response.status_code == 200 + assert response.json() is True + + +def test_path_bool_False(): + response = client.get("/path/bool/False") + assert response.status_code == 200 + assert response.json() is False + +def test_path_bool_false(): + response = client.get("/path/bool/false") + assert response.status_code == 200 + assert response.json() is False -response_greater_than_0 = { - "detail": [ + +def test_path_param_foo(): + response = client.get("/path/param/foo") + assert response.status_code == 200 + assert response.json() == "foo" + + +def test_path_param_minlength_foo(): + response = client.get("/path/param-minlength/foo") + assert response.status_code == 200 + assert response.json() == "foo" + + +def test_path_param_minlength_fo(): + response = client.get("/path/param-minlength/fo") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "string_too_short", + "loc": ["path", "item_id"], + "msg": "String should have at least 3 characters", + "input": "fo", + "ctx": {"min_length": 3}, + "url": match_pydantic_error_url("string_too_short"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["path", "item_id"], + "msg": "ensure this value has at least 3 characters", + "type": "value_error.any_str.min_length", + "ctx": {"limit_value": 3}, + } + ] + } + ) + + +def test_path_param_maxlength_foo(): + response = client.get("/path/param-maxlength/foo") + assert response.status_code == 200 + assert response.json() == "foo" + + +def test_path_param_maxlength_foobar(): + response = client.get("/path/param-maxlength/foobar") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "string_too_long", + "loc": ["path", "item_id"], + "msg": "String should have at most 3 characters", + "input": "foobar", + "ctx": {"max_length": 3}, + "url": match_pydantic_error_url("string_too_long"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["path", "item_id"], + "msg": "ensure this value has at most 3 characters", + "type": "value_error.any_str.max_length", + "ctx": {"limit_value": 3}, + } + ] + } + ) + + +def test_path_param_min_maxlength_foo(): + response = client.get("/path/param-min_maxlength/foo") + assert response.status_code == 200 + assert response.json() == "foo" + + +def test_path_param_min_maxlength_foobar(): + response = client.get("/path/param-min_maxlength/foobar") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "string_too_long", + "loc": ["path", "item_id"], + "msg": "String should have at most 3 characters", + "input": "foobar", + "ctx": {"max_length": 3}, + "url": match_pydantic_error_url("string_too_long"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["path", "item_id"], + "msg": "ensure this value has at most 3 characters", + "type": "value_error.any_str.max_length", + "ctx": {"limit_value": 3}, + } + ] + } + ) + + +def test_path_param_min_maxlength_f(): + response = client.get("/path/param-min_maxlength/f") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "string_too_short", + "loc": ["path", "item_id"], + "msg": "String should have at least 2 characters", + "input": "f", + "ctx": {"min_length": 2}, + "url": match_pydantic_error_url("string_too_short"), + } + ] + } + ) | IsDict( + { + "detail": [ + { + "loc": ["path", "item_id"], + "msg": "ensure this value has at least 2 characters", + "type": "value_error.any_str.min_length", + "ctx": {"limit_value": 2}, + } + ] + } + ) + + +def test_path_param_gt_42(): + response = client.get("/path/param-gt/42") + assert response.status_code == 200 + assert response.json() == 42 + + +def test_path_param_gt_2(): + response = client.get("/path/param-gt/2") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "greater_than", + "loc": ["path", "item_id"], + "msg": "Input should be greater than 3", + "input": "2", + "ctx": {"gt": 3.0}, + "url": match_pydantic_error_url("greater_than"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["path", "item_id"], + "msg": "ensure this value is greater than 3", + "type": "value_error.number.not_gt", + "ctx": {"limit_value": 3}, + } + ] + } + ) + + +def test_path_param_gt0_0_05(): + response = client.get("/path/param-gt0/0.05") + assert response.status_code == 200 + assert response.json() == 0.05 + + +def test_path_param_gt0_0(): + response = client.get("/path/param-gt0/0") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "greater_than", + "loc": ["path", "item_id"], + "msg": "Input should be greater than 0", + "input": "0", + "ctx": {"gt": 0.0}, + "url": match_pydantic_error_url("greater_than"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["path", "item_id"], + "msg": "ensure this value is greater than 0", + "type": "value_error.number.not_gt", + "ctx": {"limit_value": 0}, + } + ] + } + ) + + +def test_path_param_ge_42(): + response = client.get("/path/param-ge/42") + assert response.status_code == 200 + assert response.json() == 42 + + +def test_path_param_ge_3(): + response = client.get("/path/param-ge/3") + assert response.status_code == 200 + assert response.json() == 3 + + +def test_path_param_ge_2(): + response = client.get("/path/param-ge/2") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "greater_than_equal", + "loc": ["path", "item_id"], + "msg": "Input should be greater than or equal to 3", + "input": "2", + "ctx": {"ge": 3.0}, + "url": match_pydantic_error_url("greater_than_equal"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["path", "item_id"], + "msg": "ensure this value is greater than or equal to 3", + "type": "value_error.number.not_ge", + "ctx": {"limit_value": 3}, + } + ] + } + ) + + +def test_path_param_lt_42(): + response = client.get("/path/param-lt/42") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "less_than", + "loc": ["path", "item_id"], + "msg": "Input should be less than 3", + "input": "42", + "ctx": {"lt": 3.0}, + "url": match_pydantic_error_url("less_than"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["path", "item_id"], + "msg": "ensure this value is less than 3", + "type": "value_error.number.not_lt", + "ctx": {"limit_value": 3}, + } + ] + } + ) + + +def test_path_param_lt_2(): + response = client.get("/path/param-lt/2") + assert response.status_code == 200 + assert response.json() == 2 + + +def test_path_param_lt0__1(): + response = client.get("/path/param-lt0/-1") + assert response.status_code == 200 + assert response.json() == -1 + + +def test_path_param_lt0_0(): + response = client.get("/path/param-lt0/0") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "less_than", + "loc": ["path", "item_id"], + "msg": "Input should be less than 0", + "input": "0", + "ctx": {"lt": 0.0}, + "url": match_pydantic_error_url("less_than"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["path", "item_id"], + "msg": "ensure this value is less than 0", + "type": "value_error.number.not_lt", + "ctx": {"limit_value": 0}, + } + ] + } + ) + + +def test_path_param_le_42(): + response = client.get("/path/param-le/42") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "less_than_equal", + "loc": ["path", "item_id"], + "msg": "Input should be less than or equal to 3", + "input": "42", + "ctx": {"le": 3.0}, + "url": match_pydantic_error_url("less_than_equal"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 { - "loc": ["path", "item_id"], - "msg": "ensure this value is greater than 0", - "type": "value_error.number.not_gt", - "ctx": {"limit_value": 0}, + "detail": [ + { + "loc": ["path", "item_id"], + "msg": "ensure this value is less than or equal to 3", + "type": "value_error.number.not_le", + "ctx": {"limit_value": 3}, + } + ] } - ] -} + ) -response_greater_than_1 = { - "detail": [ +def test_path_param_le_3(): + response = client.get("/path/param-le/3") + assert response.status_code == 200 + assert response.json() == 3 + + +def test_path_param_le_2(): + response = client.get("/path/param-le/2") + assert response.status_code == 200 + assert response.json() == 2 + + +def test_path_param_lt_gt_2(): + response = client.get("/path/param-lt-gt/2") + assert response.status_code == 200 + assert response.json() == 2 + + +def test_path_param_lt_gt_4(): + response = client.get("/path/param-lt-gt/4") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "less_than", + "loc": ["path", "item_id"], + "msg": "Input should be less than 3", + "input": "4", + "ctx": {"lt": 3.0}, + "url": match_pydantic_error_url("less_than"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["path", "item_id"], + "msg": "ensure this value is less than 3", + "type": "value_error.number.not_lt", + "ctx": {"limit_value": 3}, + } + ] + } + ) + + +def test_path_param_lt_gt_0(): + response = client.get("/path/param-lt-gt/0") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "greater_than", + "loc": ["path", "item_id"], + "msg": "Input should be greater than 1", + "input": "0", + "ctx": {"gt": 1.0}, + "url": match_pydantic_error_url("greater_than"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["path", "item_id"], + "msg": "ensure this value is greater than 1", + "type": "value_error.number.not_gt", + "ctx": {"limit_value": 1}, + } + ] + } + ) + + +def test_path_param_le_ge_2(): + response = client.get("/path/param-le-ge/2") + assert response.status_code == 200 + assert response.json() == 2 + + +def test_path_param_le_ge_1(): + response = client.get("/path/param-le-ge/1") + assert response.status_code == 200 + + +def test_path_param_le_ge_3(): + response = client.get("/path/param-le-ge/3") + assert response.status_code == 200 + assert response.json() == 3 + + +def test_path_param_le_ge_4(): + response = client.get("/path/param-le-ge/4") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "less_than_equal", + "loc": ["path", "item_id"], + "msg": "Input should be less than or equal to 3", + "input": "4", + "ctx": {"le": 3.0}, + "url": match_pydantic_error_url("less_than_equal"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["path", "item_id"], + "msg": "ensure this value is less than or equal to 3", + "type": "value_error.number.not_le", + "ctx": {"limit_value": 3}, + } + ] + } + ) + + +def test_path_param_lt_int_2(): + response = client.get("/path/param-lt-int/2") + assert response.status_code == 200 + assert response.json() == 2 + + +def test_path_param_lt_int_42(): + response = client.get("/path/param-lt-int/42") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "less_than", + "loc": ["path", "item_id"], + "msg": "Input should be less than 3", + "input": "42", + "ctx": {"lt": 3}, + "url": match_pydantic_error_url("less_than"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["path", "item_id"], + "msg": "ensure this value is less than 3", + "type": "value_error.number.not_lt", + "ctx": {"limit_value": 3}, + } + ] + } + ) + + +def test_path_param_lt_int_2_7(): + response = client.get("/path/param-lt-int/2.7") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "int_parsing", + "loc": ["path", "item_id"], + "msg": "Input should be a valid integer, unable to parse string as an integer", + "input": "2.7", + "url": match_pydantic_error_url("int_parsing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["path", "item_id"], + "msg": "value is not a valid integer", + "type": "type_error.integer", + } + ] + } + ) + + +def test_path_param_gt_int_42(): + response = client.get("/path/param-gt-int/42") + assert response.status_code == 200 + assert response.json() == 42 + + +def test_path_param_gt_int_2(): + response = client.get("/path/param-gt-int/2") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "greater_than", + "loc": ["path", "item_id"], + "msg": "Input should be greater than 3", + "input": "2", + "ctx": {"gt": 3}, + "url": match_pydantic_error_url("greater_than"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["path", "item_id"], + "msg": "ensure this value is greater than 3", + "type": "value_error.number.not_gt", + "ctx": {"limit_value": 3}, + } + ] + } + ) + + +def test_path_param_gt_int_2_7(): + response = client.get("/path/param-gt-int/2.7") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "int_parsing", + "loc": ["path", "item_id"], + "msg": "Input should be a valid integer, unable to parse string as an integer", + "input": "2.7", + "url": match_pydantic_error_url("int_parsing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["path", "item_id"], + "msg": "value is not a valid integer", + "type": "type_error.integer", + } + ] + } + ) + + +def test_path_param_le_int_42(): + response = client.get("/path/param-le-int/42") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "less_than_equal", + "loc": ["path", "item_id"], + "msg": "Input should be less than or equal to 3", + "input": "42", + "ctx": {"le": 3}, + "url": match_pydantic_error_url("less_than_equal"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["path", "item_id"], + "msg": "ensure this value is less than or equal to 3", + "type": "value_error.number.not_le", + "ctx": {"limit_value": 3}, + } + ] + } + ) + + +def test_path_param_le_int_3(): + response = client.get("/path/param-le-int/3") + assert response.status_code == 200 + assert response.json() == 3 + + +def test_path_param_le_int_2(): + response = client.get("/path/param-le-int/2") + assert response.status_code == 200 + assert response.json() == 2 + + +def test_path_param_le_int_2_7(): + response = client.get("/path/param-le-int/2.7") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "int_parsing", + "loc": ["path", "item_id"], + "msg": "Input should be a valid integer, unable to parse string as an integer", + "input": "2.7", + "url": match_pydantic_error_url("int_parsing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["path", "item_id"], + "msg": "value is not a valid integer", + "type": "type_error.integer", + } + ] + } + ) + + +def test_path_param_ge_int_42(): + response = client.get("/path/param-ge-int/42") + assert response.status_code == 200 + assert response.json() == 42 + + +def test_path_param_ge_int_3(): + response = client.get("/path/param-ge-int/3") + assert response.status_code == 200 + assert response.json() == 3 + + +def test_path_param_ge_int_2(): + response = client.get("/path/param-ge-int/2") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "greater_than_equal", + "loc": ["path", "item_id"], + "msg": "Input should be greater than or equal to 3", + "input": "2", + "ctx": {"ge": 3}, + "url": match_pydantic_error_url("greater_than_equal"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["path", "item_id"], + "msg": "ensure this value is greater than or equal to 3", + "type": "value_error.number.not_ge", + "ctx": {"limit_value": 3}, + } + ] + } + ) + + +def test_path_param_ge_int_2_7(): + response = client.get("/path/param-ge-int/2.7") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "int_parsing", + "loc": ["path", "item_id"], + "msg": "Input should be a valid integer, unable to parse string as an integer", + "input": "2.7", + "url": match_pydantic_error_url("int_parsing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["path", "item_id"], + "msg": "value is not a valid integer", + "type": "type_error.integer", + } + ] + } + ) + + +def test_path_param_lt_gt_int_2(): + response = client.get("/path/param-lt-gt-int/2") + assert response.status_code == 200 + assert response.json() == 2 + + +def test_path_param_lt_gt_int_4(): + response = client.get("/path/param-lt-gt-int/4") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "less_than", + "loc": ["path", "item_id"], + "msg": "Input should be less than 3", + "input": "4", + "ctx": {"lt": 3}, + "url": match_pydantic_error_url("less_than"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["path", "item_id"], + "msg": "ensure this value is less than 3", + "type": "value_error.number.not_lt", + "ctx": {"limit_value": 3}, + } + ] + } + ) + + +def test_path_param_lt_gt_int_0(): + response = client.get("/path/param-lt-gt-int/0") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "greater_than", + "loc": ["path", "item_id"], + "msg": "Input should be greater than 1", + "input": "0", + "ctx": {"gt": 1}, + "url": match_pydantic_error_url("greater_than"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["path", "item_id"], + "msg": "ensure this value is greater than 1", + "type": "value_error.number.not_gt", + "ctx": {"limit_value": 1}, + } + ] + } + ) + + +def test_path_param_lt_gt_int_2_7(): + response = client.get("/path/param-lt-gt-int/2.7") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "int_parsing", + "loc": ["path", "item_id"], + "msg": "Input should be a valid integer, unable to parse string as an integer", + "input": "2.7", + "url": match_pydantic_error_url("int_parsing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["path", "item_id"], + "msg": "value is not a valid integer", + "type": "type_error.integer", + } + ] + } + ) + + +def test_path_param_le_ge_int_2(): + response = client.get("/path/param-le-ge-int/2") + assert response.status_code == 200 + assert response.json() == 2 + + +def test_path_param_le_ge_int_1(): + response = client.get("/path/param-le-ge-int/1") + assert response.status_code == 200 + assert response.json() == 1 + + +def test_path_param_le_ge_int_3(): + response = client.get("/path/param-le-ge-int/3") + assert response.status_code == 200 + assert response.json() == 3 + + +def test_path_param_le_ge_int_4(): + response = client.get("/path/param-le-ge-int/4") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "less_than_equal", + "loc": ["path", "item_id"], + "msg": "Input should be less than or equal to 3", + "input": "4", + "ctx": {"le": 3}, + "url": match_pydantic_error_url("less_than_equal"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["path", "item_id"], + "msg": "ensure this value is less than or equal to 3", + "type": "value_error.number.not_le", + "ctx": {"limit_value": 3}, + } + ] + } + ) + + +def test_path_param_le_ge_int_2_7(): + response = client.get("/path/param-le-ge-int/2.7") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "int_parsing", + "loc": ["path", "item_id"], + "msg": "Input should be a valid integer, unable to parse string as an integer", + "input": "2.7", + "url": match_pydantic_error_url("int_parsing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 { - "loc": ["path", "item_id"], - "msg": "ensure this value is greater than 1", - "type": "value_error.number.not_gt", - "ctx": {"limit_value": 1}, + "detail": [ + { + "loc": ["path", "item_id"], + "msg": "value is not a valid integer", + "type": "type_error.integer", + } + ] } - ] -} - - -response_greater_than_equal_3 = { - "detail": [ - { - "loc": ["path", "item_id"], - "msg": "ensure this value is greater than or equal to 3", - "type": "value_error.number.not_ge", - "ctx": {"limit_value": 3}, - } - ] -} - - -response_less_than_3 = { - "detail": [ - { - "loc": ["path", "item_id"], - "msg": "ensure this value is less than 3", - "type": "value_error.number.not_lt", - "ctx": {"limit_value": 3}, - } - ] -} - - -response_less_than_0 = { - "detail": [ - { - "loc": ["path", "item_id"], - "msg": "ensure this value is less than 0", - "type": "value_error.number.not_lt", - "ctx": {"limit_value": 0}, - } - ] -} - - -response_less_than_equal_3 = { - "detail": [ - { - "loc": ["path", "item_id"], - "msg": "ensure this value is less than or equal to 3", - "type": "value_error.number.not_le", - "ctx": {"limit_value": 3}, - } - ] -} - - -@pytest.mark.parametrize( - "path,expected_status,expected_response", - [ - ("/path/foobar", 200, "foobar"), - ("/path/str/foobar", 200, "foobar"), - ("/path/str/42", 200, "42"), - ("/path/str/True", 200, "True"), - ("/path/int/foobar", 422, response_not_valid_int), - ("/path/int/True", 422, response_not_valid_int), - ("/path/int/42", 200, 42), - ("/path/int/42.5", 422, response_not_valid_int), - ("/path/float/foobar", 422, response_not_valid_float), - ("/path/float/True", 422, response_not_valid_float), - ("/path/float/42", 200, 42), - ("/path/float/42.5", 200, 42.5), - ("/path/bool/foobar", 422, response_not_valid_bool), - ("/path/bool/True", 200, True), - ("/path/bool/42", 422, response_not_valid_bool), - ("/path/bool/42.5", 422, response_not_valid_bool), - ("/path/bool/1", 200, True), - ("/path/bool/0", 200, False), - ("/path/bool/true", 200, True), - ("/path/bool/False", 200, False), - ("/path/bool/false", 200, False), - ("/path/param/foo", 200, "foo"), - ("/path/param-minlength/foo", 200, "foo"), - ("/path/param-minlength/fo", 422, response_at_least_3), - ("/path/param-maxlength/foo", 200, "foo"), - ("/path/param-maxlength/foobar", 422, response_maximum_3), - ("/path/param-min_maxlength/foo", 200, "foo"), - ("/path/param-min_maxlength/foobar", 422, response_maximum_3), - ("/path/param-min_maxlength/f", 422, response_at_least_2), - ("/path/param-gt/42", 200, 42), - ("/path/param-gt/2", 422, response_greater_than_3), - ("/path/param-gt0/0.05", 200, 0.05), - ("/path/param-gt0/0", 422, response_greater_than_0), - ("/path/param-ge/42", 200, 42), - ("/path/param-ge/3", 200, 3), - ("/path/param-ge/2", 422, response_greater_than_equal_3), - ("/path/param-lt/42", 422, response_less_than_3), - ("/path/param-lt/2", 200, 2), - ("/path/param-lt0/-1", 200, -1), - ("/path/param-lt0/0", 422, response_less_than_0), - ("/path/param-le/42", 422, response_less_than_equal_3), - ("/path/param-le/3", 200, 3), - ("/path/param-le/2", 200, 2), - ("/path/param-lt-gt/2", 200, 2), - ("/path/param-lt-gt/4", 422, response_less_than_3), - ("/path/param-lt-gt/0", 422, response_greater_than_1), - ("/path/param-le-ge/2", 200, 2), - ("/path/param-le-ge/1", 200, 1), - ("/path/param-le-ge/3", 200, 3), - ("/path/param-le-ge/4", 422, response_less_than_equal_3), - ("/path/param-lt-int/2", 200, 2), - ("/path/param-lt-int/42", 422, response_less_than_3), - ("/path/param-lt-int/2.7", 422, response_not_valid_int), - ("/path/param-gt-int/42", 200, 42), - ("/path/param-gt-int/2", 422, response_greater_than_3), - ("/path/param-gt-int/2.7", 422, response_not_valid_int), - ("/path/param-le-int/42", 422, response_less_than_equal_3), - ("/path/param-le-int/3", 200, 3), - ("/path/param-le-int/2", 200, 2), - ("/path/param-le-int/2.7", 422, response_not_valid_int), - ("/path/param-ge-int/42", 200, 42), - ("/path/param-ge-int/3", 200, 3), - ("/path/param-ge-int/2", 422, response_greater_than_equal_3), - ("/path/param-ge-int/2.7", 422, response_not_valid_int), - ("/path/param-lt-gt-int/2", 200, 2), - ("/path/param-lt-gt-int/4", 422, response_less_than_3), - ("/path/param-lt-gt-int/0", 422, response_greater_than_1), - ("/path/param-lt-gt-int/2.7", 422, response_not_valid_int), - ("/path/param-le-ge-int/2", 200, 2), - ("/path/param-le-ge-int/1", 200, 1), - ("/path/param-le-ge-int/3", 200, 3), - ("/path/param-le-ge-int/4", 422, response_less_than_equal_3), - ("/path/param-le-ge-int/2.7", 422, response_not_valid_int), - ], -) -def test_get_path(path, expected_status, expected_response): - response = client.get(path) - assert response.status_code == expected_status - assert response.json() == expected_response + ) diff --git a/tests/test_put_no_body.py b/tests/test_put_no_body.py index a02d1152c82a6..8f4c82532c2d2 100644 --- a/tests/test_put_no_body.py +++ b/tests/test_put_no_body.py @@ -28,7 +28,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { diff --git a/tests/test_query.py b/tests/test_query.py index 0c73eb665eda7..5bb9995d6c5ad 100644 --- a/tests/test_query.py +++ b/tests/test_query.py @@ -1,62 +1,410 @@ -import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url from .main import app client = TestClient(app) -response_missing = { - "detail": [ - { - "loc": ["query", "query"], - "msg": "field required", - "type": "value_error.missing", - } - ] -} - -response_not_valid_int = { - "detail": [ - { - "loc": ["query", "query"], - "msg": "value is not a valid integer", - "type": "type_error.integer", - } - ] -} - - -@pytest.mark.parametrize( - "path,expected_status,expected_response", - [ - ("/query", 422, response_missing), - ("/query?query=baz", 200, "foo bar baz"), - ("/query?not_declared=baz", 422, response_missing), - ("/query/optional", 200, "foo bar"), - ("/query/optional?query=baz", 200, "foo bar baz"), - ("/query/optional?not_declared=baz", 200, "foo bar"), - ("/query/int", 422, response_missing), - ("/query/int?query=42", 200, "foo bar 42"), - ("/query/int?query=42.5", 422, response_not_valid_int), - ("/query/int?query=baz", 422, response_not_valid_int), - ("/query/int?not_declared=baz", 422, response_missing), - ("/query/int/optional", 200, "foo bar"), - ("/query/int/optional?query=50", 200, "foo bar 50"), - ("/query/int/optional?query=foo", 422, response_not_valid_int), - ("/query/int/default", 200, "foo bar 10"), - ("/query/int/default?query=50", 200, "foo bar 50"), - ("/query/int/default?query=foo", 422, response_not_valid_int), - ("/query/param", 200, "foo bar"), - ("/query/param?query=50", 200, "foo bar 50"), - ("/query/param-required", 422, response_missing), - ("/query/param-required?query=50", 200, "foo bar 50"), - ("/query/param-required/int", 422, response_missing), - ("/query/param-required/int?query=50", 200, "foo bar 50"), - ("/query/param-required/int?query=foo", 422, response_not_valid_int), - ("/query/frozenset/?query=1&query=1&query=2", 200, "1,2"), - ], -) -def test_get_path(path, expected_status, expected_response): - response = client.get(path) - assert response.status_code == expected_status - assert response.json() == expected_response + +def test_query(): + response = client.get("/query") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["query", "query"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["query", "query"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) + + +def test_query_query_baz(): + response = client.get("/query?query=baz") + assert response.status_code == 200 + assert response.json() == "foo bar baz" + + +def test_query_not_declared_baz(): + response = client.get("/query?not_declared=baz") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["query", "query"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["query", "query"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) + + +def test_query_optional(): + response = client.get("/query/optional") + assert response.status_code == 200 + assert response.json() == "foo bar" + + +def test_query_optional_query_baz(): + response = client.get("/query/optional?query=baz") + assert response.status_code == 200 + assert response.json() == "foo bar baz" + + +def test_query_optional_not_declared_baz(): + response = client.get("/query/optional?not_declared=baz") + assert response.status_code == 200 + assert response.json() == "foo bar" + + +def test_query_int(): + response = client.get("/query/int") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["query", "query"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["query", "query"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) + + +def test_query_int_query_42(): + response = client.get("/query/int?query=42") + assert response.status_code == 200 + assert response.json() == "foo bar 42" + + +def test_query_int_query_42_5(): + response = client.get("/query/int?query=42.5") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "int_parsing", + "loc": ["query", "query"], + "msg": "Input should be a valid integer, unable to parse string as an integer", + "input": "42.5", + "url": match_pydantic_error_url("int_parsing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["query", "query"], + "msg": "value is not a valid integer", + "type": "type_error.integer", + } + ] + } + ) + + +def test_query_int_query_baz(): + response = client.get("/query/int?query=baz") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "int_parsing", + "loc": ["query", "query"], + "msg": "Input should be a valid integer, unable to parse string as an integer", + "input": "baz", + "url": match_pydantic_error_url("int_parsing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["query", "query"], + "msg": "value is not a valid integer", + "type": "type_error.integer", + } + ] + } + ) + + +def test_query_int_not_declared_baz(): + response = client.get("/query/int?not_declared=baz") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["query", "query"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["query", "query"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) + + +def test_query_int_optional(): + response = client.get("/query/int/optional") + assert response.status_code == 200 + assert response.json() == "foo bar" + + +def test_query_int_optional_query_50(): + response = client.get("/query/int/optional?query=50") + assert response.status_code == 200 + assert response.json() == "foo bar 50" + + +def test_query_int_optional_query_foo(): + response = client.get("/query/int/optional?query=foo") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "int_parsing", + "loc": ["query", "query"], + "msg": "Input should be a valid integer, unable to parse string as an integer", + "input": "foo", + "url": match_pydantic_error_url("int_parsing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["query", "query"], + "msg": "value is not a valid integer", + "type": "type_error.integer", + } + ] + } + ) + + +def test_query_int_default(): + response = client.get("/query/int/default") + assert response.status_code == 200 + assert response.json() == "foo bar 10" + + +def test_query_int_default_query_50(): + response = client.get("/query/int/default?query=50") + assert response.status_code == 200 + assert response.json() == "foo bar 50" + + +def test_query_int_default_query_foo(): + response = client.get("/query/int/default?query=foo") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "int_parsing", + "loc": ["query", "query"], + "msg": "Input should be a valid integer, unable to parse string as an integer", + "input": "foo", + "url": match_pydantic_error_url("int_parsing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["query", "query"], + "msg": "value is not a valid integer", + "type": "type_error.integer", + } + ] + } + ) + + +def test_query_param(): + response = client.get("/query/param") + assert response.status_code == 200 + assert response.json() == "foo bar" + + +def test_query_param_query_50(): + response = client.get("/query/param?query=50") + assert response.status_code == 200 + assert response.json() == "foo bar 50" + + +def test_query_param_required(): + response = client.get("/query/param-required") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["query", "query"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["query", "query"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) + + +def test_query_param_required_query_50(): + response = client.get("/query/param-required?query=50") + assert response.status_code == 200 + assert response.json() == "foo bar 50" + + +def test_query_param_required_int(): + response = client.get("/query/param-required/int") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["query", "query"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["query", "query"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) + + +def test_query_param_required_int_query_50(): + response = client.get("/query/param-required/int?query=50") + assert response.status_code == 200 + assert response.json() == "foo bar 50" + + +def test_query_param_required_int_query_foo(): + response = client.get("/query/param-required/int?query=foo") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "int_parsing", + "loc": ["query", "query"], + "msg": "Input should be a valid integer, unable to parse string as an integer", + "input": "foo", + "url": match_pydantic_error_url("int_parsing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["query", "query"], + "msg": "value is not a valid integer", + "type": "type_error.integer", + } + ] + } + ) + + +def test_query_frozenset_query_1_query_1_query_2(): + response = client.get("/query/frozenset/?query=1&query=1&query=2") + assert response.status_code == 200 + assert response.json() == "1,2" diff --git a/tests/test_read_with_orm_mode.py b/tests/test_read_with_orm_mode.py index 360ad250350ec..b359874439281 100644 --- a/tests/test_read_with_orm_mode.py +++ b/tests/test_read_with_orm_mode.py @@ -2,48 +2,83 @@ from fastapi import FastAPI from fastapi.testclient import TestClient -from pydantic import BaseModel +from pydantic import BaseModel, ConfigDict +from .utils import needs_pydanticv1, needs_pydanticv2 -class PersonBase(BaseModel): - name: str - lastname: str +@needs_pydanticv2 +def test_read_with_orm_mode() -> None: + class PersonBase(BaseModel): + name: str + lastname: str + + class Person(PersonBase): + @property + def full_name(self) -> str: + return f"{self.name} {self.lastname}" + + model_config = ConfigDict(from_attributes=True) + + class PersonCreate(PersonBase): + pass -class Person(PersonBase): - @property - def full_name(self) -> str: - return f"{self.name} {self.lastname}" + class PersonRead(PersonBase): + full_name: str - class Config: - orm_mode = True - read_with_orm_mode = True + model_config = {"from_attributes": True} + app = FastAPI() -class PersonCreate(PersonBase): - pass + @app.post("/people/", response_model=PersonRead) + def create_person(person: PersonCreate) -> Any: + db_person = Person.model_validate(person) + return db_person + + client = TestClient(app) + + person_data = {"name": "Dive", "lastname": "Wilson"} + response = client.post("/people/", json=person_data) + data = response.json() + assert response.status_code == 200, response.text + assert data["name"] == person_data["name"] + assert data["lastname"] == person_data["lastname"] + assert data["full_name"] == person_data["name"] + " " + person_data["lastname"] -class PersonRead(PersonBase): - full_name: str +@needs_pydanticv1 +def test_read_with_orm_mode_pv1() -> None: + class PersonBase(BaseModel): + name: str + lastname: str - class Config: - orm_mode = True + class Person(PersonBase): + @property + def full_name(self) -> str: + return f"{self.name} {self.lastname}" + class Config: + orm_mode = True + read_with_orm_mode = True -app = FastAPI() + class PersonCreate(PersonBase): + pass + class PersonRead(PersonBase): + full_name: str -@app.post("/people/", response_model=PersonRead) -def create_person(person: PersonCreate) -> Any: - db_person = Person.from_orm(person) - return db_person + class Config: + orm_mode = True + app = FastAPI() -client = TestClient(app) + @app.post("/people/", response_model=PersonRead) + def create_person(person: PersonCreate) -> Any: + db_person = Person.from_orm(person) + return db_person + client = TestClient(app) -def test_read_with_orm_mode() -> None: person_data = {"name": "Dive", "lastname": "Wilson"} response = client.post("/people/", json=person_data) data = response.json() diff --git a/tests/test_regex_deprecated_body.py b/tests/test_regex_deprecated_body.py new file mode 100644 index 0000000000000..7afddd9ae00b3 --- /dev/null +++ b/tests/test_regex_deprecated_body.py @@ -0,0 +1,182 @@ +import pytest +from dirty_equals import IsDict +from fastapi import FastAPI, Form +from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url +from typing_extensions import Annotated + +from .utils import needs_py310 + + +def get_client(): + app = FastAPI() + with pytest.warns(DeprecationWarning): + + @app.post("/items/") + async def read_items( + q: Annotated[str | None, Form(regex="^fixedquery$")] = None, + ): + if q: + return f"Hello {q}" + else: + return "Hello World" + + client = TestClient(app) + return client + + +@needs_py310 +def test_no_query(): + client = get_client() + response = client.post("/items/") + assert response.status_code == 200 + assert response.json() == "Hello World" + + +@needs_py310 +def test_q_fixedquery(): + client = get_client() + response = client.post("/items/", data={"q": "fixedquery"}) + assert response.status_code == 200 + assert response.json() == "Hello fixedquery" + + +@needs_py310 +def test_query_nonregexquery(): + client = get_client() + response = client.post("/items/", data={"q": "nonregexquery"}) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "string_pattern_mismatch", + "loc": ["body", "q"], + "msg": "String should match pattern '^fixedquery$'", + "input": "nonregexquery", + "ctx": {"pattern": "^fixedquery$"}, + "url": match_pydantic_error_url("string_pattern_mismatch"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "ctx": {"pattern": "^fixedquery$"}, + "loc": ["body", "q"], + "msg": 'string does not match regex "^fixedquery$"', + "type": "value_error.str.regex", + } + ] + } + ) + + +@needs_py310 +def test_openapi_schema(): + client = get_client() + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + # insert_assert(response.json()) + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/items/": { + "post": { + "summary": "Read Items", + "operationId": "read_items_items__post", + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": IsDict( + { + "allOf": [ + { + "$ref": "#/components/schemas/Body_read_items_items__post" + } + ], + "title": "Body", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "$ref": "#/components/schemas/Body_read_items_items__post" + } + ) + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + } + }, + "components": { + "schemas": { + "Body_read_items_items__post": { + "properties": { + "q": IsDict( + { + "anyOf": [ + {"type": "string", "pattern": "^fixedquery$"}, + {"type": "null"}, + ], + "title": "Q", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"type": "string", "pattern": "^fixedquery$", "title": "Q"} + ) + }, + "type": "object", + "title": "Body_read_items_items__post", + }, + "HTTPValidationError": { + "properties": { + "detail": { + "items": {"$ref": "#/components/schemas/ValidationError"}, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + } + }, + } diff --git a/tests/test_regex_deprecated_params.py b/tests/test_regex_deprecated_params.py new file mode 100644 index 0000000000000..7190b543cb63e --- /dev/null +++ b/tests/test_regex_deprecated_params.py @@ -0,0 +1,165 @@ +import pytest +from dirty_equals import IsDict +from fastapi import FastAPI, Query +from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url +from typing_extensions import Annotated + +from .utils import needs_py310 + + +def get_client(): + app = FastAPI() + with pytest.warns(DeprecationWarning): + + @app.get("/items/") + async def read_items( + q: Annotated[str | None, Query(regex="^fixedquery$")] = None, + ): + if q: + return f"Hello {q}" + else: + return "Hello World" + + client = TestClient(app) + return client + + +@needs_py310 +def test_query_params_str_validations_no_query(): + client = get_client() + response = client.get("/items/") + assert response.status_code == 200 + assert response.json() == "Hello World" + + +@needs_py310 +def test_query_params_str_validations_q_fixedquery(): + client = get_client() + response = client.get("/items/", params={"q": "fixedquery"}) + assert response.status_code == 200 + assert response.json() == "Hello fixedquery" + + +@needs_py310 +def test_query_params_str_validations_item_query_nonregexquery(): + client = get_client() + response = client.get("/items/", params={"q": "nonregexquery"}) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "string_pattern_mismatch", + "loc": ["query", "q"], + "msg": "String should match pattern '^fixedquery$'", + "input": "nonregexquery", + "ctx": {"pattern": "^fixedquery$"}, + "url": match_pydantic_error_url("string_pattern_mismatch"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "ctx": {"pattern": "^fixedquery$"}, + "loc": ["query", "q"], + "msg": 'string does not match regex "^fixedquery$"', + "type": "value_error.str.regex", + } + ] + } + ) + + +@needs_py310 +def test_openapi_schema(): + client = get_client() + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + # insert_assert(response.json()) + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/items/": { + "get": { + "summary": "Read Items", + "operationId": "read_items_items__get", + "parameters": [ + { + "name": "q", + "in": "query", + "required": False, + "schema": IsDict( + { + "anyOf": [ + {"type": "string", "pattern": "^fixedquery$"}, + {"type": "null"}, + ], + "title": "Q", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "string", + "pattern": "^fixedquery$", + "title": "Q", + } + ), + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + } + }, + "components": { + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": {"$ref": "#/components/schemas/ValidationError"}, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + } + }, + } diff --git a/tests/test_repeated_dependency_schema.py b/tests/test_repeated_dependency_schema.py index ca0305184aaff..d7d0dfa052910 100644 --- a/tests/test_repeated_dependency_schema.py +++ b/tests/test_repeated_dependency_schema.py @@ -50,7 +50,7 @@ def get_deps(dep1: str = Depends(get_header), dep2: str = Depends(get_something_ } }, "info": {"title": "FastAPI", "version": "0.1.0"}, - "openapi": "3.0.2", + "openapi": "3.1.0", "paths": { "/": { "get": { diff --git a/tests/test_repeated_parameter_alias.py b/tests/test_repeated_parameter_alias.py index c656a161df4df..fd72eaab299ed 100644 --- a/tests/test_repeated_parameter_alias.py +++ b/tests/test_repeated_parameter_alias.py @@ -58,7 +58,7 @@ def test_openapi_schema(): } }, "info": {"title": "FastAPI", "version": "0.1.0"}, - "openapi": "3.0.2", + "openapi": "3.1.0", "paths": { "/{repeated_alias}": { "get": { diff --git a/tests/test_reponse_set_reponse_code_empty.py b/tests/test_reponse_set_reponse_code_empty.py index 14770fed0a80a..bf3aa758c3289 100644 --- a/tests/test_reponse_set_reponse_code_empty.py +++ b/tests/test_reponse_set_reponse_code_empty.py @@ -32,7 +32,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/{id}": { diff --git a/tests/test_request_body_parameters_media_type.py b/tests/test_request_body_parameters_media_type.py index 32f6c6a7252db..8c72fee54a4df 100644 --- a/tests/test_request_body_parameters_media_type.py +++ b/tests/test_request_body_parameters_media_type.py @@ -39,9 +39,8 @@ async def create_shop( def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text - # insert_assert(response.json()) assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/products": { diff --git a/tests/test_response_by_alias.py b/tests/test_response_by_alias.py index 1861a40fab0c5..e162cd39b5e85 100644 --- a/tests/test_response_by_alias.py +++ b/tests/test_response_by_alias.py @@ -1,8 +1,9 @@ from typing import List from fastapi import FastAPI +from fastapi._compat import PYDANTIC_V2 from fastapi.testclient import TestClient -from pydantic import BaseModel, Field +from pydantic import BaseModel, ConfigDict, Field app = FastAPI() @@ -14,13 +15,24 @@ class Model(BaseModel): class ModelNoAlias(BaseModel): name: str - class Config: - schema_extra = { - "description": ( - "response_model_by_alias=False is basically a quick hack, to support " - "proper OpenAPI use another model with the correct field names" - ) - } + if PYDANTIC_V2: + model_config = ConfigDict( + json_schema_extra={ + "description": ( + "response_model_by_alias=False is basically a quick hack, to support " + "proper OpenAPI use another model with the correct field names" + ) + } + ) + else: + + class Config: + schema_extra = { + "description": ( + "response_model_by_alias=False is basically a quick hack, to support " + "proper OpenAPI use another model with the correct field names" + ) + } @app.get("/dict", response_model=Model, response_model_by_alias=False) @@ -138,7 +150,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/dict": { diff --git a/tests/test_response_class_no_mediatype.py b/tests/test_response_class_no_mediatype.py index 2d75c7535827d..706929ac3673c 100644 --- a/tests/test_response_class_no_mediatype.py +++ b/tests/test_response_class_no_mediatype.py @@ -42,7 +42,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/a": { diff --git a/tests/test_response_code_no_body.py b/tests/test_response_code_no_body.py index 3851a325de585..3ca8708f1263a 100644 --- a/tests/test_response_code_no_body.py +++ b/tests/test_response_code_no_body.py @@ -50,7 +50,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/a": { diff --git a/tests/test_response_model_as_return_annotation.py b/tests/test_response_model_as_return_annotation.py index 7decdff7d0713..6948430a13b56 100644 --- a/tests/test_response_model_as_return_annotation.py +++ b/tests/test_response_model_as_return_annotation.py @@ -2,10 +2,10 @@ import pytest from fastapi import FastAPI -from fastapi.exceptions import FastAPIError +from fastapi.exceptions import FastAPIError, ResponseValidationError from fastapi.responses import JSONResponse, Response from fastapi.testclient import TestClient -from pydantic import BaseModel, ValidationError +from pydantic import BaseModel class BaseUser(BaseModel): @@ -277,13 +277,15 @@ def test_response_model_no_annotation_return_exact_dict(): def test_response_model_no_annotation_return_invalid_dict(): - with pytest.raises(ValidationError): + with pytest.raises(ResponseValidationError) as excinfo: client.get("/response_model-no_annotation-return_invalid_dict") + assert "missing" in str(excinfo.value) def test_response_model_no_annotation_return_invalid_model(): - with pytest.raises(ValidationError): + with pytest.raises(ResponseValidationError) as excinfo: client.get("/response_model-no_annotation-return_invalid_model") + assert "missing" in str(excinfo.value) def test_response_model_no_annotation_return_dict_with_extra_data(): @@ -313,13 +315,15 @@ def test_no_response_model_annotation_return_exact_dict(): def test_no_response_model_annotation_return_invalid_dict(): - with pytest.raises(ValidationError): + with pytest.raises(ResponseValidationError) as excinfo: client.get("/no_response_model-annotation-return_invalid_dict") + assert "missing" in str(excinfo.value) def test_no_response_model_annotation_return_invalid_model(): - with pytest.raises(ValidationError): + with pytest.raises(ResponseValidationError) as excinfo: client.get("/no_response_model-annotation-return_invalid_model") + assert "missing" in str(excinfo.value) def test_no_response_model_annotation_return_dict_with_extra_data(): @@ -395,13 +399,15 @@ def test_response_model_model1_annotation_model2_return_exact_dict(): def test_response_model_model1_annotation_model2_return_invalid_dict(): - with pytest.raises(ValidationError): + with pytest.raises(ResponseValidationError) as excinfo: client.get("/response_model_model1-annotation_model2-return_invalid_dict") + assert "missing" in str(excinfo.value) def test_response_model_model1_annotation_model2_return_invalid_model(): - with pytest.raises(ValidationError): + with pytest.raises(ResponseValidationError) as excinfo: client.get("/response_model_model1-annotation_model2-return_invalid_model") + assert "missing" in str(excinfo.value) def test_response_model_model1_annotation_model2_return_dict_with_extra_data(): @@ -507,7 +513,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/no_response_model-no_annotation-return_model": { diff --git a/tests/test_response_model_data_filter.py b/tests/test_response_model_data_filter.py new file mode 100644 index 0000000000000..a3e0f95f0438c --- /dev/null +++ b/tests/test_response_model_data_filter.py @@ -0,0 +1,81 @@ +from typing import List + +from fastapi import FastAPI +from fastapi.testclient import TestClient +from pydantic import BaseModel + +app = FastAPI() + + +class UserBase(BaseModel): + email: str + + +class UserCreate(UserBase): + password: str + + +class UserDB(UserBase): + hashed_password: str + + +class PetDB(BaseModel): + name: str + owner: UserDB + + +class PetOut(BaseModel): + name: str + owner: UserBase + + +@app.post("/users/", response_model=UserBase) +async def create_user(user: UserCreate): + return user + + +@app.get("/pets/{pet_id}", response_model=PetOut) +async def read_pet(pet_id: int): + user = UserDB( + email="johndoe@example.com", + hashed_password="secrethashed", + ) + pet = PetDB(name="Nibbler", owner=user) + return pet + + +@app.get("/pets/", response_model=List[PetOut]) +async def read_pets(): + user = UserDB( + email="johndoe@example.com", + hashed_password="secrethashed", + ) + pet1 = PetDB(name="Nibbler", owner=user) + pet2 = PetDB(name="Zoidberg", owner=user) + return [pet1, pet2] + + +client = TestClient(app) + + +def test_filter_top_level_model(): + response = client.post( + "/users", json={"email": "johndoe@example.com", "password": "secret"} + ) + assert response.json() == {"email": "johndoe@example.com"} + + +def test_filter_second_level_model(): + response = client.get("/pets/1") + assert response.json() == { + "name": "Nibbler", + "owner": {"email": "johndoe@example.com"}, + } + + +def test_list_of_models(): + response = client.get("/pets/") + assert response.json() == [ + {"name": "Nibbler", "owner": {"email": "johndoe@example.com"}}, + {"name": "Zoidberg", "owner": {"email": "johndoe@example.com"}}, + ] diff --git a/tests/test_response_model_data_filter_no_inheritance.py b/tests/test_response_model_data_filter_no_inheritance.py new file mode 100644 index 0000000000000..64003a8417f2a --- /dev/null +++ b/tests/test_response_model_data_filter_no_inheritance.py @@ -0,0 +1,83 @@ +from typing import List + +from fastapi import FastAPI +from fastapi.testclient import TestClient +from pydantic import BaseModel + +app = FastAPI() + + +class UserCreate(BaseModel): + email: str + password: str + + +class UserDB(BaseModel): + email: str + hashed_password: str + + +class User(BaseModel): + email: str + + +class PetDB(BaseModel): + name: str + owner: UserDB + + +class PetOut(BaseModel): + name: str + owner: User + + +@app.post("/users/", response_model=User) +async def create_user(user: UserCreate): + return user + + +@app.get("/pets/{pet_id}", response_model=PetOut) +async def read_pet(pet_id: int): + user = UserDB( + email="johndoe@example.com", + hashed_password="secrethashed", + ) + pet = PetDB(name="Nibbler", owner=user) + return pet + + +@app.get("/pets/", response_model=List[PetOut]) +async def read_pets(): + user = UserDB( + email="johndoe@example.com", + hashed_password="secrethashed", + ) + pet1 = PetDB(name="Nibbler", owner=user) + pet2 = PetDB(name="Zoidberg", owner=user) + return [pet1, pet2] + + +client = TestClient(app) + + +def test_filter_top_level_model(): + response = client.post( + "/users", json={"email": "johndoe@example.com", "password": "secret"} + ) + assert response.json() == {"email": "johndoe@example.com"} + + +def test_filter_second_level_model(): + response = client.get("/pets/1") + assert response.json() == { + "name": "Nibbler", + "owner": {"email": "johndoe@example.com"}, + } + + +def test_list_of_models(): + response = client.get("/pets/") + assert response.json() == [ + {"name": "Nibbler", "owner": {"email": "johndoe@example.com"}}, + {"name": "Zoidberg", "owner": {"email": "johndoe@example.com"}}, + ] diff --git a/tests/test_response_model_sub_types.py b/tests/test_response_model_sub_types.py index e462006ff1735..660bcee1bb7eb 100644 --- a/tests/test_response_model_sub_types.py +++ b/tests/test_response_model_sub_types.py @@ -50,7 +50,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/valid1": { diff --git a/tests/test_router_events.py b/tests/test_router_events.py index ba6b7638286ae..1b9de18aea26c 100644 --- a/tests/test_router_events.py +++ b/tests/test_router_events.py @@ -21,6 +21,9 @@ def state() -> State: return State() +@pytest.mark.filterwarnings( + r"ignore:\s*on_event is deprecated, use lifespan event handlers instead.*:DeprecationWarning" +) def test_router_events(state: State) -> None: app = FastAPI() diff --git a/tests/test_schema_extra_examples.py b/tests/test_schema_extra_examples.py index 41021a98391cd..b313f47e90fa2 100644 --- a/tests/test_schema_extra_examples.py +++ b/tests/test_schema_extra_examples.py @@ -1,240 +1,228 @@ from typing import Union +import pytest +from dirty_equals import IsDict from fastapi import Body, Cookie, FastAPI, Header, Path, Query +from fastapi._compat import PYDANTIC_V2 from fastapi.testclient import TestClient -from pydantic import BaseModel - -app = FastAPI() - - -class Item(BaseModel): - data: str - - class Config: - schema_extra = {"example": {"data": "Data in schema_extra"}} - - -@app.post("/schema_extra/") -def schema_extra(item: Item): - return item - - -@app.post("/example/") -def example(item: Item = Body(example={"data": "Data in Body example"})): - return item - - -@app.post("/examples/") -def examples( - item: Item = Body( - examples={ - "example1": { - "summary": "example1 summary", - "value": {"data": "Data in Body examples, example1"}, - }, - "example2": {"value": {"data": "Data in Body examples, example2"}}, - }, - ) -): - return item - - -@app.post("/example_examples/") -def example_examples( - item: Item = Body( - example={"data": "Overridden example"}, - examples={ - "example1": {"value": {"data": "examples example_examples 1"}}, - "example2": {"value": {"data": "examples example_examples 2"}}, - }, - ) -): - return item - - -# TODO: enable these tests once/if Form(embed=False) is supported -# TODO: In that case, define if File() should support example/examples too -# @app.post("/form_example") -# def form_example(firstname: str = Form(example="John")): -# return firstname - - -# @app.post("/form_examples") -# def form_examples( -# lastname: str = Form( -# ..., -# examples={ -# "example1": {"summary": "last name summary", "value": "Doe"}, -# "example2": {"value": "Doesn't"}, -# }, -# ), -# ): -# return lastname - - -# @app.post("/form_example_examples") -# def form_example_examples( -# lastname: str = Form( -# ..., -# example="Doe overridden", -# examples={ -# "example1": {"summary": "last name summary", "value": "Doe"}, -# "example2": {"value": "Doesn't"}, -# }, -# ), -# ): -# return lastname - - -@app.get("/path_example/{item_id}") -def path_example( - item_id: str = Path( - example="item_1", - ), -): - return item_id - - -@app.get("/path_examples/{item_id}") -def path_examples( - item_id: str = Path( - examples={ - "example1": {"summary": "item ID summary", "value": "item_1"}, - "example2": {"value": "item_2"}, - }, - ), -): - return item_id - - -@app.get("/path_example_examples/{item_id}") -def path_example_examples( - item_id: str = Path( - example="item_overridden", - examples={ - "example1": {"summary": "item ID summary", "value": "item_1"}, - "example2": {"value": "item_2"}, - }, - ), -): - return item_id - - -@app.get("/query_example/") -def query_example( - data: Union[str, None] = Query( - default=None, - example="query1", - ), -): - return data - - -@app.get("/query_examples/") -def query_examples( - data: Union[str, None] = Query( - default=None, - examples={ - "example1": {"summary": "Query example 1", "value": "query1"}, - "example2": {"value": "query2"}, - }, - ), -): - return data - - -@app.get("/query_example_examples/") -def query_example_examples( - data: Union[str, None] = Query( - default=None, - example="query_overridden", - examples={ - "example1": {"summary": "Query example 1", "value": "query1"}, - "example2": {"value": "query2"}, - }, - ), -): - return data - - -@app.get("/header_example/") -def header_example( - data: Union[str, None] = Header( - default=None, - example="header1", - ), -): - return data - - -@app.get("/header_examples/") -def header_examples( - data: Union[str, None] = Header( - default=None, - examples={ - "example1": {"summary": "header example 1", "value": "header1"}, - "example2": {"value": "header2"}, - }, - ), -): - return data - - -@app.get("/header_example_examples/") -def header_example_examples( - data: Union[str, None] = Header( - default=None, - example="header_overridden", - examples={ - "example1": {"summary": "Query example 1", "value": "header1"}, - "example2": {"value": "header2"}, - }, - ), -): - return data - - -@app.get("/cookie_example/") -def cookie_example( - data: Union[str, None] = Cookie( - default=None, - example="cookie1", - ), -): - return data - - -@app.get("/cookie_examples/") -def cookie_examples( - data: Union[str, None] = Cookie( - default=None, - examples={ - "example1": {"summary": "cookie example 1", "value": "cookie1"}, - "example2": {"value": "cookie2"}, - }, - ), -): - return data - - -@app.get("/cookie_example_examples/") -def cookie_example_examples( - data: Union[str, None] = Cookie( - default=None, - example="cookie_overridden", - examples={ - "example1": {"summary": "Query example 1", "value": "cookie1"}, - "example2": {"value": "cookie2"}, - }, - ), -): - return data - - -client = TestClient(app) +from pydantic import BaseModel, ConfigDict + + +def create_app(): + app = FastAPI() + + class Item(BaseModel): + data: str + + if PYDANTIC_V2: + model_config = ConfigDict( + json_schema_extra={"example": {"data": "Data in schema_extra"}} + ) + else: + + class Config: + schema_extra = {"example": {"data": "Data in schema_extra"}} + + @app.post("/schema_extra/") + def schema_extra(item: Item): + return item + + with pytest.warns(DeprecationWarning): + + @app.post("/example/") + def example(item: Item = Body(example={"data": "Data in Body example"})): + return item + + @app.post("/examples/") + def examples( + item: Item = Body( + examples=[ + {"data": "Data in Body examples, example1"}, + {"data": "Data in Body examples, example2"}, + ], + ), + ): + return item + + with pytest.warns(DeprecationWarning): + + @app.post("/example_examples/") + def example_examples( + item: Item = Body( + example={"data": "Overridden example"}, + examples=[ + {"data": "examples example_examples 1"}, + {"data": "examples example_examples 2"}, + ], + ), + ): + return item + + # TODO: enable these tests once/if Form(embed=False) is supported + # TODO: In that case, define if File() should support example/examples too + # @app.post("/form_example") + # def form_example(firstname: str = Form(example="John")): + # return firstname + + # @app.post("/form_examples") + # def form_examples( + # lastname: str = Form( + # ..., + # examples={ + # "example1": {"summary": "last name summary", "value": "Doe"}, + # "example2": {"value": "Doesn't"}, + # }, + # ), + # ): + # return lastname + + # @app.post("/form_example_examples") + # def form_example_examples( + # lastname: str = Form( + # ..., + # example="Doe overridden", + # examples={ + # "example1": {"summary": "last name summary", "value": "Doe"}, + # "example2": {"value": "Doesn't"}, + # }, + # ), + # ): + # return lastname + + with pytest.warns(DeprecationWarning): + + @app.get("/path_example/{item_id}") + def path_example( + item_id: str = Path( + example="item_1", + ), + ): + return item_id + + @app.get("/path_examples/{item_id}") + def path_examples( + item_id: str = Path( + examples=["item_1", "item_2"], + ), + ): + return item_id + + with pytest.warns(DeprecationWarning): + + @app.get("/path_example_examples/{item_id}") + def path_example_examples( + item_id: str = Path( + example="item_overridden", + examples=["item_1", "item_2"], + ), + ): + return item_id + + with pytest.warns(DeprecationWarning): + + @app.get("/query_example/") + def query_example( + data: Union[str, None] = Query( + default=None, + example="query1", + ), + ): + return data + + @app.get("/query_examples/") + def query_examples( + data: Union[str, None] = Query( + default=None, + examples=["query1", "query2"], + ), + ): + return data + + with pytest.warns(DeprecationWarning): + + @app.get("/query_example_examples/") + def query_example_examples( + data: Union[str, None] = Query( + default=None, + example="query_overridden", + examples=["query1", "query2"], + ), + ): + return data + + with pytest.warns(DeprecationWarning): + + @app.get("/header_example/") + def header_example( + data: Union[str, None] = Header( + default=None, + example="header1", + ), + ): + return data + + @app.get("/header_examples/") + def header_examples( + data: Union[str, None] = Header( + default=None, + examples=[ + "header1", + "header2", + ], + ), + ): + return data + + with pytest.warns(DeprecationWarning): + + @app.get("/header_example_examples/") + def header_example_examples( + data: Union[str, None] = Header( + default=None, + example="header_overridden", + examples=["header1", "header2"], + ), + ): + return data + + with pytest.warns(DeprecationWarning): + + @app.get("/cookie_example/") + def cookie_example( + data: Union[str, None] = Cookie( + default=None, + example="cookie1", + ), + ): + return data + + @app.get("/cookie_examples/") + def cookie_examples( + data: Union[str, None] = Cookie( + default=None, + examples=["cookie1", "cookie2"], + ), + ): + return data + + with pytest.warns(DeprecationWarning): + + @app.get("/cookie_example_examples/") + def cookie_example_examples( + data: Union[str, None] = Cookie( + default=None, + example="cookie_overridden", + examples=["cookie1", "cookie2"], + ), + ): + return data + + return app def test_call_api(): + app = create_app() + client = TestClient(app) response = client.post("/schema_extra/", json={"data": "Foo"}) assert response.status_code == 200, response.text response = client.post("/example/", json={"data": "Foo"}) @@ -277,10 +265,12 @@ def test_openapi_schema(): * Body(example={}) overrides schema_extra in pydantic model * Body(examples{}) overrides Body(example={}) and schema_extra in pydantic model """ + app = create_app() + client = TestClient(app) response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/schema_extra/": { @@ -351,20 +341,28 @@ def test_openapi_schema(): "requestBody": { "content": { "application/json": { - "schema": {"$ref": "#/components/schemas/Item"}, - "examples": { - "example1": { - "summary": "example1 summary", - "value": { - "data": "Data in Body examples, example1" - }, - }, - "example2": { - "value": { - "data": "Data in Body examples, example2" - } - }, - }, + "schema": IsDict( + { + "$ref": "#/components/schemas/Item", + "examples": [ + {"data": "Data in Body examples, example1"}, + {"data": "Data in Body examples, example2"}, + ], + } + ) + | IsDict( + # TODO: remove this when deprecating Pydantic v1 + { + "allOf": [ + {"$ref": "#/components/schemas/Item"} + ], + "title": "Item", + "examples": [ + {"data": "Data in Body examples, example1"}, + {"data": "Data in Body examples, example2"}, + ], + } + ) } }, "required": True, @@ -394,15 +392,29 @@ def test_openapi_schema(): "requestBody": { "content": { "application/json": { - "schema": {"$ref": "#/components/schemas/Item"}, - "examples": { - "example1": { - "value": {"data": "examples example_examples 1"} - }, - "example2": { - "value": {"data": "examples example_examples 2"} + "schema": IsDict( + { + "$ref": "#/components/schemas/Item", + "examples": [ + {"data": "examples example_examples 1"}, + {"data": "examples example_examples 2"}, + ], + } + ) + | IsDict( + # TODO: remove this when deprecating Pydantic v1 + { + "allOf": [ + {"$ref": "#/components/schemas/Item"} + ], + "title": "Item", + "examples": [ + {"data": "examples example_examples 1"}, + {"data": "examples example_examples 2"}, + ], }, - }, + ), + "example": {"data": "Overridden example"}, } }, "required": True, @@ -463,13 +475,10 @@ def test_openapi_schema(): "parameters": [ { "required": True, - "schema": {"title": "Item Id", "type": "string"}, - "examples": { - "example1": { - "summary": "item ID summary", - "value": "item_1", - }, - "example2": {"value": "item_2"}, + "schema": { + "title": "Item Id", + "type": "string", + "examples": ["item_1", "item_2"], }, "name": "item_id", "in": "path", @@ -500,14 +509,12 @@ def test_openapi_schema(): "parameters": [ { "required": True, - "schema": {"title": "Item Id", "type": "string"}, - "examples": { - "example1": { - "summary": "item ID summary", - "value": "item_1", - }, - "example2": {"value": "item_2"}, + "schema": { + "title": "Item Id", + "type": "string", + "examples": ["item_1", "item_2"], }, + "example": "item_overridden", "name": "item_id", "in": "path", } @@ -537,7 +544,16 @@ def test_openapi_schema(): "parameters": [ { "required": False, - "schema": {"title": "Data", "type": "string"}, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Data", + } + ) + | IsDict( + # TODO: Remove this when deprecating Pydantic v1 + {"title": "Data", "type": "string"} + ), "example": "query1", "name": "data", "in": "query", @@ -568,14 +584,21 @@ def test_openapi_schema(): "parameters": [ { "required": False, - "schema": {"title": "Data", "type": "string"}, - "examples": { - "example1": { - "summary": "Query example 1", - "value": "query1", - }, - "example2": {"value": "query2"}, - }, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Data", + "examples": ["query1", "query2"], + } + ) + | IsDict( + # TODO: Remove this when deprecating Pydantic v1 + { + "type": "string", + "title": "Data", + "examples": ["query1", "query2"], + } + ), "name": "data", "in": "query", } @@ -605,14 +628,22 @@ def test_openapi_schema(): "parameters": [ { "required": False, - "schema": {"title": "Data", "type": "string"}, - "examples": { - "example1": { - "summary": "Query example 1", - "value": "query1", - }, - "example2": {"value": "query2"}, - }, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Data", + "examples": ["query1", "query2"], + } + ) + | IsDict( + # TODO: Remove this when deprecating Pydantic v1 + { + "type": "string", + "title": "Data", + "examples": ["query1", "query2"], + } + ), + "example": "query_overridden", "name": "data", "in": "query", } @@ -642,7 +673,16 @@ def test_openapi_schema(): "parameters": [ { "required": False, - "schema": {"title": "Data", "type": "string"}, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Data", + } + ) + | IsDict( + # TODO: Remove this when deprecating Pydantic v1 + {"title": "Data", "type": "string"} + ), "example": "header1", "name": "data", "in": "header", @@ -673,14 +713,21 @@ def test_openapi_schema(): "parameters": [ { "required": False, - "schema": {"title": "Data", "type": "string"}, - "examples": { - "example1": { - "summary": "header example 1", - "value": "header1", - }, - "example2": {"value": "header2"}, - }, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Data", + "examples": ["header1", "header2"], + } + ) + | IsDict( + # TODO: Remove this when deprecating Pydantic v1 + { + "type": "string", + "title": "Data", + "examples": ["header1", "header2"], + } + ), "name": "data", "in": "header", } @@ -710,14 +757,22 @@ def test_openapi_schema(): "parameters": [ { "required": False, - "schema": {"title": "Data", "type": "string"}, - "examples": { - "example1": { - "summary": "Query example 1", - "value": "header1", - }, - "example2": {"value": "header2"}, - }, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Data", + "examples": ["header1", "header2"], + } + ) + | IsDict( + # TODO: Remove this when deprecating Pydantic v1 + { + "title": "Data", + "type": "string", + "examples": ["header1", "header2"], + } + ), + "example": "header_overridden", "name": "data", "in": "header", } @@ -747,7 +802,16 @@ def test_openapi_schema(): "parameters": [ { "required": False, - "schema": {"title": "Data", "type": "string"}, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Data", + } + ) + | IsDict( + # TODO: Remove this when deprecating Pydantic v1 + {"title": "Data", "type": "string"} + ), "example": "cookie1", "name": "data", "in": "cookie", @@ -778,14 +842,21 @@ def test_openapi_schema(): "parameters": [ { "required": False, - "schema": {"title": "Data", "type": "string"}, - "examples": { - "example1": { - "summary": "cookie example 1", - "value": "cookie1", - }, - "example2": {"value": "cookie2"}, - }, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Data", + "examples": ["cookie1", "cookie2"], + } + ) + | IsDict( + # TODO: Remove this when deprecating Pydantic v1 + { + "title": "Data", + "type": "string", + "examples": ["cookie1", "cookie2"], + } + ), "name": "data", "in": "cookie", } @@ -815,14 +886,22 @@ def test_openapi_schema(): "parameters": [ { "required": False, - "schema": {"title": "Data", "type": "string"}, - "examples": { - "example1": { - "summary": "Query example 1", - "value": "cookie1", - }, - "example2": {"value": "cookie2"}, - }, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Data", + "examples": ["cookie1", "cookie2"], + } + ) + | IsDict( + # TODO: Remove this when deprecating Pydantic v1 + { + "title": "Data", + "type": "string", + "examples": ["cookie1", "cookie2"], + } + ), + "example": "cookie_overridden", "name": "data", "in": "cookie", } diff --git a/tests/test_security_api_key_cookie.py b/tests/test_security_api_key_cookie.py index b1c648c55e184..4ddb8e2eeb11b 100644 --- a/tests/test_security_api_key_cookie.py +++ b/tests/test_security_api_key_cookie.py @@ -41,7 +41,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/me": { diff --git a/tests/test_security_api_key_cookie_description.py b/tests/test_security_api_key_cookie_description.py index ac8b4abf8791b..d99d616e06796 100644 --- a/tests/test_security_api_key_cookie_description.py +++ b/tests/test_security_api_key_cookie_description.py @@ -41,7 +41,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/me": { diff --git a/tests/test_security_api_key_cookie_optional.py b/tests/test_security_api_key_cookie_optional.py index b8c440c9d703f..cb5590168d30c 100644 --- a/tests/test_security_api_key_cookie_optional.py +++ b/tests/test_security_api_key_cookie_optional.py @@ -48,7 +48,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/me": { diff --git a/tests/test_security_api_key_header.py b/tests/test_security_api_key_header.py index 96ad80b54a5bf..1ff883703d59d 100644 --- a/tests/test_security_api_key_header.py +++ b/tests/test_security_api_key_header.py @@ -41,7 +41,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/me": { diff --git a/tests/test_security_api_key_header_description.py b/tests/test_security_api_key_header_description.py index 382f53dd78197..27f9d0f29e6d6 100644 --- a/tests/test_security_api_key_header_description.py +++ b/tests/test_security_api_key_header_description.py @@ -41,7 +41,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/me": { diff --git a/tests/test_security_api_key_header_optional.py b/tests/test_security_api_key_header_optional.py index adfb20ba08d0c..6f9682a64fef3 100644 --- a/tests/test_security_api_key_header_optional.py +++ b/tests/test_security_api_key_header_optional.py @@ -47,7 +47,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/me": { diff --git a/tests/test_security_api_key_query.py b/tests/test_security_api_key_query.py index da98eafd6cce2..dc7a0a621aabe 100644 --- a/tests/test_security_api_key_query.py +++ b/tests/test_security_api_key_query.py @@ -41,7 +41,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/me": { diff --git a/tests/test_security_api_key_query_description.py b/tests/test_security_api_key_query_description.py index 3c08afc5f4d8b..35dc7743a23ea 100644 --- a/tests/test_security_api_key_query_description.py +++ b/tests/test_security_api_key_query_description.py @@ -41,7 +41,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/me": { diff --git a/tests/test_security_api_key_query_optional.py b/tests/test_security_api_key_query_optional.py index 99a26cfd0bec3..4cc134bd49ab9 100644 --- a/tests/test_security_api_key_query_optional.py +++ b/tests/test_security_api_key_query_optional.py @@ -47,7 +47,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/me": { diff --git a/tests/test_security_http_base.py b/tests/test_security_http_base.py index d3a7542034685..51928bafd5988 100644 --- a/tests/test_security_http_base.py +++ b/tests/test_security_http_base.py @@ -31,7 +31,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/me": { diff --git a/tests/test_security_http_base_description.py b/tests/test_security_http_base_description.py index 3d7d150166bf7..bc79f32424b6a 100644 --- a/tests/test_security_http_base_description.py +++ b/tests/test_security_http_base_description.py @@ -31,7 +31,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/me": { diff --git a/tests/test_security_http_base_optional.py b/tests/test_security_http_base_optional.py index 180c9110e9919..dd4d76843ab29 100644 --- a/tests/test_security_http_base_optional.py +++ b/tests/test_security_http_base_optional.py @@ -37,7 +37,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/me": { diff --git a/tests/test_security_http_basic_optional.py b/tests/test_security_http_basic_optional.py index 7e7fcac32a8e7..9b6cb6c455436 100644 --- a/tests/test_security_http_basic_optional.py +++ b/tests/test_security_http_basic_optional.py @@ -54,7 +54,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/me": { diff --git a/tests/test_security_http_basic_realm.py b/tests/test_security_http_basic_realm.py index 470afd662a4e6..9fc33971aec6c 100644 --- a/tests/test_security_http_basic_realm.py +++ b/tests/test_security_http_basic_realm.py @@ -52,7 +52,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/me": { diff --git a/tests/test_security_http_basic_realm_description.py b/tests/test_security_http_basic_realm_description.py index 44289007b55d4..02122442eb113 100644 --- a/tests/test_security_http_basic_realm_description.py +++ b/tests/test_security_http_basic_realm_description.py @@ -52,7 +52,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/me": { diff --git a/tests/test_security_http_bearer.py b/tests/test_security_http_bearer.py index f24869fc32360..5b9e2d6919b09 100644 --- a/tests/test_security_http_bearer.py +++ b/tests/test_security_http_bearer.py @@ -37,7 +37,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/me": { diff --git a/tests/test_security_http_bearer_description.py b/tests/test_security_http_bearer_description.py index 6d5ad0b8e7e00..2f11c3a148c0d 100644 --- a/tests/test_security_http_bearer_description.py +++ b/tests/test_security_http_bearer_description.py @@ -37,7 +37,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/me": { diff --git a/tests/test_security_http_bearer_optional.py b/tests/test_security_http_bearer_optional.py index b596ac7300d9d..943da2ee2e93e 100644 --- a/tests/test_security_http_bearer_optional.py +++ b/tests/test_security_http_bearer_optional.py @@ -43,7 +43,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/me": { diff --git a/tests/test_security_http_digest.py b/tests/test_security_http_digest.py index 2a25efe023325..133d35763c3ed 100644 --- a/tests/test_security_http_digest.py +++ b/tests/test_security_http_digest.py @@ -39,7 +39,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/me": { diff --git a/tests/test_security_http_digest_description.py b/tests/test_security_http_digest_description.py index 721f7cfde5e54..4e31a0c00848c 100644 --- a/tests/test_security_http_digest_description.py +++ b/tests/test_security_http_digest_description.py @@ -39,7 +39,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/me": { diff --git a/tests/test_security_http_digest_optional.py b/tests/test_security_http_digest_optional.py index d4c3597bcbe2e..1e6eb8bd7f673 100644 --- a/tests/test_security_http_digest_optional.py +++ b/tests/test_security_http_digest_optional.py @@ -45,7 +45,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/me": { diff --git a/tests/test_security_oauth2.py b/tests/test_security_oauth2.py index 23dce7cfa9664..e98f80ebfbe03 100644 --- a/tests/test_security_oauth2.py +++ b/tests/test_security_oauth2.py @@ -1,7 +1,8 @@ -import pytest +from dirty_equals import IsDict from fastapi import Depends, FastAPI, Security from fastapi.security import OAuth2, OAuth2PasswordRequestFormStrict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url from pydantic import BaseModel app = FastAPI() @@ -59,83 +60,143 @@ def test_security_oauth2_password_bearer_no_header(): assert response.json() == {"detail": "Not authenticated"} -required_params = { - "detail": [ +def test_strict_login_no_data(): + response = client.post("/login") + assert response.status_code == 422 + assert response.json() == IsDict( { - "loc": ["body", "grant_type"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "username"], - "msg": "field required", - "type": "value_error.missing", - }, + "detail": [ + { + "type": "missing", + "loc": ["body", "grant_type"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 { - "loc": ["body", "password"], - "msg": "field required", - "type": "value_error.missing", - }, - ] -} + "detail": [ + { + "loc": ["body", "grant_type"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "username"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "password"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) -grant_type_required = { - "detail": [ + +def test_strict_login_no_grant_type(): + response = client.post("/login", data={"username": "johndoe", "password": "secret"}) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "grant_type"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 { - "loc": ["body", "grant_type"], - "msg": "field required", - "type": "value_error.missing", + "detail": [ + { + "loc": ["body", "grant_type"], + "msg": "field required", + "type": "value_error.missing", + } + ] } - ] -} + ) -grant_type_incorrect = { - "detail": [ + +def test_strict_login_incorrect_grant_type(): + response = client.post( + "/login", + data={"username": "johndoe", "password": "secret", "grant_type": "incorrect"}, + ) + assert response.status_code == 422 + assert response.json() == IsDict( { - "loc": ["body", "grant_type"], - "msg": 'string does not match regex "password"', - "type": "value_error.str.regex", - "ctx": {"pattern": "password"}, + "detail": [ + { + "type": "string_pattern_mismatch", + "loc": ["body", "grant_type"], + "msg": "String should match pattern 'password'", + "input": "incorrect", + "ctx": {"pattern": "password"}, + "url": match_pydantic_error_url("string_pattern_mismatch"), + } + ] } - ] -} - - -@pytest.mark.parametrize( - "data,expected_status,expected_response", - [ - (None, 422, required_params), - ({"username": "johndoe", "password": "secret"}, 422, grant_type_required), - ( - {"username": "johndoe", "password": "secret", "grant_type": "incorrect"}, - 422, - grant_type_incorrect, - ), - ( - {"username": "johndoe", "password": "secret", "grant_type": "password"}, - 200, - { - "grant_type": "password", - "username": "johndoe", - "password": "secret", - "scopes": [], - "client_id": None, - "client_secret": None, - }, - ), - ], -) -def test_strict_login(data, expected_status, expected_response): - response = client.post("/login", data=data) - assert response.status_code == expected_status - assert response.json() == expected_response + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "grant_type"], + "msg": 'string does not match regex "password"', + "type": "value_error.str.regex", + "ctx": {"pattern": "password"}, + } + ] + } + ) + + +def test_strict_login_correct_grant_type(): + response = client.post( + "/login", + data={"username": "johndoe", "password": "secret", "grant_type": "password"}, + ) + assert response.status_code == 200 + assert response.json() == { + "grant_type": "password", + "username": "johndoe", + "password": "secret", + "scopes": [], + "client_id": None, + "client_secret": None, + } def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/login": { @@ -199,8 +260,26 @@ def test_openapi_schema(): "username": {"title": "Username", "type": "string"}, "password": {"title": "Password", "type": "string"}, "scope": {"title": "Scope", "type": "string", "default": ""}, - "client_id": {"title": "Client Id", "type": "string"}, - "client_secret": {"title": "Client Secret", "type": "string"}, + "client_id": IsDict( + { + "title": "Client Id", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Client Id", "type": "string"} + ), + "client_secret": IsDict( + { + "title": "Client Secret", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Client Secret", "type": "string"} + ), }, }, "ValidationError": { diff --git a/tests/test_security_oauth2_authorization_code_bearer.py b/tests/test_security_oauth2_authorization_code_bearer.py index 6df81528db7ec..f2097b14904a4 100644 --- a/tests/test_security_oauth2_authorization_code_bearer.py +++ b/tests/test_security_oauth2_authorization_code_bearer.py @@ -41,7 +41,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { diff --git a/tests/test_security_oauth2_authorization_code_bearer_description.py b/tests/test_security_oauth2_authorization_code_bearer_description.py index c119abde4da18..5386fbbd9db62 100644 --- a/tests/test_security_oauth2_authorization_code_bearer_description.py +++ b/tests/test_security_oauth2_authorization_code_bearer_description.py @@ -44,7 +44,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { diff --git a/tests/test_security_oauth2_optional.py b/tests/test_security_oauth2_optional.py index 3ef9f4a8d2448..d06c01bba0c74 100644 --- a/tests/test_security_oauth2_optional.py +++ b/tests/test_security_oauth2_optional.py @@ -1,9 +1,10 @@ from typing import Optional -import pytest +from dirty_equals import IsDict from fastapi import Depends, FastAPI, Security from fastapi.security import OAuth2, OAuth2PasswordRequestFormStrict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url from pydantic import BaseModel app = FastAPI() @@ -63,83 +64,143 @@ def test_security_oauth2_password_bearer_no_header(): assert response.json() == {"msg": "Create an account first"} -required_params = { - "detail": [ +def test_strict_login_no_data(): + response = client.post("/login") + assert response.status_code == 422 + assert response.json() == IsDict( { - "loc": ["body", "grant_type"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "username"], - "msg": "field required", - "type": "value_error.missing", - }, + "detail": [ + { + "type": "missing", + "loc": ["body", "grant_type"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 { - "loc": ["body", "password"], - "msg": "field required", - "type": "value_error.missing", - }, - ] -} + "detail": [ + { + "loc": ["body", "grant_type"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "username"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "password"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) -grant_type_required = { - "detail": [ + +def test_strict_login_no_grant_type(): + response = client.post("/login", data={"username": "johndoe", "password": "secret"}) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "grant_type"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 { - "loc": ["body", "grant_type"], - "msg": "field required", - "type": "value_error.missing", + "detail": [ + { + "loc": ["body", "grant_type"], + "msg": "field required", + "type": "value_error.missing", + } + ] } - ] -} + ) -grant_type_incorrect = { - "detail": [ + +def test_strict_login_incorrect_grant_type(): + response = client.post( + "/login", + data={"username": "johndoe", "password": "secret", "grant_type": "incorrect"}, + ) + assert response.status_code == 422 + assert response.json() == IsDict( { - "loc": ["body", "grant_type"], - "msg": 'string does not match regex "password"', - "type": "value_error.str.regex", - "ctx": {"pattern": "password"}, + "detail": [ + { + "type": "string_pattern_mismatch", + "loc": ["body", "grant_type"], + "msg": "String should match pattern 'password'", + "input": "incorrect", + "ctx": {"pattern": "password"}, + "url": match_pydantic_error_url("string_pattern_mismatch"), + } + ] } - ] -} - - -@pytest.mark.parametrize( - "data,expected_status,expected_response", - [ - (None, 422, required_params), - ({"username": "johndoe", "password": "secret"}, 422, grant_type_required), - ( - {"username": "johndoe", "password": "secret", "grant_type": "incorrect"}, - 422, - grant_type_incorrect, - ), - ( - {"username": "johndoe", "password": "secret", "grant_type": "password"}, - 200, - { - "grant_type": "password", - "username": "johndoe", - "password": "secret", - "scopes": [], - "client_id": None, - "client_secret": None, - }, - ), - ], -) -def test_strict_login(data, expected_status, expected_response): - response = client.post("/login", data=data) - assert response.status_code == expected_status - assert response.json() == expected_response + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "grant_type"], + "msg": 'string does not match regex "password"', + "type": "value_error.str.regex", + "ctx": {"pattern": "password"}, + } + ] + } + ) + + +def test_strict_login_correct_data(): + response = client.post( + "/login", + data={"username": "johndoe", "password": "secret", "grant_type": "password"}, + ) + assert response.status_code == 200 + assert response.json() == { + "grant_type": "password", + "username": "johndoe", + "password": "secret", + "scopes": [], + "client_id": None, + "client_secret": None, + } def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/login": { @@ -203,8 +264,26 @@ def test_openapi_schema(): "username": {"title": "Username", "type": "string"}, "password": {"title": "Password", "type": "string"}, "scope": {"title": "Scope", "type": "string", "default": ""}, - "client_id": {"title": "Client Id", "type": "string"}, - "client_secret": {"title": "Client Secret", "type": "string"}, + "client_id": IsDict( + { + "title": "Client Id", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Client Id", "type": "string"} + ), + "client_secret": IsDict( + { + "title": "Client Secret", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Client Secret", "type": "string"} + ), }, }, "ValidationError": { diff --git a/tests/test_security_oauth2_optional_description.py b/tests/test_security_oauth2_optional_description.py index b6425fde4db19..9287e4366e643 100644 --- a/tests/test_security_oauth2_optional_description.py +++ b/tests/test_security_oauth2_optional_description.py @@ -1,9 +1,10 @@ from typing import Optional -import pytest +from dirty_equals import IsDict from fastapi import Depends, FastAPI, Security from fastapi.security import OAuth2, OAuth2PasswordRequestFormStrict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url from pydantic import BaseModel app = FastAPI() @@ -64,83 +65,143 @@ def test_security_oauth2_password_bearer_no_header(): assert response.json() == {"msg": "Create an account first"} -required_params = { - "detail": [ +def test_strict_login_None(): + response = client.post("/login", data=None) + assert response.status_code == 422 + assert response.json() == IsDict( { - "loc": ["body", "grant_type"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "username"], - "msg": "field required", - "type": "value_error.missing", - }, + "detail": [ + { + "type": "missing", + "loc": ["body", "grant_type"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 { - "loc": ["body", "password"], - "msg": "field required", - "type": "value_error.missing", - }, - ] -} + "detail": [ + { + "loc": ["body", "grant_type"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "username"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "password"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) -grant_type_required = { - "detail": [ + +def test_strict_login_no_grant_type(): + response = client.post("/login", data={"username": "johndoe", "password": "secret"}) + assert response.status_code == 422 + assert response.json() == IsDict( { - "loc": ["body", "grant_type"], - "msg": "field required", - "type": "value_error.missing", + "detail": [ + { + "type": "missing", + "loc": ["body", "grant_type"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] } - ] -} + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "grant_type"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) + -grant_type_incorrect = { - "detail": [ +def test_strict_login_incorrect_grant_type(): + response = client.post( + "/login", + data={"username": "johndoe", "password": "secret", "grant_type": "incorrect"}, + ) + assert response.status_code == 422 + assert response.json() == IsDict( { - "loc": ["body", "grant_type"], - "msg": 'string does not match regex "password"', - "type": "value_error.str.regex", - "ctx": {"pattern": "password"}, + "detail": [ + { + "type": "string_pattern_mismatch", + "loc": ["body", "grant_type"], + "msg": "String should match pattern 'password'", + "input": "incorrect", + "ctx": {"pattern": "password"}, + "url": match_pydantic_error_url("string_pattern_mismatch"), + } + ] } - ] -} - - -@pytest.mark.parametrize( - "data,expected_status,expected_response", - [ - (None, 422, required_params), - ({"username": "johndoe", "password": "secret"}, 422, grant_type_required), - ( - {"username": "johndoe", "password": "secret", "grant_type": "incorrect"}, - 422, - grant_type_incorrect, - ), - ( - {"username": "johndoe", "password": "secret", "grant_type": "password"}, - 200, - { - "grant_type": "password", - "username": "johndoe", - "password": "secret", - "scopes": [], - "client_id": None, - "client_secret": None, - }, - ), - ], -) -def test_strict_login(data, expected_status, expected_response): - response = client.post("/login", data=data) - assert response.status_code == expected_status - assert response.json() == expected_response + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "grant_type"], + "msg": 'string does not match regex "password"', + "type": "value_error.str.regex", + "ctx": {"pattern": "password"}, + } + ] + } + ) + + +def test_strict_login_correct_correct_grant_type(): + response = client.post( + "/login", + data={"username": "johndoe", "password": "secret", "grant_type": "password"}, + ) + assert response.status_code == 200, response.text + assert response.json() == { + "grant_type": "password", + "username": "johndoe", + "password": "secret", + "scopes": [], + "client_id": None, + "client_secret": None, + } def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/login": { @@ -204,8 +265,26 @@ def test_openapi_schema(): "username": {"title": "Username", "type": "string"}, "password": {"title": "Password", "type": "string"}, "scope": {"title": "Scope", "type": "string", "default": ""}, - "client_id": {"title": "Client Id", "type": "string"}, - "client_secret": {"title": "Client Secret", "type": "string"}, + "client_id": IsDict( + { + "title": "Client Id", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Client Id", "type": "string"} + ), + "client_secret": IsDict( + { + "title": "Client Secret", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Client Secret", "type": "string"} + ), }, }, "ValidationError": { diff --git a/tests/test_security_oauth2_password_bearer_optional.py b/tests/test_security_oauth2_password_bearer_optional.py index e5dcbb553d589..4c9362c3eb0a8 100644 --- a/tests/test_security_oauth2_password_bearer_optional.py +++ b/tests/test_security_oauth2_password_bearer_optional.py @@ -41,7 +41,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { diff --git a/tests/test_security_oauth2_password_bearer_optional_description.py b/tests/test_security_oauth2_password_bearer_optional_description.py index 9ff48e7156dc5..6e6ea846cd33d 100644 --- a/tests/test_security_oauth2_password_bearer_optional_description.py +++ b/tests/test_security_oauth2_password_bearer_optional_description.py @@ -45,7 +45,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { diff --git a/tests/test_security_openid_connect.py b/tests/test_security_openid_connect.py index 206de6574f893..1e322e640ed36 100644 --- a/tests/test_security_openid_connect.py +++ b/tests/test_security_openid_connect.py @@ -47,7 +47,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/me": { diff --git a/tests/test_security_openid_connect_description.py b/tests/test_security_openid_connect_description.py index 5884de7930817..44cf57f86281c 100644 --- a/tests/test_security_openid_connect_description.py +++ b/tests/test_security_openid_connect_description.py @@ -49,7 +49,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/me": { diff --git a/tests/test_security_openid_connect_optional.py b/tests/test_security_openid_connect_optional.py index 8ac719118320e..e817434b0dac9 100644 --- a/tests/test_security_openid_connect_optional.py +++ b/tests/test_security_openid_connect_optional.py @@ -53,7 +53,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/me": { diff --git a/tests/test_skip_defaults.py b/tests/test_skip_defaults.py index 181fff612ee7f..02765291cb7a7 100644 --- a/tests/test_skip_defaults.py +++ b/tests/test_skip_defaults.py @@ -12,7 +12,7 @@ class SubModel(BaseModel): class Model(BaseModel): - x: Optional[int] + x: Optional[int] = None sub: SubModel diff --git a/tests/test_starlette_exception.py b/tests/test_starlette_exception.py index 96f835b935aae..229fe801636d6 100644 --- a/tests/test_starlette_exception.py +++ b/tests/test_starlette_exception.py @@ -80,7 +80,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/http-no-body-statuscode-exception": { diff --git a/tests/test_sub_callbacks.py b/tests/test_sub_callbacks.py index c5a0237e80355..ed7f4efe8a360 100644 --- a/tests/test_sub_callbacks.py +++ b/tests/test_sub_callbacks.py @@ -1,5 +1,6 @@ from typing import Optional +from dirty_equals import IsDict from fastapi import APIRouter, FastAPI from fastapi.testclient import TestClient from pydantic import BaseModel, HttpUrl @@ -87,7 +88,7 @@ def test_openapi_schema(): with client: response = client.get("/openapi.json") assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/invoices/": { @@ -98,13 +99,30 @@ def test_openapi_schema(): "parameters": [ { "required": False, - "schema": { - "title": "Callback Url", - "maxLength": 2083, - "minLength": 1, - "type": "string", - "format": "uri", - }, + "schema": IsDict( + { + "title": "Callback Url", + "anyOf": [ + { + "type": "string", + "format": "uri", + "minLength": 1, + "maxLength": 2083, + }, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "Callback Url", + "maxLength": 2083, + "minLength": 1, + "type": "string", + "format": "uri", + } + ), "name": "callback_url", "in": "query", } @@ -244,7 +262,16 @@ def test_openapi_schema(): "type": "object", "properties": { "id": {"title": "Id", "type": "string"}, - "title": {"title": "Title", "type": "string"}, + "title": IsDict( + { + "title": "Title", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Title", "type": "string"} + ), "customer": {"title": "Customer", "type": "string"}, "total": {"title": "Total", "type": "number"}, }, diff --git a/tests/test_tuples.py b/tests/test_tuples.py index 4fa1f7a133e54..ca33d2580c2f9 100644 --- a/tests/test_tuples.py +++ b/tests/test_tuples.py @@ -1,5 +1,6 @@ from typing import List, Tuple +from dirty_equals import IsDict from fastapi import FastAPI, Form from fastapi.testclient import TestClient from pydantic import BaseModel @@ -86,7 +87,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/model-with-tuple/": { @@ -126,16 +127,31 @@ def test_openapi_schema(): "requestBody": { "content": { "application/json": { - "schema": { - "title": "Square", - "maxItems": 2, - "minItems": 2, - "type": "array", - "items": [ - {"$ref": "#/components/schemas/Coordinate"}, - {"$ref": "#/components/schemas/Coordinate"}, - ], - } + "schema": IsDict( + { + "title": "Square", + "maxItems": 2, + "minItems": 2, + "type": "array", + "prefixItems": [ + {"$ref": "#/components/schemas/Coordinate"}, + {"$ref": "#/components/schemas/Coordinate"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "Square", + "maxItems": 2, + "minItems": 2, + "type": "array", + "items": [ + {"$ref": "#/components/schemas/Coordinate"}, + {"$ref": "#/components/schemas/Coordinate"}, + ], + } + ) } }, "required": True, @@ -198,13 +214,28 @@ def test_openapi_schema(): "required": ["values"], "type": "object", "properties": { - "values": { - "title": "Values", - "maxItems": 2, - "minItems": 2, - "type": "array", - "items": [{"type": "integer"}, {"type": "integer"}], - } + "values": IsDict( + { + "title": "Values", + "maxItems": 2, + "minItems": 2, + "type": "array", + "prefixItems": [ + {"type": "integer"}, + {"type": "integer"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "Values", + "maxItems": 2, + "minItems": 2, + "type": "array", + "items": [{"type": "integer"}, {"type": "integer"}], + } + ) }, }, "Coordinate": { @@ -235,12 +266,26 @@ def test_openapi_schema(): "items": { "title": "Items", "type": "array", - "items": { - "maxItems": 2, - "minItems": 2, - "type": "array", - "items": [{"type": "string"}, {"type": "string"}], - }, + "items": IsDict( + { + "maxItems": 2, + "minItems": 2, + "type": "array", + "prefixItems": [ + {"type": "string"}, + {"type": "string"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "maxItems": 2, + "minItems": 2, + "type": "array", + "items": [{"type": "string"}, {"type": "string"}], + } + ), } }, }, diff --git a/tests/test_tutorial/test_additional_responses/test_tutorial001.py b/tests/test_tutorial/test_additional_responses/test_tutorial001.py index 3d6267023e246..3afeaff840691 100644 --- a/tests/test_tutorial/test_additional_responses/test_tutorial001.py +++ b/tests/test_tutorial/test_additional_responses/test_tutorial001.py @@ -21,7 +21,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { diff --git a/tests/test_tutorial/test_additional_responses/test_tutorial002.py b/tests/test_tutorial/test_additional_responses/test_tutorial002.py index 6182ed5079025..588a3160a93e9 100644 --- a/tests/test_tutorial/test_additional_responses/test_tutorial002.py +++ b/tests/test_tutorial/test_additional_responses/test_tutorial002.py @@ -1,6 +1,7 @@ import os import shutil +from dirty_equals import IsDict from fastapi.testclient import TestClient from docs_src.additional_responses.tutorial002 import app @@ -27,7 +28,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { @@ -64,7 +65,16 @@ def test_openapi_schema(): }, { "required": False, - "schema": {"title": "Img", "type": "boolean"}, + "schema": IsDict( + { + "anyOf": [{"type": "boolean"}, {"type": "null"}], + "title": "Img", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Img", "type": "boolean"} + ), "name": "img", "in": "query", }, diff --git a/tests/test_tutorial/test_additional_responses/test_tutorial003.py b/tests/test_tutorial/test_additional_responses/test_tutorial003.py index 77568d9d4f216..bd34d2938c455 100644 --- a/tests/test_tutorial/test_additional_responses/test_tutorial003.py +++ b/tests/test_tutorial/test_additional_responses/test_tutorial003.py @@ -21,7 +21,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { diff --git a/tests/test_tutorial/test_additional_responses/test_tutorial004.py b/tests/test_tutorial/test_additional_responses/test_tutorial004.py index 3fbd91e5c2a3c..55b556d8e19b8 100644 --- a/tests/test_tutorial/test_additional_responses/test_tutorial004.py +++ b/tests/test_tutorial/test_additional_responses/test_tutorial004.py @@ -1,6 +1,7 @@ import os import shutil +from dirty_equals import IsDict from fastapi.testclient import TestClient from docs_src.additional_responses.tutorial004 import app @@ -27,7 +28,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { @@ -67,7 +68,16 @@ def test_openapi_schema(): }, { "required": False, - "schema": {"title": "Img", "type": "boolean"}, + "schema": IsDict( + { + "anyOf": [{"type": "boolean"}, {"type": "null"}], + "title": "Img", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Img", "type": "boolean"} + ), "name": "img", "in": "query", }, diff --git a/tests/test_tutorial/test_async_sql_databases/test_tutorial001.py b/tests/test_tutorial/test_async_sql_databases/test_tutorial001.py index 3da362a50588e..13568a5328350 100644 --- a/tests/test_tutorial/test_async_sql_databases/test_tutorial001.py +++ b/tests/test_tutorial/test_async_sql_databases/test_tutorial001.py @@ -1,9 +1,20 @@ +import pytest +from fastapi import FastAPI from fastapi.testclient import TestClient -from docs_src.async_sql_databases.tutorial001 import app +from ...utils import needs_pydanticv1 -def test_create_read(): +@pytest.fixture(name="app", scope="module") +def get_app(): + with pytest.warns(DeprecationWarning): + from docs_src.async_sql_databases.tutorial001 import app + yield app + + +# TODO: pv2 add version with Pydantic v2 +@needs_pydanticv1 +def test_create_read(app: FastAPI): with TestClient(app) as client: note = {"text": "Foo bar", "completed": False} response = client.post("/notes/", json=note) @@ -17,12 +28,12 @@ def test_create_read(): assert data in response.json() -def test_openapi_schema(): +def test_openapi_schema(app: FastAPI): with TestClient(app) as client: response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/notes/": { diff --git a/tests/test_tutorial/test_behind_a_proxy/test_tutorial001.py b/tests/test_tutorial/test_behind_a_proxy/test_tutorial001.py index 7533a1b689e76..a070f850f7593 100644 --- a/tests/test_tutorial/test_behind_a_proxy/test_tutorial001.py +++ b/tests/test_tutorial/test_behind_a_proxy/test_tutorial001.py @@ -15,7 +15,7 @@ def test_openapi(): response = client.get("/openapi.json") assert response.status_code == 200 assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/app": { diff --git a/tests/test_tutorial/test_behind_a_proxy/test_tutorial002.py b/tests/test_tutorial/test_behind_a_proxy/test_tutorial002.py index 930ab3bf5c7d7..ce791e2157b31 100644 --- a/tests/test_tutorial/test_behind_a_proxy/test_tutorial002.py +++ b/tests/test_tutorial/test_behind_a_proxy/test_tutorial002.py @@ -15,7 +15,7 @@ def test_openapi(): response = client.get("/openapi.json") assert response.status_code == 200 assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/app": { diff --git a/tests/test_tutorial/test_behind_a_proxy/test_tutorial003.py b/tests/test_tutorial/test_behind_a_proxy/test_tutorial003.py index ae8f1a495dda6..ec17b4179001f 100644 --- a/tests/test_tutorial/test_behind_a_proxy/test_tutorial003.py +++ b/tests/test_tutorial/test_behind_a_proxy/test_tutorial003.py @@ -1,3 +1,4 @@ +from dirty_equals import IsOneOf from fastapi.testclient import TestClient from docs_src.behind_a_proxy.tutorial003 import app @@ -11,17 +12,28 @@ def test_main(): assert response.json() == {"message": "Hello World", "root_path": "/api/v1"} -def test_openapi(): +def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200 assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "servers": [ {"url": "/api/v1"}, - {"url": "https://stag.example.com", "description": "Staging environment"}, { - "url": "https://prod.example.com", + "url": IsOneOf( + "https://stag.example.com/", + # TODO: remove when deprecating Pydantic v1 + "https://stag.example.com", + ), + "description": "Staging environment", + }, + { + "url": IsOneOf( + "https://prod.example.com/", + # TODO: remove when deprecating Pydantic v1 + "https://prod.example.com", + ), "description": "Production environment", }, ], diff --git a/tests/test_tutorial/test_behind_a_proxy/test_tutorial004.py b/tests/test_tutorial/test_behind_a_proxy/test_tutorial004.py index e67ad1cb1fc07..2f8eb46995b29 100644 --- a/tests/test_tutorial/test_behind_a_proxy/test_tutorial004.py +++ b/tests/test_tutorial/test_behind_a_proxy/test_tutorial004.py @@ -1,3 +1,4 @@ +from dirty_equals import IsOneOf from fastapi.testclient import TestClient from docs_src.behind_a_proxy.tutorial004 import app @@ -11,16 +12,27 @@ def test_main(): assert response.json() == {"message": "Hello World", "root_path": "/api/v1"} -def test_openapi(): +def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200 assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "servers": [ - {"url": "https://stag.example.com", "description": "Staging environment"}, { - "url": "https://prod.example.com", + "url": IsOneOf( + "https://stag.example.com/", + # TODO: remove when deprecating Pydantic v1 + "https://stag.example.com", + ), + "description": "Staging environment", + }, + { + "url": IsOneOf( + "https://prod.example.com/", + # TODO: remove when deprecating Pydantic v1 + "https://prod.example.com", + ), "description": "Production environment", }, ], diff --git a/tests/test_tutorial/test_bigger_applications/test_main.py b/tests/test_tutorial/test_bigger_applications/test_main.py index a13decd75b86d..526e265a612a4 100644 --- a/tests/test_tutorial/test_bigger_applications/test_main.py +++ b/tests/test_tutorial/test_bigger_applications/test_main.py @@ -1,138 +1,368 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url -from docs_src.bigger_applications.app.main import app -client = TestClient(app) +@pytest.fixture(name="client") +def get_client(): + from docs_src.bigger_applications.app.main import app + client = TestClient(app) + return client -no_jessica = { - "detail": [ + +def test_users_token_jessica(client: TestClient): + response = client.get("/users?token=jessica") + assert response.status_code == 200 + assert response.json() == [{"username": "Rick"}, {"username": "Morty"}] + + +def test_users_with_no_token(client: TestClient): + response = client.get("/users") + assert response.status_code == 422 + assert response.json() == IsDict( { - "loc": ["query", "token"], - "msg": "field required", - "type": "value_error.missing", - }, - ] -} - - -@pytest.mark.parametrize( - "path,expected_status,expected_response,headers", - [ - ( - "/users?token=jessica", - 200, - [{"username": "Rick"}, {"username": "Morty"}], - {}, - ), - ("/users", 422, no_jessica, {}), - ("/users/foo?token=jessica", 200, {"username": "foo"}, {}), - ("/users/foo", 422, no_jessica, {}), - ("/users/me?token=jessica", 200, {"username": "fakecurrentuser"}, {}), - ("/users/me", 422, no_jessica, {}), - ( - "/users?token=monica", - 400, - {"detail": "No Jessica token provided"}, - {}, - ), - ( - "/items?token=jessica", - 200, - {"plumbus": {"name": "Plumbus"}, "gun": {"name": "Portal Gun"}}, - {"X-Token": "fake-super-secret-token"}, - ), - ("/items", 422, no_jessica, {"X-Token": "fake-super-secret-token"}), - ( - "/items/plumbus?token=jessica", - 200, - {"name": "Plumbus", "item_id": "plumbus"}, - {"X-Token": "fake-super-secret-token"}, - ), - ( - "/items/bar?token=jessica", - 404, - {"detail": "Item not found"}, - {"X-Token": "fake-super-secret-token"}, - ), - ("/items/plumbus", 422, no_jessica, {"X-Token": "fake-super-secret-token"}), - ( - "/items?token=jessica", - 400, - {"detail": "X-Token header invalid"}, - {"X-Token": "invalid"}, - ), - ( - "/items/bar?token=jessica", - 400, - {"detail": "X-Token header invalid"}, - {"X-Token": "invalid"}, - ), - ( - "/items?token=jessica", - 422, - { - "detail": [ - { - "loc": ["header", "x-token"], - "msg": "field required", - "type": "value_error.missing", - } - ] - }, - {}, - ), - ( - "/items/plumbus?token=jessica", - 422, - { - "detail": [ - { - "loc": ["header", "x-token"], - "msg": "field required", - "type": "value_error.missing", - } - ] - }, - {}, - ), - ("/?token=jessica", 200, {"message": "Hello Bigger Applications!"}, {}), - ("/", 422, no_jessica, {}), - ], -) -def test_get_path(path, expected_status, expected_response, headers): - response = client.get(path, headers=headers) - assert response.status_code == expected_status - assert response.json() == expected_response - - -def test_put_no_header(): - response = client.put("/items/foo") - assert response.status_code == 422, response.text + "detail": [ + { + "type": "missing", + "loc": ["query", "token"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["query", "token"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) + + +def test_users_foo_token_jessica(client: TestClient): + response = client.get("/users/foo?token=jessica") + assert response.status_code == 200 + assert response.json() == {"username": "foo"} + + +def test_users_foo_with_no_token(client: TestClient): + response = client.get("/users/foo") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["query", "token"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["query", "token"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) + + +def test_users_me_token_jessica(client: TestClient): + response = client.get("/users/me?token=jessica") + assert response.status_code == 200 + assert response.json() == {"username": "fakecurrentuser"} + + +def test_users_me_with_no_token(client: TestClient): + response = client.get("/users/me") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["query", "token"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["query", "token"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) + + +def test_users_token_monica_with_no_jessica(client: TestClient): + response = client.get("/users?token=monica") + assert response.status_code == 400 + assert response.json() == {"detail": "No Jessica token provided"} + + +def test_items_token_jessica(client: TestClient): + response = client.get( + "/items?token=jessica", headers={"X-Token": "fake-super-secret-token"} + ) + assert response.status_code == 200 assert response.json() == { - "detail": [ - { - "loc": ["query", "token"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["header", "x-token"], - "msg": "field required", - "type": "value_error.missing", - }, - ] + "plumbus": {"name": "Plumbus"}, + "gun": {"name": "Portal Gun"}, } -def test_put_invalid_header(): +def test_items_with_no_token_jessica(client: TestClient): + response = client.get("/items", headers={"X-Token": "fake-super-secret-token"}) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["query", "token"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["query", "token"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) + + +def test_items_plumbus_token_jessica(client: TestClient): + response = client.get( + "/items/plumbus?token=jessica", headers={"X-Token": "fake-super-secret-token"} + ) + assert response.status_code == 200 + assert response.json() == {"name": "Plumbus", "item_id": "plumbus"} + + +def test_items_bar_token_jessica(client: TestClient): + response = client.get( + "/items/bar?token=jessica", headers={"X-Token": "fake-super-secret-token"} + ) + assert response.status_code == 404 + assert response.json() == {"detail": "Item not found"} + + +def test_items_plumbus_with_no_token(client: TestClient): + response = client.get( + "/items/plumbus", headers={"X-Token": "fake-super-secret-token"} + ) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["query", "token"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["query", "token"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) + + +def test_items_with_invalid_token(client: TestClient): + response = client.get("/items?token=jessica", headers={"X-Token": "invalid"}) + assert response.status_code == 400 + assert response.json() == {"detail": "X-Token header invalid"} + + +def test_items_bar_with_invalid_token(client: TestClient): + response = client.get("/items/bar?token=jessica", headers={"X-Token": "invalid"}) + assert response.status_code == 400 + assert response.json() == {"detail": "X-Token header invalid"} + + +def test_items_with_missing_x_token_header(client: TestClient): + response = client.get("/items?token=jessica") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["header", "x-token"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["header", "x-token"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) + + +def test_items_plumbus_with_missing_x_token_header(client: TestClient): + response = client.get("/items/plumbus?token=jessica") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["header", "x-token"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["header", "x-token"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) + + +def test_root_token_jessica(client: TestClient): + response = client.get("/?token=jessica") + assert response.status_code == 200 + assert response.json() == {"message": "Hello Bigger Applications!"} + + +def test_root_with_no_token(client: TestClient): + response = client.get("/") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["query", "token"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["query", "token"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) + + +def test_put_no_header(client: TestClient): + response = client.put("/items/foo") + assert response.status_code == 422, response.text + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["query", "token"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["header", "x-token"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["query", "token"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["header", "x-token"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) + + +def test_put_invalid_header(client: TestClient): response = client.put("/items/foo", headers={"X-Token": "invalid"}) assert response.status_code == 400, response.text assert response.json() == {"detail": "X-Token header invalid"} -def test_put(): +def test_put(client: TestClient): response = client.put( "/items/plumbus?token=jessica", headers={"X-Token": "fake-super-secret-token"} ) @@ -140,7 +370,7 @@ def test_put(): assert response.json() == {"item_id": "plumbus", "name": "The great Plumbus"} -def test_put_forbidden(): +def test_put_forbidden(client: TestClient): response = client.put( "/items/bar?token=jessica", headers={"X-Token": "fake-super-secret-token"} ) @@ -148,7 +378,7 @@ def test_put_forbidden(): assert response.json() == {"detail": "You can only update the item: plumbus"} -def test_admin(): +def test_admin(client: TestClient): response = client.post( "/admin/?token=jessica", headers={"X-Token": "fake-super-secret-token"} ) @@ -156,17 +386,17 @@ def test_admin(): assert response.json() == {"message": "Admin getting schwifty"} -def test_admin_invalid_header(): +def test_admin_invalid_header(client: TestClient): response = client.post("/admin/", headers={"X-Token": "invalid"}) assert response.status_code == 400, response.text assert response.json() == {"detail": "X-Token header invalid"} -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/": { diff --git a/tests/test_tutorial/test_bigger_applications/test_main_an.py b/tests/test_tutorial/test_bigger_applications/test_main_an.py index 64e19c3f391c0..c0b77d4a72242 100644 --- a/tests/test_tutorial/test_bigger_applications/test_main_an.py +++ b/tests/test_tutorial/test_bigger_applications/test_main_an.py @@ -1,138 +1,368 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url -from docs_src.bigger_applications.app_an.main import app -client = TestClient(app) +@pytest.fixture(name="client") +def get_client(): + from docs_src.bigger_applications.app_an.main import app + client = TestClient(app) + return client -no_jessica = { - "detail": [ + +def test_users_token_jessica(client: TestClient): + response = client.get("/users?token=jessica") + assert response.status_code == 200 + assert response.json() == [{"username": "Rick"}, {"username": "Morty"}] + + +def test_users_with_no_token(client: TestClient): + response = client.get("/users") + assert response.status_code == 422 + assert response.json() == IsDict( { - "loc": ["query", "token"], - "msg": "field required", - "type": "value_error.missing", - }, - ] -} - - -@pytest.mark.parametrize( - "path,expected_status,expected_response,headers", - [ - ( - "/users?token=jessica", - 200, - [{"username": "Rick"}, {"username": "Morty"}], - {}, - ), - ("/users", 422, no_jessica, {}), - ("/users/foo?token=jessica", 200, {"username": "foo"}, {}), - ("/users/foo", 422, no_jessica, {}), - ("/users/me?token=jessica", 200, {"username": "fakecurrentuser"}, {}), - ("/users/me", 422, no_jessica, {}), - ( - "/users?token=monica", - 400, - {"detail": "No Jessica token provided"}, - {}, - ), - ( - "/items?token=jessica", - 200, - {"plumbus": {"name": "Plumbus"}, "gun": {"name": "Portal Gun"}}, - {"X-Token": "fake-super-secret-token"}, - ), - ("/items", 422, no_jessica, {"X-Token": "fake-super-secret-token"}), - ( - "/items/plumbus?token=jessica", - 200, - {"name": "Plumbus", "item_id": "plumbus"}, - {"X-Token": "fake-super-secret-token"}, - ), - ( - "/items/bar?token=jessica", - 404, - {"detail": "Item not found"}, - {"X-Token": "fake-super-secret-token"}, - ), - ("/items/plumbus", 422, no_jessica, {"X-Token": "fake-super-secret-token"}), - ( - "/items?token=jessica", - 400, - {"detail": "X-Token header invalid"}, - {"X-Token": "invalid"}, - ), - ( - "/items/bar?token=jessica", - 400, - {"detail": "X-Token header invalid"}, - {"X-Token": "invalid"}, - ), - ( - "/items?token=jessica", - 422, - { - "detail": [ - { - "loc": ["header", "x-token"], - "msg": "field required", - "type": "value_error.missing", - } - ] - }, - {}, - ), - ( - "/items/plumbus?token=jessica", - 422, - { - "detail": [ - { - "loc": ["header", "x-token"], - "msg": "field required", - "type": "value_error.missing", - } - ] - }, - {}, - ), - ("/?token=jessica", 200, {"message": "Hello Bigger Applications!"}, {}), - ("/", 422, no_jessica, {}), - ], -) -def test_get_path(path, expected_status, expected_response, headers): - response = client.get(path, headers=headers) - assert response.status_code == expected_status - assert response.json() == expected_response - - -def test_put_no_header(): - response = client.put("/items/foo") - assert response.status_code == 422, response.text + "detail": [ + { + "type": "missing", + "loc": ["query", "token"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["query", "token"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) + + +def test_users_foo_token_jessica(client: TestClient): + response = client.get("/users/foo?token=jessica") + assert response.status_code == 200 + assert response.json() == {"username": "foo"} + + +def test_users_foo_with_no_token(client: TestClient): + response = client.get("/users/foo") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["query", "token"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["query", "token"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) + + +def test_users_me_token_jessica(client: TestClient): + response = client.get("/users/me?token=jessica") + assert response.status_code == 200 + assert response.json() == {"username": "fakecurrentuser"} + + +def test_users_me_with_no_token(client: TestClient): + response = client.get("/users/me") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["query", "token"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["query", "token"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) + + +def test_users_token_monica_with_no_jessica(client: TestClient): + response = client.get("/users?token=monica") + assert response.status_code == 400 + assert response.json() == {"detail": "No Jessica token provided"} + + +def test_items_token_jessica(client: TestClient): + response = client.get( + "/items?token=jessica", headers={"X-Token": "fake-super-secret-token"} + ) + assert response.status_code == 200 assert response.json() == { - "detail": [ - { - "loc": ["query", "token"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["header", "x-token"], - "msg": "field required", - "type": "value_error.missing", - }, - ] + "plumbus": {"name": "Plumbus"}, + "gun": {"name": "Portal Gun"}, } -def test_put_invalid_header(): +def test_items_with_no_token_jessica(client: TestClient): + response = client.get("/items", headers={"X-Token": "fake-super-secret-token"}) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["query", "token"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["query", "token"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) + + +def test_items_plumbus_token_jessica(client: TestClient): + response = client.get( + "/items/plumbus?token=jessica", headers={"X-Token": "fake-super-secret-token"} + ) + assert response.status_code == 200 + assert response.json() == {"name": "Plumbus", "item_id": "plumbus"} + + +def test_items_bar_token_jessica(client: TestClient): + response = client.get( + "/items/bar?token=jessica", headers={"X-Token": "fake-super-secret-token"} + ) + assert response.status_code == 404 + assert response.json() == {"detail": "Item not found"} + + +def test_items_plumbus_with_no_token(client: TestClient): + response = client.get( + "/items/plumbus", headers={"X-Token": "fake-super-secret-token"} + ) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["query", "token"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["query", "token"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) + + +def test_items_with_invalid_token(client: TestClient): + response = client.get("/items?token=jessica", headers={"X-Token": "invalid"}) + assert response.status_code == 400 + assert response.json() == {"detail": "X-Token header invalid"} + + +def test_items_bar_with_invalid_token(client: TestClient): + response = client.get("/items/bar?token=jessica", headers={"X-Token": "invalid"}) + assert response.status_code == 400 + assert response.json() == {"detail": "X-Token header invalid"} + + +def test_items_with_missing_x_token_header(client: TestClient): + response = client.get("/items?token=jessica") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["header", "x-token"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["header", "x-token"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) + + +def test_items_plumbus_with_missing_x_token_header(client: TestClient): + response = client.get("/items/plumbus?token=jessica") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["header", "x-token"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["header", "x-token"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) + + +def test_root_token_jessica(client: TestClient): + response = client.get("/?token=jessica") + assert response.status_code == 200 + assert response.json() == {"message": "Hello Bigger Applications!"} + + +def test_root_with_no_token(client: TestClient): + response = client.get("/") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["query", "token"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["query", "token"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) + + +def test_put_no_header(client: TestClient): + response = client.put("/items/foo") + assert response.status_code == 422, response.text + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["query", "token"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["header", "x-token"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["query", "token"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["header", "x-token"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) + + +def test_put_invalid_header(client: TestClient): response = client.put("/items/foo", headers={"X-Token": "invalid"}) assert response.status_code == 400, response.text assert response.json() == {"detail": "X-Token header invalid"} -def test_put(): +def test_put(client: TestClient): response = client.put( "/items/plumbus?token=jessica", headers={"X-Token": "fake-super-secret-token"} ) @@ -140,7 +370,7 @@ def test_put(): assert response.json() == {"item_id": "plumbus", "name": "The great Plumbus"} -def test_put_forbidden(): +def test_put_forbidden(client: TestClient): response = client.put( "/items/bar?token=jessica", headers={"X-Token": "fake-super-secret-token"} ) @@ -148,7 +378,7 @@ def test_put_forbidden(): assert response.json() == {"detail": "You can only update the item: plumbus"} -def test_admin(): +def test_admin(client: TestClient): response = client.post( "/admin/?token=jessica", headers={"X-Token": "fake-super-secret-token"} ) @@ -156,17 +386,17 @@ def test_admin(): assert response.json() == {"message": "Admin getting schwifty"} -def test_admin_invalid_header(): +def test_admin_invalid_header(client: TestClient): response = client.post("/admin/", headers={"X-Token": "invalid"}) assert response.status_code == 400, response.text assert response.json() == {"detail": "X-Token header invalid"} -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/": { diff --git a/tests/test_tutorial/test_bigger_applications/test_main_an_py39.py b/tests/test_tutorial/test_bigger_applications/test_main_an_py39.py index 70c86b4d7f200..948331b5ddfd3 100644 --- a/tests/test_tutorial/test_bigger_applications/test_main_an_py39.py +++ b/tests/test_tutorial/test_bigger_applications/test_main_an_py39.py @@ -1,18 +1,10 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url from ...utils import needs_py39 -no_jessica = { - "detail": [ - { - "loc": ["query", "token"], - "msg": "field required", - "type": "value_error.missing", - }, - ] -} - @pytest.fixture(name="client") def get_client(): @@ -23,116 +15,366 @@ def get_client(): @needs_py39 -@pytest.mark.parametrize( - "path,expected_status,expected_response,headers", - [ - ( - "/users?token=jessica", - 200, - [{"username": "Rick"}, {"username": "Morty"}], - {}, - ), - ("/users", 422, no_jessica, {}), - ("/users/foo?token=jessica", 200, {"username": "foo"}, {}), - ("/users/foo", 422, no_jessica, {}), - ("/users/me?token=jessica", 200, {"username": "fakecurrentuser"}, {}), - ("/users/me", 422, no_jessica, {}), - ( - "/users?token=monica", - 400, - {"detail": "No Jessica token provided"}, - {}, - ), - ( - "/items?token=jessica", - 200, - {"plumbus": {"name": "Plumbus"}, "gun": {"name": "Portal Gun"}}, - {"X-Token": "fake-super-secret-token"}, - ), - ("/items", 422, no_jessica, {"X-Token": "fake-super-secret-token"}), - ( - "/items/plumbus?token=jessica", - 200, - {"name": "Plumbus", "item_id": "plumbus"}, - {"X-Token": "fake-super-secret-token"}, - ), - ( - "/items/bar?token=jessica", - 404, - {"detail": "Item not found"}, - {"X-Token": "fake-super-secret-token"}, - ), - ("/items/plumbus", 422, no_jessica, {"X-Token": "fake-super-secret-token"}), - ( - "/items?token=jessica", - 400, - {"detail": "X-Token header invalid"}, - {"X-Token": "invalid"}, - ), - ( - "/items/bar?token=jessica", - 400, - {"detail": "X-Token header invalid"}, - {"X-Token": "invalid"}, - ), - ( - "/items?token=jessica", - 422, - { - "detail": [ - { - "loc": ["header", "x-token"], - "msg": "field required", - "type": "value_error.missing", - } - ] - }, - {}, - ), - ( - "/items/plumbus?token=jessica", - 422, - { - "detail": [ - { - "loc": ["header", "x-token"], - "msg": "field required", - "type": "value_error.missing", - } - ] - }, - {}, - ), - ("/?token=jessica", 200, {"message": "Hello Bigger Applications!"}, {}), - ("/", 422, no_jessica, {}), - ], -) -def test_get_path( - path, expected_status, expected_response, headers, client: TestClient -): - response = client.get(path, headers=headers) - assert response.status_code == expected_status - assert response.json() == expected_response +def test_users_token_jessica(client: TestClient): + response = client.get("/users?token=jessica") + assert response.status_code == 200 + assert response.json() == [{"username": "Rick"}, {"username": "Morty"}] + + +@needs_py39 +def test_users_with_no_token(client: TestClient): + response = client.get("/users") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["query", "token"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["query", "token"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) + + +@needs_py39 +def test_users_foo_token_jessica(client: TestClient): + response = client.get("/users/foo?token=jessica") + assert response.status_code == 200 + assert response.json() == {"username": "foo"} + + +@needs_py39 +def test_users_foo_with_no_token(client: TestClient): + response = client.get("/users/foo") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["query", "token"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["query", "token"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) + + +@needs_py39 +def test_users_me_token_jessica(client: TestClient): + response = client.get("/users/me?token=jessica") + assert response.status_code == 200 + assert response.json() == {"username": "fakecurrentuser"} + + +@needs_py39 +def test_users_me_with_no_token(client: TestClient): + response = client.get("/users/me") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["query", "token"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["query", "token"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) + + +@needs_py39 +def test_users_token_monica_with_no_jessica(client: TestClient): + response = client.get("/users?token=monica") + assert response.status_code == 400 + assert response.json() == {"detail": "No Jessica token provided"} + + +@needs_py39 +def test_items_token_jessica(client: TestClient): + response = client.get( + "/items?token=jessica", headers={"X-Token": "fake-super-secret-token"} + ) + assert response.status_code == 200 + assert response.json() == { + "plumbus": {"name": "Plumbus"}, + "gun": {"name": "Portal Gun"}, + } + + +@needs_py39 +def test_items_with_no_token_jessica(client: TestClient): + response = client.get("/items", headers={"X-Token": "fake-super-secret-token"}) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["query", "token"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["query", "token"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) + + +@needs_py39 +def test_items_plumbus_token_jessica(client: TestClient): + response = client.get( + "/items/plumbus?token=jessica", headers={"X-Token": "fake-super-secret-token"} + ) + assert response.status_code == 200 + assert response.json() == {"name": "Plumbus", "item_id": "plumbus"} + + +@needs_py39 +def test_items_bar_token_jessica(client: TestClient): + response = client.get( + "/items/bar?token=jessica", headers={"X-Token": "fake-super-secret-token"} + ) + assert response.status_code == 404 + assert response.json() == {"detail": "Item not found"} + + +@needs_py39 +def test_items_plumbus_with_no_token(client: TestClient): + response = client.get( + "/items/plumbus", headers={"X-Token": "fake-super-secret-token"} + ) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["query", "token"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["query", "token"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) + + +@needs_py39 +def test_items_with_invalid_token(client: TestClient): + response = client.get("/items?token=jessica", headers={"X-Token": "invalid"}) + assert response.status_code == 400 + assert response.json() == {"detail": "X-Token header invalid"} + + +@needs_py39 +def test_items_bar_with_invalid_token(client: TestClient): + response = client.get("/items/bar?token=jessica", headers={"X-Token": "invalid"}) + assert response.status_code == 400 + assert response.json() == {"detail": "X-Token header invalid"} + + +@needs_py39 +def test_items_with_missing_x_token_header(client: TestClient): + response = client.get("/items?token=jessica") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["header", "x-token"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["header", "x-token"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) + + +@needs_py39 +def test_items_plumbus_with_missing_x_token_header(client: TestClient): + response = client.get("/items/plumbus?token=jessica") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["header", "x-token"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["header", "x-token"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) + + +@needs_py39 +def test_root_token_jessica(client: TestClient): + response = client.get("/?token=jessica") + assert response.status_code == 200 + assert response.json() == {"message": "Hello Bigger Applications!"} + + +@needs_py39 +def test_root_with_no_token(client: TestClient): + response = client.get("/") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["query", "token"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["query", "token"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) @needs_py39 def test_put_no_header(client: TestClient): response = client.put("/items/foo") assert response.status_code == 422, response.text - assert response.json() == { - "detail": [ - { - "loc": ["query", "token"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["header", "x-token"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["query", "token"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["header", "x-token"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["query", "token"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["header", "x-token"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) @needs_py39 @@ -181,7 +423,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/": { diff --git a/tests/test_tutorial/test_body/test_tutorial001.py b/tests/test_tutorial/test_body/test_tutorial001.py index cd1209adea5aa..2476b773f4070 100644 --- a/tests/test_tutorial/test_body/test_tutorial001.py +++ b/tests/test_tutorial/test_body/test_tutorial001.py @@ -1,134 +1,268 @@ from unittest.mock import patch import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url -from docs_src.body.tutorial001 import app -client = TestClient(app) +@pytest.fixture +def client(): + from docs_src.body.tutorial001 import app + client = TestClient(app) + return client -price_missing = { - "detail": [ + +def test_body_float(client: TestClient): + response = client.post("/items/", json={"name": "Foo", "price": 50.5}) + assert response.status_code == 200 + assert response.json() == { + "name": "Foo", + "price": 50.5, + "description": None, + "tax": None, + } + + +def test_post_with_str_float(client: TestClient): + response = client.post("/items/", json={"name": "Foo", "price": "50.5"}) + assert response.status_code == 200 + assert response.json() == { + "name": "Foo", + "price": 50.5, + "description": None, + "tax": None, + } + + +def test_post_with_str_float_description(client: TestClient): + response = client.post( + "/items/", json={"name": "Foo", "price": "50.5", "description": "Some Foo"} + ) + assert response.status_code == 200 + assert response.json() == { + "name": "Foo", + "price": 50.5, + "description": "Some Foo", + "tax": None, + } + + +def test_post_with_str_float_description_tax(client: TestClient): + response = client.post( + "/items/", + json={"name": "Foo", "price": "50.5", "description": "Some Foo", "tax": 0.3}, + ) + assert response.status_code == 200 + assert response.json() == { + "name": "Foo", + "price": 50.5, + "description": "Some Foo", + "tax": 0.3, + } + + +def test_post_with_only_name(client: TestClient): + response = client.post("/items/", json={"name": "Foo"}) + assert response.status_code == 422 + assert response.json() == IsDict( { - "loc": ["body", "price"], - "msg": "field required", - "type": "value_error.missing", + "detail": [ + { + "type": "missing", + "loc": ["body", "price"], + "msg": "Field required", + "input": {"name": "Foo"}, + "url": match_pydantic_error_url("missing"), + } + ] } - ] -} + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "price"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) + -price_not_float = { - "detail": [ +def test_post_with_only_name_price(client: TestClient): + response = client.post("/items/", json={"name": "Foo", "price": "twenty"}) + assert response.status_code == 422 + assert response.json() == IsDict( { - "loc": ["body", "price"], - "msg": "value is not a valid float", - "type": "type_error.float", + "detail": [ + { + "type": "float_parsing", + "loc": ["body", "price"], + "msg": "Input should be a valid number, unable to parse string as a number", + "input": "twenty", + "url": match_pydantic_error_url("float_parsing"), + } + ] } - ] -} + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "price"], + "msg": "value is not a valid float", + "type": "type_error.float", + } + ] + } + ) -name_price_missing = { - "detail": [ + +def test_post_with_no_data(client: TestClient): + response = client.post("/items/", json={}) + assert response.status_code == 422 + assert response.json() == IsDict( { - "loc": ["body", "name"], - "msg": "field required", - "type": "value_error.missing", - }, + "detail": [ + { + "type": "missing", + "loc": ["body", "name"], + "msg": "Field required", + "input": {}, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "price"], + "msg": "Field required", + "input": {}, + "url": match_pydantic_error_url("missing"), + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 { - "loc": ["body", "price"], - "msg": "field required", - "type": "value_error.missing", - }, - ] -} - -body_missing = { - "detail": [ - {"loc": ["body"], "msg": "field required", "type": "value_error.missing"} - ] -} - - -@pytest.mark.parametrize( - "path,body,expected_status,expected_response", - [ - ( - "/items/", - {"name": "Foo", "price": 50.5}, - 200, - {"name": "Foo", "price": 50.5, "description": None, "tax": None}, - ), - ( - "/items/", - {"name": "Foo", "price": "50.5"}, - 200, - {"name": "Foo", "price": 50.5, "description": None, "tax": None}, - ), - ( - "/items/", - {"name": "Foo", "price": "50.5", "description": "Some Foo"}, - 200, - {"name": "Foo", "price": 50.5, "description": "Some Foo", "tax": None}, - ), - ( - "/items/", - {"name": "Foo", "price": "50.5", "description": "Some Foo", "tax": 0.3}, - 200, - {"name": "Foo", "price": 50.5, "description": "Some Foo", "tax": 0.3}, - ), - ("/items/", {"name": "Foo"}, 422, price_missing), - ("/items/", {"name": "Foo", "price": "twenty"}, 422, price_not_float), - ("/items/", {}, 422, name_price_missing), - ("/items/", None, 422, body_missing), - ], -) -def test_post_body(path, body, expected_status, expected_response): - response = client.post(path, json=body) - assert response.status_code == expected_status - assert response.json() == expected_response - - -def test_post_broken_body(): + "detail": [ + { + "loc": ["body", "name"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "price"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) + + +def test_post_with_none(client: TestClient): + response = client.post("/items/", json=None) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) + + +def test_post_broken_body(client: TestClient): response = client.post( "/items/", headers={"content-type": "application/json"}, content="{some broken json}", ) assert response.status_code == 422, response.text - assert response.json() == { - "detail": [ - { - "loc": ["body", 1], - "msg": "Expecting property name enclosed in double quotes: line 1 column 2 (char 1)", - "type": "value_error.jsondecode", - "ctx": { - "msg": "Expecting property name enclosed in double quotes", - "doc": "{some broken json}", - "pos": 1, - "lineno": 1, - "colno": 2, - }, - } - ] - } + assert response.json() == IsDict( + { + "detail": [ + { + "type": "json_invalid", + "loc": ["body", 1], + "msg": "JSON decode error", + "input": {}, + "ctx": { + "error": "Expecting property name enclosed in double quotes" + }, + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", 1], + "msg": "Expecting property name enclosed in double quotes: line 1 column 2 (char 1)", + "type": "value_error.jsondecode", + "ctx": { + "msg": "Expecting property name enclosed in double quotes", + "doc": "{some broken json}", + "pos": 1, + "lineno": 1, + "colno": 2, + }, + } + ] + } + ) -def test_post_form_for_json(): +def test_post_form_for_json(client: TestClient): response = client.post("/items/", data={"name": "Foo", "price": 50.5}) assert response.status_code == 422, response.text - assert response.json() == { - "detail": [ - { - "loc": ["body"], - "msg": "value is not a valid dict", - "type": "type_error.dict", - } - ] - } + assert response.json() == IsDict( + { + "detail": [ + { + "type": "model_attributes_type", + "loc": ["body"], + "msg": "Input should be a valid dictionary or object to extract fields from", + "input": "name=Foo&price=50.5", + "url": match_pydantic_error_url("model_attributes_type"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body"], + "msg": "value is not a valid dict", + "type": "type_error.dict", + } + ] + } + ) -def test_explicit_content_type(): +def test_explicit_content_type(client: TestClient): response = client.post( "/items/", content='{"name": "Foo", "price": 50.5}', @@ -137,7 +271,7 @@ def test_explicit_content_type(): assert response.status_code == 200, response.text -def test_geo_json(): +def test_geo_json(client: TestClient): response = client.post( "/items/", content='{"name": "Foo", "price": 50.5}', @@ -146,7 +280,7 @@ def test_geo_json(): assert response.status_code == 200, response.text -def test_no_content_type_is_json(): +def test_no_content_type_is_json(client: TestClient): response = client.post( "/items/", content='{"name": "Foo", "price": 50.5}', @@ -160,47 +294,108 @@ def test_no_content_type_is_json(): } -def test_wrong_headers(): +def test_wrong_headers(client: TestClient): data = '{"name": "Foo", "price": 50.5}' - invalid_dict = { - "detail": [ - { - "loc": ["body"], - "msg": "value is not a valid dict", - "type": "type_error.dict", - } - ] - } - response = client.post( "/items/", content=data, headers={"Content-Type": "text/plain"} ) assert response.status_code == 422, response.text - assert response.json() == invalid_dict + assert response.json() == IsDict( + { + "detail": [ + { + "type": "model_attributes_type", + "loc": ["body"], + "msg": "Input should be a valid dictionary or object to extract fields from", + "input": '{"name": "Foo", "price": 50.5}', + "url": match_pydantic_error_url( + "model_attributes_type" + ), # "https://errors.pydantic.dev/0.38.0/v/dict_attributes_type", + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body"], + "msg": "value is not a valid dict", + "type": "type_error.dict", + } + ] + } + ) response = client.post( "/items/", content=data, headers={"Content-Type": "application/geo+json-seq"} ) assert response.status_code == 422, response.text - assert response.json() == invalid_dict + assert response.json() == IsDict( + { + "detail": [ + { + "type": "model_attributes_type", + "loc": ["body"], + "msg": "Input should be a valid dictionary or object to extract fields from", + "input": '{"name": "Foo", "price": 50.5}', + "url": match_pydantic_error_url("model_attributes_type"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body"], + "msg": "value is not a valid dict", + "type": "type_error.dict", + } + ] + } + ) response = client.post( "/items/", content=data, headers={"Content-Type": "application/not-really-json"} ) assert response.status_code == 422, response.text - assert response.json() == invalid_dict + assert response.json() == IsDict( + { + "detail": [ + { + "type": "model_attributes_type", + "loc": ["body"], + "msg": "Input should be a valid dictionary or object to extract fields from", + "input": '{"name": "Foo", "price": 50.5}', + "url": match_pydantic_error_url("model_attributes_type"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body"], + "msg": "value is not a valid dict", + "type": "type_error.dict", + } + ] + } + ) -def test_other_exceptions(): +def test_other_exceptions(client: TestClient): with patch("json.loads", side_effect=Exception): response = client.post("/items/", json={"test": "test2"}) assert response.status_code == 400, response.text -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { @@ -243,8 +438,26 @@ def test_openapi_schema(): "properties": { "name": {"title": "Name", "type": "string"}, "price": {"title": "Price", "type": "number"}, - "description": {"title": "Description", "type": "string"}, - "tax": {"title": "Tax", "type": "number"}, + "description": IsDict( + { + "title": "Description", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Description", "type": "string"} + ), + "tax": IsDict( + { + "title": "Tax", + "anyOf": [{"type": "number"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Tax", "type": "number"} + ), }, }, "ValidationError": { diff --git a/tests/test_tutorial/test_body/test_tutorial001_py310.py b/tests/test_tutorial/test_body/test_tutorial001_py310.py index 5ebcbbf574aa7..b64d860053515 100644 --- a/tests/test_tutorial/test_body/test_tutorial001_py310.py +++ b/tests/test_tutorial/test_body/test_tutorial001_py310.py @@ -1,7 +1,9 @@ from unittest.mock import patch import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url from ...utils import needs_py310 @@ -14,86 +16,189 @@ def client(): return client -price_missing = { - "detail": [ +@needs_py310 +def test_body_float(client: TestClient): + response = client.post("/items/", json={"name": "Foo", "price": 50.5}) + assert response.status_code == 200 + assert response.json() == { + "name": "Foo", + "price": 50.5, + "description": None, + "tax": None, + } + + +@needs_py310 +def test_post_with_str_float(client: TestClient): + response = client.post("/items/", json={"name": "Foo", "price": "50.5"}) + assert response.status_code == 200 + assert response.json() == { + "name": "Foo", + "price": 50.5, + "description": None, + "tax": None, + } + + +@needs_py310 +def test_post_with_str_float_description(client: TestClient): + response = client.post( + "/items/", json={"name": "Foo", "price": "50.5", "description": "Some Foo"} + ) + assert response.status_code == 200 + assert response.json() == { + "name": "Foo", + "price": 50.5, + "description": "Some Foo", + "tax": None, + } + + +@needs_py310 +def test_post_with_str_float_description_tax(client: TestClient): + response = client.post( + "/items/", + json={"name": "Foo", "price": "50.5", "description": "Some Foo", "tax": 0.3}, + ) + assert response.status_code == 200 + assert response.json() == { + "name": "Foo", + "price": 50.5, + "description": "Some Foo", + "tax": 0.3, + } + + +@needs_py310 +def test_post_with_only_name(client: TestClient): + response = client.post("/items/", json={"name": "Foo"}) + assert response.status_code == 422 + assert response.json() == IsDict( { - "loc": ["body", "price"], - "msg": "field required", - "type": "value_error.missing", + "detail": [ + { + "type": "missing", + "loc": ["body", "price"], + "msg": "Field required", + "input": {"name": "Foo"}, + "url": match_pydantic_error_url("missing"), + } + ] } - ] -} - -price_not_float = { - "detail": [ + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 { - "loc": ["body", "price"], - "msg": "value is not a valid float", - "type": "type_error.float", + "detail": [ + { + "loc": ["body", "price"], + "msg": "field required", + "type": "value_error.missing", + } + ] } - ] -} + ) + -name_price_missing = { - "detail": [ +@needs_py310 +def test_post_with_only_name_price(client: TestClient): + response = client.post("/items/", json={"name": "Foo", "price": "twenty"}) + assert response.status_code == 422 + assert response.json() == IsDict( { - "loc": ["body", "name"], - "msg": "field required", - "type": "value_error.missing", - }, + "detail": [ + { + "type": "float_parsing", + "loc": ["body", "price"], + "msg": "Input should be a valid number, unable to parse string as a number", + "input": "twenty", + "url": match_pydantic_error_url("float_parsing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 { - "loc": ["body", "price"], - "msg": "field required", - "type": "value_error.missing", - }, - ] -} + "detail": [ + { + "loc": ["body", "price"], + "msg": "value is not a valid float", + "type": "type_error.float", + } + ] + } + ) -body_missing = { - "detail": [ - {"loc": ["body"], "msg": "field required", "type": "value_error.missing"} - ] -} + +@needs_py310 +def test_post_with_no_data(client: TestClient): + response = client.post("/items/", json={}) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "name"], + "msg": "Field required", + "input": {}, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "price"], + "msg": "Field required", + "input": {}, + "url": match_pydantic_error_url("missing"), + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "name"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "price"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) @needs_py310 -@pytest.mark.parametrize( - "path,body,expected_status,expected_response", - [ - ( - "/items/", - {"name": "Foo", "price": 50.5}, - 200, - {"name": "Foo", "price": 50.5, "description": None, "tax": None}, - ), - ( - "/items/", - {"name": "Foo", "price": "50.5"}, - 200, - {"name": "Foo", "price": 50.5, "description": None, "tax": None}, - ), - ( - "/items/", - {"name": "Foo", "price": "50.5", "description": "Some Foo"}, - 200, - {"name": "Foo", "price": 50.5, "description": "Some Foo", "tax": None}, - ), - ( - "/items/", - {"name": "Foo", "price": "50.5", "description": "Some Foo", "tax": 0.3}, - 200, - {"name": "Foo", "price": 50.5, "description": "Some Foo", "tax": 0.3}, - ), - ("/items/", {"name": "Foo"}, 422, price_missing), - ("/items/", {"name": "Foo", "price": "twenty"}, 422, price_not_float), - ("/items/", {}, 422, name_price_missing), - ("/items/", None, 422, body_missing), - ], -) -def test_post_body(path, body, expected_status, expected_response, client: TestClient): - response = client.post(path, json=body) - assert response.status_code == expected_status - assert response.json() == expected_response +def test_post_with_none(client: TestClient): + response = client.post("/items/", json=None) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) @needs_py310 @@ -104,37 +209,69 @@ def test_post_broken_body(client: TestClient): content="{some broken json}", ) assert response.status_code == 422, response.text - assert response.json() == { - "detail": [ - { - "loc": ["body", 1], - "msg": "Expecting property name enclosed in double quotes: line 1 column 2 (char 1)", - "type": "value_error.jsondecode", - "ctx": { - "msg": "Expecting property name enclosed in double quotes", - "doc": "{some broken json}", - "pos": 1, - "lineno": 1, - "colno": 2, - }, - } - ] - } + assert response.json() == IsDict( + { + "detail": [ + { + "type": "json_invalid", + "loc": ["body", 1], + "msg": "JSON decode error", + "input": {}, + "ctx": { + "error": "Expecting property name enclosed in double quotes" + }, + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", 1], + "msg": "Expecting property name enclosed in double quotes: line 1 column 2 (char 1)", + "type": "value_error.jsondecode", + "ctx": { + "msg": "Expecting property name enclosed in double quotes", + "doc": "{some broken json}", + "pos": 1, + "lineno": 1, + "colno": 2, + }, + } + ] + } + ) @needs_py310 def test_post_form_for_json(client: TestClient): response = client.post("/items/", data={"name": "Foo", "price": 50.5}) assert response.status_code == 422, response.text - assert response.json() == { - "detail": [ - { - "loc": ["body"], - "msg": "value is not a valid dict", - "type": "type_error.dict", - } - ] - } + assert response.json() == IsDict( + { + "detail": [ + { + "type": "model_attributes_type", + "loc": ["body"], + "msg": "Input should be a valid dictionary or object to extract fields from", + "input": "name=Foo&price=50.5", + "url": match_pydantic_error_url("model_attributes_type"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body"], + "msg": "value is not a valid dict", + "type": "type_error.dict", + } + ] + } + ) @needs_py310 @@ -175,32 +312,91 @@ def test_no_content_type_is_json(client: TestClient): @needs_py310 def test_wrong_headers(client: TestClient): data = '{"name": "Foo", "price": 50.5}' - invalid_dict = { - "detail": [ - { - "loc": ["body"], - "msg": "value is not a valid dict", - "type": "type_error.dict", - } - ] - } - response = client.post( "/items/", content=data, headers={"Content-Type": "text/plain"} ) assert response.status_code == 422, response.text - assert response.json() == invalid_dict + assert response.json() == IsDict( + { + "detail": [ + { + "type": "model_attributes_type", + "loc": ["body"], + "msg": "Input should be a valid dictionary or object to extract fields from", + "input": '{"name": "Foo", "price": 50.5}', + "url": match_pydantic_error_url("model_attributes_type"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body"], + "msg": "value is not a valid dict", + "type": "type_error.dict", + } + ] + } + ) response = client.post( "/items/", content=data, headers={"Content-Type": "application/geo+json-seq"} ) assert response.status_code == 422, response.text - assert response.json() == invalid_dict + assert response.json() == IsDict( + { + "detail": [ + { + "type": "model_attributes_type", + "loc": ["body"], + "msg": "Input should be a valid dictionary or object to extract fields from", + "input": '{"name": "Foo", "price": 50.5}', + "url": match_pydantic_error_url("model_attributes_type"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body"], + "msg": "value is not a valid dict", + "type": "type_error.dict", + } + ] + } + ) response = client.post( "/items/", content=data, headers={"Content-Type": "application/not-really-json"} ) assert response.status_code == 422, response.text - assert response.json() == invalid_dict + assert response.json() == IsDict( + { + "detail": [ + { + "type": "model_attributes_type", + "loc": ["body"], + "msg": "Input should be a valid dictionary or object to extract fields from", + "input": '{"name": "Foo", "price": 50.5}', + "url": match_pydantic_error_url("model_attributes_type"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body"], + "msg": "value is not a valid dict", + "type": "type_error.dict", + } + ] + } + ) @needs_py310 @@ -215,7 +411,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { @@ -258,8 +454,26 @@ def test_openapi_schema(client: TestClient): "properties": { "name": {"title": "Name", "type": "string"}, "price": {"title": "Price", "type": "number"}, - "description": {"title": "Description", "type": "string"}, - "tax": {"title": "Tax", "type": "number"}, + "description": IsDict( + { + "title": "Description", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Description", "type": "string"} + ), + "tax": IsDict( + { + "title": "Tax", + "anyOf": [{"type": "number"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Tax", "type": "number"} + ), }, }, "ValidationError": { diff --git a/tests/test_tutorial/test_body_fields/test_tutorial001.py b/tests/test_tutorial/test_body_fields/test_tutorial001.py index a7ea0e9496664..1ff2d95760b9b 100644 --- a/tests/test_tutorial/test_body_fields/test_tutorial001.py +++ b/tests/test_tutorial/test_body_fields/test_tutorial001.py @@ -1,70 +1,86 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url -from docs_src.body_fields.tutorial001 import app -client = TestClient(app) +@pytest.fixture(name="client") +def get_client(): + from docs_src.body_fields.tutorial001 import app + client = TestClient(app) + return client -price_not_greater = { - "detail": [ - { - "ctx": {"limit_value": 0}, - "loc": ["body", "item", "price"], - "msg": "ensure this value is greater than 0", - "type": "value_error.number.not_gt", - } - ] -} + +def test_items_5(client: TestClient): + response = client.put("/items/5", json={"item": {"name": "Foo", "price": 3.0}}) + assert response.status_code == 200 + assert response.json() == { + "item_id": 5, + "item": {"name": "Foo", "price": 3.0, "description": None, "tax": None}, + } + + +def test_items_6(client: TestClient): + response = client.put( + "/items/6", + json={ + "item": { + "name": "Bar", + "price": 0.2, + "description": "Some bar", + "tax": "5.4", + } + }, + ) + assert response.status_code == 200 + assert response.json() == { + "item_id": 6, + "item": { + "name": "Bar", + "price": 0.2, + "description": "Some bar", + "tax": 5.4, + }, + } -@pytest.mark.parametrize( - "path,body,expected_status,expected_response", - [ - ( - "/items/5", - {"item": {"name": "Foo", "price": 3.0}}, - 200, - { - "item_id": 5, - "item": {"name": "Foo", "price": 3.0, "description": None, "tax": None}, - }, - ), - ( - "/items/6", - { - "item": { - "name": "Bar", - "price": 0.2, - "description": "Some bar", - "tax": "5.4", +def test_invalid_price(client: TestClient): + response = client.put("/items/5", json={"item": {"name": "Foo", "price": -3.0}}) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "greater_than", + "loc": ["body", "item", "price"], + "msg": "Input should be greater than 0", + "input": -3.0, + "ctx": {"gt": 0.0}, + "url": match_pydantic_error_url("greater_than"), } - }, - 200, - { - "item_id": 6, - "item": { - "name": "Bar", - "price": 0.2, - "description": "Some bar", - "tax": 5.4, - }, - }, - ), - ("/items/5", {"item": {"name": "Foo", "price": -3.0}}, 422, price_not_greater), - ], -) -def test(path, body, expected_status, expected_response): - response = client.put(path, json=body) - assert response.status_code == expected_status - assert response.json() == expected_response + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "ctx": {"limit_value": 0}, + "loc": ["body", "item", "price"], + "msg": "ensure this value is greater than 0", + "type": "value_error.number.not_gt", + } + ] + } + ) -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { @@ -116,18 +132,39 @@ def test_openapi_schema(): "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, - "description": { - "title": "The description of the item", - "maxLength": 300, - "type": "string", - }, + "description": IsDict( + { + "title": "The description of the item", + "anyOf": [ + {"maxLength": 300, "type": "string"}, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "The description of the item", + "maxLength": 300, + "type": "string", + } + ), "price": { "title": "Price", "exclusiveMinimum": 0.0, "type": "number", "description": "The price must be greater than zero", }, - "tax": {"title": "Tax", "type": "number"}, + "tax": IsDict( + { + "title": "Tax", + "anyOf": [{"type": "number"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Tax", "type": "number"} + ), }, }, "Body_update_item_items__item_id__put": { diff --git a/tests/test_tutorial/test_body_fields/test_tutorial001_an.py b/tests/test_tutorial/test_body_fields/test_tutorial001_an.py index 32f996ecbd5d5..907d6842a42fe 100644 --- a/tests/test_tutorial/test_body_fields/test_tutorial001_an.py +++ b/tests/test_tutorial/test_body_fields/test_tutorial001_an.py @@ -1,70 +1,86 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url -from docs_src.body_fields.tutorial001_an import app -client = TestClient(app) +@pytest.fixture(name="client") +def get_client(): + from docs_src.body_fields.tutorial001_an import app + client = TestClient(app) + return client -price_not_greater = { - "detail": [ - { - "ctx": {"limit_value": 0}, - "loc": ["body", "item", "price"], - "msg": "ensure this value is greater than 0", - "type": "value_error.number.not_gt", - } - ] -} + +def test_items_5(client: TestClient): + response = client.put("/items/5", json={"item": {"name": "Foo", "price": 3.0}}) + assert response.status_code == 200 + assert response.json() == { + "item_id": 5, + "item": {"name": "Foo", "price": 3.0, "description": None, "tax": None}, + } + + +def test_items_6(client: TestClient): + response = client.put( + "/items/6", + json={ + "item": { + "name": "Bar", + "price": 0.2, + "description": "Some bar", + "tax": "5.4", + } + }, + ) + assert response.status_code == 200 + assert response.json() == { + "item_id": 6, + "item": { + "name": "Bar", + "price": 0.2, + "description": "Some bar", + "tax": 5.4, + }, + } -@pytest.mark.parametrize( - "path,body,expected_status,expected_response", - [ - ( - "/items/5", - {"item": {"name": "Foo", "price": 3.0}}, - 200, - { - "item_id": 5, - "item": {"name": "Foo", "price": 3.0, "description": None, "tax": None}, - }, - ), - ( - "/items/6", - { - "item": { - "name": "Bar", - "price": 0.2, - "description": "Some bar", - "tax": "5.4", +def test_invalid_price(client: TestClient): + response = client.put("/items/5", json={"item": {"name": "Foo", "price": -3.0}}) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "greater_than", + "loc": ["body", "item", "price"], + "msg": "Input should be greater than 0", + "input": -3.0, + "ctx": {"gt": 0.0}, + "url": match_pydantic_error_url("greater_than"), } - }, - 200, - { - "item_id": 6, - "item": { - "name": "Bar", - "price": 0.2, - "description": "Some bar", - "tax": 5.4, - }, - }, - ), - ("/items/5", {"item": {"name": "Foo", "price": -3.0}}, 422, price_not_greater), - ], -) -def test(path, body, expected_status, expected_response): - response = client.put(path, json=body) - assert response.status_code == expected_status - assert response.json() == expected_response + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "ctx": {"limit_value": 0}, + "loc": ["body", "item", "price"], + "msg": "ensure this value is greater than 0", + "type": "value_error.number.not_gt", + } + ] + } + ) -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { @@ -116,18 +132,39 @@ def test_openapi_schema(): "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, - "description": { - "title": "The description of the item", - "maxLength": 300, - "type": "string", - }, + "description": IsDict( + { + "title": "The description of the item", + "anyOf": [ + {"maxLength": 300, "type": "string"}, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "The description of the item", + "maxLength": 300, + "type": "string", + } + ), "price": { "title": "Price", "exclusiveMinimum": 0.0, "type": "number", "description": "The price must be greater than zero", }, - "tax": {"title": "Tax", "type": "number"}, + "tax": IsDict( + { + "title": "Tax", + "anyOf": [{"type": "number"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Tax", "type": "number"} + ), }, }, "Body_update_item_items__item_id__put": { diff --git a/tests/test_tutorial/test_body_fields/test_tutorial001_an_py310.py b/tests/test_tutorial/test_body_fields/test_tutorial001_an_py310.py index 20e032fcd8a05..431d2d1819468 100644 --- a/tests/test_tutorial/test_body_fields/test_tutorial001_an_py310.py +++ b/tests/test_tutorial/test_body_fields/test_tutorial001_an_py310.py @@ -1,5 +1,7 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url from ...utils import needs_py310 @@ -12,59 +14,71 @@ def get_client(): return client -price_not_greater = { - "detail": [ - { - "ctx": {"limit_value": 0}, - "loc": ["body", "item", "price"], - "msg": "ensure this value is greater than 0", - "type": "value_error.number.not_gt", - } - ] -} +@needs_py310 +def test_items_5(client: TestClient): + response = client.put("/items/5", json={"item": {"name": "Foo", "price": 3.0}}) + assert response.status_code == 200 + assert response.json() == { + "item_id": 5, + "item": {"name": "Foo", "price": 3.0, "description": None, "tax": None}, + } @needs_py310 -@pytest.mark.parametrize( - "path,body,expected_status,expected_response", - [ - ( - "/items/5", - {"item": {"name": "Foo", "price": 3.0}}, - 200, - { - "item_id": 5, - "item": {"name": "Foo", "price": 3.0, "description": None, "tax": None}, - }, - ), - ( - "/items/6", - { - "item": { - "name": "Bar", - "price": 0.2, - "description": "Some bar", - "tax": "5.4", +def test_items_6(client: TestClient): + response = client.put( + "/items/6", + json={ + "item": { + "name": "Bar", + "price": 0.2, + "description": "Some bar", + "tax": "5.4", + } + }, + ) + assert response.status_code == 200 + assert response.json() == { + "item_id": 6, + "item": { + "name": "Bar", + "price": 0.2, + "description": "Some bar", + "tax": 5.4, + }, + } + + +@needs_py310 +def test_invalid_price(client: TestClient): + response = client.put("/items/5", json={"item": {"name": "Foo", "price": -3.0}}) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "greater_than", + "loc": ["body", "item", "price"], + "msg": "Input should be greater than 0", + "input": -3.0, + "ctx": {"gt": 0.0}, + "url": match_pydantic_error_url("greater_than"), } - }, - 200, - { - "item_id": 6, - "item": { - "name": "Bar", - "price": 0.2, - "description": "Some bar", - "tax": 5.4, - }, - }, - ), - ("/items/5", {"item": {"name": "Foo", "price": -3.0}}, 422, price_not_greater), - ], -) -def test(path, body, expected_status, expected_response, client: TestClient): - response = client.put(path, json=body) - assert response.status_code == expected_status - assert response.json() == expected_response + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "ctx": {"limit_value": 0}, + "loc": ["body", "item", "price"], + "msg": "ensure this value is greater than 0", + "type": "value_error.number.not_gt", + } + ] + } + ) @needs_py310 @@ -72,7 +86,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { @@ -124,18 +138,39 @@ def test_openapi_schema(client: TestClient): "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, - "description": { - "title": "The description of the item", - "maxLength": 300, - "type": "string", - }, + "description": IsDict( + { + "title": "The description of the item", + "anyOf": [ + {"maxLength": 300, "type": "string"}, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "The description of the item", + "maxLength": 300, + "type": "string", + } + ), "price": { "title": "Price", "exclusiveMinimum": 0.0, "type": "number", "description": "The price must be greater than zero", }, - "tax": {"title": "Tax", "type": "number"}, + "tax": IsDict( + { + "title": "Tax", + "anyOf": [{"type": "number"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Tax", "type": "number"} + ), }, }, "Body_update_item_items__item_id__put": { diff --git a/tests/test_tutorial/test_body_fields/test_tutorial001_an_py39.py b/tests/test_tutorial/test_body_fields/test_tutorial001_an_py39.py index e3baf5f2badf9..8cef6c154c9cc 100644 --- a/tests/test_tutorial/test_body_fields/test_tutorial001_an_py39.py +++ b/tests/test_tutorial/test_body_fields/test_tutorial001_an_py39.py @@ -1,5 +1,7 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url from ...utils import needs_py39 @@ -12,59 +14,71 @@ def get_client(): return client -price_not_greater = { - "detail": [ - { - "ctx": {"limit_value": 0}, - "loc": ["body", "item", "price"], - "msg": "ensure this value is greater than 0", - "type": "value_error.number.not_gt", - } - ] -} +@needs_py39 +def test_items_5(client: TestClient): + response = client.put("/items/5", json={"item": {"name": "Foo", "price": 3.0}}) + assert response.status_code == 200 + assert response.json() == { + "item_id": 5, + "item": {"name": "Foo", "price": 3.0, "description": None, "tax": None}, + } @needs_py39 -@pytest.mark.parametrize( - "path,body,expected_status,expected_response", - [ - ( - "/items/5", - {"item": {"name": "Foo", "price": 3.0}}, - 200, - { - "item_id": 5, - "item": {"name": "Foo", "price": 3.0, "description": None, "tax": None}, - }, - ), - ( - "/items/6", - { - "item": { - "name": "Bar", - "price": 0.2, - "description": "Some bar", - "tax": "5.4", +def test_items_6(client: TestClient): + response = client.put( + "/items/6", + json={ + "item": { + "name": "Bar", + "price": 0.2, + "description": "Some bar", + "tax": "5.4", + } + }, + ) + assert response.status_code == 200 + assert response.json() == { + "item_id": 6, + "item": { + "name": "Bar", + "price": 0.2, + "description": "Some bar", + "tax": 5.4, + }, + } + + +@needs_py39 +def test_invalid_price(client: TestClient): + response = client.put("/items/5", json={"item": {"name": "Foo", "price": -3.0}}) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "greater_than", + "loc": ["body", "item", "price"], + "msg": "Input should be greater than 0", + "input": -3.0, + "ctx": {"gt": 0.0}, + "url": match_pydantic_error_url("greater_than"), } - }, - 200, - { - "item_id": 6, - "item": { - "name": "Bar", - "price": 0.2, - "description": "Some bar", - "tax": 5.4, - }, - }, - ), - ("/items/5", {"item": {"name": "Foo", "price": -3.0}}, 422, price_not_greater), - ], -) -def test(path, body, expected_status, expected_response, client: TestClient): - response = client.put(path, json=body) - assert response.status_code == expected_status - assert response.json() == expected_response + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "ctx": {"limit_value": 0}, + "loc": ["body", "item", "price"], + "msg": "ensure this value is greater than 0", + "type": "value_error.number.not_gt", + } + ] + } + ) @needs_py39 @@ -72,7 +86,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { @@ -124,18 +138,39 @@ def test_openapi_schema(client: TestClient): "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, - "description": { - "title": "The description of the item", - "maxLength": 300, - "type": "string", - }, + "description": IsDict( + { + "title": "The description of the item", + "anyOf": [ + {"maxLength": 300, "type": "string"}, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "The description of the item", + "maxLength": 300, + "type": "string", + } + ), "price": { "title": "Price", "exclusiveMinimum": 0.0, "type": "number", "description": "The price must be greater than zero", }, - "tax": {"title": "Tax", "type": "number"}, + "tax": IsDict( + { + "title": "Tax", + "anyOf": [{"type": "number"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Tax", "type": "number"} + ), }, }, "Body_update_item_items__item_id__put": { diff --git a/tests/test_tutorial/test_body_fields/test_tutorial001_py310.py b/tests/test_tutorial/test_body_fields/test_tutorial001_py310.py index 4c2f48674a7a3..b48cd9ec26d92 100644 --- a/tests/test_tutorial/test_body_fields/test_tutorial001_py310.py +++ b/tests/test_tutorial/test_body_fields/test_tutorial001_py310.py @@ -1,5 +1,7 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url from ...utils import needs_py310 @@ -12,59 +14,71 @@ def get_client(): return client -price_not_greater = { - "detail": [ - { - "ctx": {"limit_value": 0}, - "loc": ["body", "item", "price"], - "msg": "ensure this value is greater than 0", - "type": "value_error.number.not_gt", - } - ] -} +@needs_py310 +def test_items_5(client: TestClient): + response = client.put("/items/5", json={"item": {"name": "Foo", "price": 3.0}}) + assert response.status_code == 200 + assert response.json() == { + "item_id": 5, + "item": {"name": "Foo", "price": 3.0, "description": None, "tax": None}, + } @needs_py310 -@pytest.mark.parametrize( - "path,body,expected_status,expected_response", - [ - ( - "/items/5", - {"item": {"name": "Foo", "price": 3.0}}, - 200, - { - "item_id": 5, - "item": {"name": "Foo", "price": 3.0, "description": None, "tax": None}, - }, - ), - ( - "/items/6", - { - "item": { - "name": "Bar", - "price": 0.2, - "description": "Some bar", - "tax": "5.4", +def test_items_6(client: TestClient): + response = client.put( + "/items/6", + json={ + "item": { + "name": "Bar", + "price": 0.2, + "description": "Some bar", + "tax": "5.4", + } + }, + ) + assert response.status_code == 200 + assert response.json() == { + "item_id": 6, + "item": { + "name": "Bar", + "price": 0.2, + "description": "Some bar", + "tax": 5.4, + }, + } + + +@needs_py310 +def test_invalid_price(client: TestClient): + response = client.put("/items/5", json={"item": {"name": "Foo", "price": -3.0}}) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "greater_than", + "loc": ["body", "item", "price"], + "msg": "Input should be greater than 0", + "input": -3.0, + "ctx": {"gt": 0.0}, + "url": match_pydantic_error_url("greater_than"), } - }, - 200, - { - "item_id": 6, - "item": { - "name": "Bar", - "price": 0.2, - "description": "Some bar", - "tax": 5.4, - }, - }, - ), - ("/items/5", {"item": {"name": "Foo", "price": -3.0}}, 422, price_not_greater), - ], -) -def test(path, body, expected_status, expected_response, client: TestClient): - response = client.put(path, json=body) - assert response.status_code == expected_status - assert response.json() == expected_response + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "ctx": {"limit_value": 0}, + "loc": ["body", "item", "price"], + "msg": "ensure this value is greater than 0", + "type": "value_error.number.not_gt", + } + ] + } + ) @needs_py310 @@ -72,7 +86,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { @@ -124,18 +138,39 @@ def test_openapi_schema(client: TestClient): "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, - "description": { - "title": "The description of the item", - "maxLength": 300, - "type": "string", - }, + "description": IsDict( + { + "title": "The description of the item", + "anyOf": [ + {"maxLength": 300, "type": "string"}, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "The description of the item", + "maxLength": 300, + "type": "string", + } + ), "price": { "title": "Price", "exclusiveMinimum": 0.0, "type": "number", "description": "The price must be greater than zero", }, - "tax": {"title": "Tax", "type": "number"}, + "tax": IsDict( + { + "title": "Tax", + "anyOf": [{"type": "number"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Tax", "type": "number"} + ), }, }, "Body_update_item_items__item_id__put": { diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial001.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial001.py index 496ab38fb97a6..e5dc13b268e7d 100644 --- a/tests/test_tutorial/test_body_multiple_params/test_tutorial001.py +++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial001.py @@ -1,56 +1,78 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url -from docs_src.body_multiple_params.tutorial001 import app -client = TestClient(app) +@pytest.fixture(name="client") +def get_client(): + from docs_src.body_multiple_params.tutorial001 import app + client = TestClient(app) + return client -item_id_not_int = { - "detail": [ - { - "loc": ["path", "item_id"], - "msg": "value is not a valid integer", - "type": "type_error.integer", - } - ] -} +def test_post_body_q_bar_content(client: TestClient): + response = client.put("/items/5?q=bar", json={"name": "Foo", "price": 50.5}) + assert response.status_code == 200 + assert response.json() == { + "item_id": 5, + "item": { + "name": "Foo", + "price": 50.5, + "description": None, + "tax": None, + }, + "q": "bar", + } -@pytest.mark.parametrize( - "path,body,expected_status,expected_response", - [ - ( - "/items/5?q=bar", - {"name": "Foo", "price": 50.5}, - 200, - { - "item_id": 5, - "item": { - "name": "Foo", - "price": 50.5, - "description": None, - "tax": None, - }, - "q": "bar", - }, - ), - ("/items/5?q=bar", None, 200, {"item_id": 5, "q": "bar"}), - ("/items/5", None, 200, {"item_id": 5}), - ("/items/foo", None, 422, item_id_not_int), - ], -) -def test_post_body(path, body, expected_status, expected_response): - response = client.put(path, json=body) - assert response.status_code == expected_status - assert response.json() == expected_response +def test_post_no_body_q_bar(client: TestClient): + response = client.put("/items/5?q=bar", json=None) + assert response.status_code == 200 + assert response.json() == {"item_id": 5, "q": "bar"} -def test_openapi_schema(): + +def test_post_no_body(client: TestClient): + response = client.put("/items/5", json=None) + assert response.status_code == 200 + assert response.json() == {"item_id": 5} + + +def test_post_id_foo(client: TestClient): + response = client.put("/items/foo", json=None) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "int_parsing", + "loc": ["path", "item_id"], + "msg": "Input should be a valid integer, unable to parse string as an integer", + "input": "foo", + "url": match_pydantic_error_url("int_parsing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["path", "item_id"], + "msg": "value is not a valid integer", + "type": "type_error.integer", + } + ] + } + ) + + +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { @@ -87,7 +109,16 @@ def test_openapi_schema(): }, { "required": False, - "schema": {"title": "Q", "type": "string"}, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Q", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Q", "type": "string"} + ), "name": "q", "in": "query", }, @@ -95,7 +126,19 @@ def test_openapi_schema(): "requestBody": { "content": { "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} + "schema": IsDict( + { + "anyOf": [ + {"$ref": "#/components/schemas/Item"}, + {"type": "null"}, + ], + "title": "Item", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"$ref": "#/components/schemas/Item"} + ) } } }, @@ -110,9 +153,27 @@ def test_openapi_schema(): "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, + "description": IsDict( + { + "title": "Description", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Description", "type": "string"} + ), "price": {"title": "Price", "type": "number"}, - "description": {"title": "Description", "type": "string"}, - "tax": {"title": "Tax", "type": "number"}, + "tax": IsDict( + { + "title": "Tax", + "anyOf": [{"type": "number"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Tax", "type": "number"} + ), }, }, "ValidationError": { diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an.py index 74a8a9b2e4a4f..51e8e3a4e9977 100644 --- a/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an.py +++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an.py @@ -1,56 +1,78 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url -from docs_src.body_multiple_params.tutorial001_an import app -client = TestClient(app) +@pytest.fixture(name="client") +def get_client(): + from docs_src.body_multiple_params.tutorial001_an import app + client = TestClient(app) + return client -item_id_not_int = { - "detail": [ - { - "loc": ["path", "item_id"], - "msg": "value is not a valid integer", - "type": "type_error.integer", - } - ] -} +def test_post_body_q_bar_content(client: TestClient): + response = client.put("/items/5?q=bar", json={"name": "Foo", "price": 50.5}) + assert response.status_code == 200 + assert response.json() == { + "item_id": 5, + "item": { + "name": "Foo", + "price": 50.5, + "description": None, + "tax": None, + }, + "q": "bar", + } -@pytest.mark.parametrize( - "path,body,expected_status,expected_response", - [ - ( - "/items/5?q=bar", - {"name": "Foo", "price": 50.5}, - 200, - { - "item_id": 5, - "item": { - "name": "Foo", - "price": 50.5, - "description": None, - "tax": None, - }, - "q": "bar", - }, - ), - ("/items/5?q=bar", None, 200, {"item_id": 5, "q": "bar"}), - ("/items/5", None, 200, {"item_id": 5}), - ("/items/foo", None, 422, item_id_not_int), - ], -) -def test_post_body(path, body, expected_status, expected_response): - response = client.put(path, json=body) - assert response.status_code == expected_status - assert response.json() == expected_response +def test_post_no_body_q_bar(client: TestClient): + response = client.put("/items/5?q=bar", json=None) + assert response.status_code == 200 + assert response.json() == {"item_id": 5, "q": "bar"} -def test_openapi_schema(): + +def test_post_no_body(client: TestClient): + response = client.put("/items/5", json=None) + assert response.status_code == 200 + assert response.json() == {"item_id": 5} + + +def test_post_id_foo(client: TestClient): + response = client.put("/items/foo", json=None) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "int_parsing", + "loc": ["path", "item_id"], + "msg": "Input should be a valid integer, unable to parse string as an integer", + "input": "foo", + "url": match_pydantic_error_url("int_parsing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["path", "item_id"], + "msg": "value is not a valid integer", + "type": "type_error.integer", + } + ] + } + ) + + +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { @@ -87,7 +109,16 @@ def test_openapi_schema(): }, { "required": False, - "schema": {"title": "Q", "type": "string"}, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Q", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Q", "type": "string"} + ), "name": "q", "in": "query", }, @@ -95,7 +126,19 @@ def test_openapi_schema(): "requestBody": { "content": { "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} + "schema": IsDict( + { + "anyOf": [ + {"$ref": "#/components/schemas/Item"}, + {"type": "null"}, + ], + "title": "Item", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"$ref": "#/components/schemas/Item"} + ) } } }, @@ -110,9 +153,27 @@ def test_openapi_schema(): "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, + "description": IsDict( + { + "title": "Description", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Description", "type": "string"} + ), "price": {"title": "Price", "type": "number"}, - "description": {"title": "Description", "type": "string"}, - "tax": {"title": "Tax", "type": "number"}, + "tax": IsDict( + { + "title": "Tax", + "anyOf": [{"type": "number"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Tax", "type": "number"} + ), }, }, "ValidationError": { diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an_py310.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an_py310.py index 9c764b6d177fb..8ac1f72618551 100644 --- a/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an_py310.py +++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an_py310.py @@ -1,5 +1,7 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url from ...utils import needs_py310 @@ -12,45 +14,64 @@ def get_client(): return client -item_id_not_int = { - "detail": [ - { - "loc": ["path", "item_id"], - "msg": "value is not a valid integer", - "type": "type_error.integer", - } - ] -} +@needs_py310 +def test_post_body_q_bar_content(client: TestClient): + response = client.put("/items/5?q=bar", json={"name": "Foo", "price": 50.5}) + assert response.status_code == 200 + assert response.json() == { + "item_id": 5, + "item": { + "name": "Foo", + "price": 50.5, + "description": None, + "tax": None, + }, + "q": "bar", + } @needs_py310 -@pytest.mark.parametrize( - "path,body,expected_status,expected_response", - [ - ( - "/items/5?q=bar", - {"name": "Foo", "price": 50.5}, - 200, - { - "item_id": 5, - "item": { - "name": "Foo", - "price": 50.5, - "description": None, - "tax": None, - }, - "q": "bar", - }, - ), - ("/items/5?q=bar", None, 200, {"item_id": 5, "q": "bar"}), - ("/items/5", None, 200, {"item_id": 5}), - ("/items/foo", None, 422, item_id_not_int), - ], -) -def test_post_body(path, body, expected_status, expected_response, client: TestClient): - response = client.put(path, json=body) - assert response.status_code == expected_status - assert response.json() == expected_response +def test_post_no_body_q_bar(client: TestClient): + response = client.put("/items/5?q=bar", json=None) + assert response.status_code == 200 + assert response.json() == {"item_id": 5, "q": "bar"} + + +@needs_py310 +def test_post_no_body(client: TestClient): + response = client.put("/items/5", json=None) + assert response.status_code == 200 + assert response.json() == {"item_id": 5} + + +@needs_py310 +def test_post_id_foo(client: TestClient): + response = client.put("/items/foo", json=None) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "int_parsing", + "loc": ["path", "item_id"], + "msg": "Input should be a valid integer, unable to parse string as an integer", + "input": "foo", + "url": match_pydantic_error_url("int_parsing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["path", "item_id"], + "msg": "value is not a valid integer", + "type": "type_error.integer", + } + ] + } + ) @needs_py310 @@ -58,7 +79,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { @@ -95,7 +116,16 @@ def test_openapi_schema(client: TestClient): }, { "required": False, - "schema": {"title": "Q", "type": "string"}, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Q", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Q", "type": "string"} + ), "name": "q", "in": "query", }, @@ -103,7 +133,19 @@ def test_openapi_schema(client: TestClient): "requestBody": { "content": { "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} + "schema": IsDict( + { + "anyOf": [ + {"$ref": "#/components/schemas/Item"}, + {"type": "null"}, + ], + "title": "Item", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"$ref": "#/components/schemas/Item"} + ) } } }, @@ -118,9 +160,27 @@ def test_openapi_schema(client: TestClient): "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, + "description": IsDict( + { + "title": "Description", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Description", "type": "string"} + ), "price": {"title": "Price", "type": "number"}, - "description": {"title": "Description", "type": "string"}, - "tax": {"title": "Tax", "type": "number"}, + "tax": IsDict( + { + "title": "Tax", + "anyOf": [{"type": "number"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Tax", "type": "number"} + ), }, }, "ValidationError": { diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an_py39.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an_py39.py index 0cca294333b53..7ada42c528b54 100644 --- a/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an_py39.py +++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an_py39.py @@ -1,5 +1,7 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url from ...utils import needs_py39 @@ -12,45 +14,64 @@ def get_client(): return client -item_id_not_int = { - "detail": [ - { - "loc": ["path", "item_id"], - "msg": "value is not a valid integer", - "type": "type_error.integer", - } - ] -} +@needs_py39 +def test_post_body_q_bar_content(client: TestClient): + response = client.put("/items/5?q=bar", json={"name": "Foo", "price": 50.5}) + assert response.status_code == 200 + assert response.json() == { + "item_id": 5, + "item": { + "name": "Foo", + "price": 50.5, + "description": None, + "tax": None, + }, + "q": "bar", + } @needs_py39 -@pytest.mark.parametrize( - "path,body,expected_status,expected_response", - [ - ( - "/items/5?q=bar", - {"name": "Foo", "price": 50.5}, - 200, - { - "item_id": 5, - "item": { - "name": "Foo", - "price": 50.5, - "description": None, - "tax": None, - }, - "q": "bar", - }, - ), - ("/items/5?q=bar", None, 200, {"item_id": 5, "q": "bar"}), - ("/items/5", None, 200, {"item_id": 5}), - ("/items/foo", None, 422, item_id_not_int), - ], -) -def test_post_body(path, body, expected_status, expected_response, client: TestClient): - response = client.put(path, json=body) - assert response.status_code == expected_status - assert response.json() == expected_response +def test_post_no_body_q_bar(client: TestClient): + response = client.put("/items/5?q=bar", json=None) + assert response.status_code == 200 + assert response.json() == {"item_id": 5, "q": "bar"} + + +@needs_py39 +def test_post_no_body(client: TestClient): + response = client.put("/items/5", json=None) + assert response.status_code == 200 + assert response.json() == {"item_id": 5} + + +@needs_py39 +def test_post_id_foo(client: TestClient): + response = client.put("/items/foo", json=None) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "int_parsing", + "loc": ["path", "item_id"], + "msg": "Input should be a valid integer, unable to parse string as an integer", + "input": "foo", + "url": match_pydantic_error_url("int_parsing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["path", "item_id"], + "msg": "value is not a valid integer", + "type": "type_error.integer", + } + ] + } + ) @needs_py39 @@ -58,7 +79,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { @@ -95,7 +116,16 @@ def test_openapi_schema(client: TestClient): }, { "required": False, - "schema": {"title": "Q", "type": "string"}, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Q", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Q", "type": "string"} + ), "name": "q", "in": "query", }, @@ -103,7 +133,19 @@ def test_openapi_schema(client: TestClient): "requestBody": { "content": { "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} + "schema": IsDict( + { + "anyOf": [ + {"$ref": "#/components/schemas/Item"}, + {"type": "null"}, + ], + "title": "Item", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"$ref": "#/components/schemas/Item"} + ) } } }, @@ -118,9 +160,27 @@ def test_openapi_schema(client: TestClient): "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, + "description": IsDict( + { + "title": "Description", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Description", "type": "string"} + ), "price": {"title": "Price", "type": "number"}, - "description": {"title": "Description", "type": "string"}, - "tax": {"title": "Tax", "type": "number"}, + "tax": IsDict( + { + "title": "Tax", + "anyOf": [{"type": "number"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Tax", "type": "number"} + ), }, }, "ValidationError": { diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial001_py310.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial001_py310.py index 3b61e717ec399..0a832eaf6f0ff 100644 --- a/tests/test_tutorial/test_body_multiple_params/test_tutorial001_py310.py +++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial001_py310.py @@ -1,5 +1,7 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url from ...utils import needs_py310 @@ -12,45 +14,64 @@ def get_client(): return client -item_id_not_int = { - "detail": [ - { - "loc": ["path", "item_id"], - "msg": "value is not a valid integer", - "type": "type_error.integer", - } - ] -} +@needs_py310 +def test_post_body_q_bar_content(client: TestClient): + response = client.put("/items/5?q=bar", json={"name": "Foo", "price": 50.5}) + assert response.status_code == 200 + assert response.json() == { + "item_id": 5, + "item": { + "name": "Foo", + "price": 50.5, + "description": None, + "tax": None, + }, + "q": "bar", + } @needs_py310 -@pytest.mark.parametrize( - "path,body,expected_status,expected_response", - [ - ( - "/items/5?q=bar", - {"name": "Foo", "price": 50.5}, - 200, - { - "item_id": 5, - "item": { - "name": "Foo", - "price": 50.5, - "description": None, - "tax": None, - }, - "q": "bar", - }, - ), - ("/items/5?q=bar", None, 200, {"item_id": 5, "q": "bar"}), - ("/items/5", None, 200, {"item_id": 5}), - ("/items/foo", None, 422, item_id_not_int), - ], -) -def test_post_body(path, body, expected_status, expected_response, client: TestClient): - response = client.put(path, json=body) - assert response.status_code == expected_status - assert response.json() == expected_response +def test_post_no_body_q_bar(client: TestClient): + response = client.put("/items/5?q=bar", json=None) + assert response.status_code == 200 + assert response.json() == {"item_id": 5, "q": "bar"} + + +@needs_py310 +def test_post_no_body(client: TestClient): + response = client.put("/items/5", json=None) + assert response.status_code == 200 + assert response.json() == {"item_id": 5} + + +@needs_py310 +def test_post_id_foo(client: TestClient): + response = client.put("/items/foo", json=None) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "int_parsing", + "loc": ["path", "item_id"], + "msg": "Input should be a valid integer, unable to parse string as an integer", + "input": "foo", + "url": match_pydantic_error_url("int_parsing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["path", "item_id"], + "msg": "value is not a valid integer", + "type": "type_error.integer", + } + ] + } + ) @needs_py310 @@ -58,7 +79,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { @@ -95,7 +116,16 @@ def test_openapi_schema(client: TestClient): }, { "required": False, - "schema": {"title": "Q", "type": "string"}, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Q", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Q", "type": "string"} + ), "name": "q", "in": "query", }, @@ -103,7 +133,19 @@ def test_openapi_schema(client: TestClient): "requestBody": { "content": { "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} + "schema": IsDict( + { + "anyOf": [ + {"$ref": "#/components/schemas/Item"}, + {"type": "null"}, + ], + "title": "Item", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"$ref": "#/components/schemas/Item"} + ) } } }, @@ -118,9 +160,27 @@ def test_openapi_schema(client: TestClient): "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, + "description": IsDict( + { + "title": "Description", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Description", "type": "string"} + ), "price": {"title": "Price", "type": "number"}, - "description": {"title": "Description", "type": "string"}, - "tax": {"title": "Tax", "type": "number"}, + "tax": IsDict( + { + "title": "Tax", + "anyOf": [{"type": "number"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Tax", "type": "number"} + ), }, }, "ValidationError": { diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial003.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial003.py index b34377a28c357..2046579a94c41 100644 --- a/tests/test_tutorial/test_body_multiple_params/test_tutorial003.py +++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial003.py @@ -1,96 +1,151 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url -from docs_src.body_multiple_params.tutorial003 import app -client = TestClient(app) +@pytest.fixture(name="client") +def get_client(): + from docs_src.body_multiple_params.tutorial003 import app + client = TestClient(app) + return client -# Test required and embedded body parameters with no bodies sent -@pytest.mark.parametrize( - "path,body,expected_status,expected_response", - [ - ( - "/items/5", - { - "importance": 2, - "item": {"name": "Foo", "price": 50.5}, - "user": {"username": "Dave"}, - }, - 200, - { - "item_id": 5, - "importance": 2, - "item": { - "name": "Foo", - "price": 50.5, - "description": None, - "tax": None, - }, - "user": {"username": "Dave", "full_name": None}, - }, - ), - ( - "/items/5", - None, - 422, - { - "detail": [ - { - "loc": ["body", "item"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "user"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "importance"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - }, - ), - ( - "/items/5", - [], - 422, - { - "detail": [ - { - "loc": ["body", "item"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "user"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "importance"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - }, - ), - ], -) -def test_post_body(path, body, expected_status, expected_response): - response = client.put(path, json=body) - assert response.status_code == expected_status - assert response.json() == expected_response + +def test_post_body_valid(client: TestClient): + response = client.put( + "/items/5", + json={ + "importance": 2, + "item": {"name": "Foo", "price": 50.5}, + "user": {"username": "Dave"}, + }, + ) + assert response.status_code == 200 + assert response.json() == { + "item_id": 5, + "importance": 2, + "item": { + "name": "Foo", + "price": 50.5, + "description": None, + "tax": None, + }, + "user": {"username": "Dave", "full_name": None}, + } + + +def test_post_body_no_data(client: TestClient): + response = client.put("/items/5", json=None) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "item"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "user"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "importance"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "item"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "user"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "importance"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) -def test_openapi_schema(): +def test_post_body_empty_list(client: TestClient): + response = client.put("/items/5", json=[]) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "item"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "user"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "importance"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "item"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "user"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "importance"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) + + +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { @@ -142,9 +197,27 @@ def test_openapi_schema(): "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, + "description": IsDict( + { + "title": "Description", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Description", "type": "string"} + ), "price": {"title": "Price", "type": "number"}, - "description": {"title": "Description", "type": "string"}, - "tax": {"title": "Tax", "type": "number"}, + "tax": IsDict( + { + "title": "Tax", + "anyOf": [{"type": "number"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Tax", "type": "number"} + ), }, }, "User": { @@ -153,7 +226,16 @@ def test_openapi_schema(): "type": "object", "properties": { "username": {"title": "Username", "type": "string"}, - "full_name": {"title": "Full Name", "type": "string"}, + "full_name": IsDict( + { + "title": "Full Name", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Full Name", "type": "string"} + ), }, }, "Body_update_item_items__item_id__put": { diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an.py index 9b8d5e15baa28..1282483e0732b 100644 --- a/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an.py +++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an.py @@ -1,96 +1,151 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url -from docs_src.body_multiple_params.tutorial003_an import app -client = TestClient(app) +@pytest.fixture(name="client") +def get_client(): + from docs_src.body_multiple_params.tutorial003_an import app + client = TestClient(app) + return client -# Test required and embedded body parameters with no bodies sent -@pytest.mark.parametrize( - "path,body,expected_status,expected_response", - [ - ( - "/items/5", - { - "importance": 2, - "item": {"name": "Foo", "price": 50.5}, - "user": {"username": "Dave"}, - }, - 200, - { - "item_id": 5, - "importance": 2, - "item": { - "name": "Foo", - "price": 50.5, - "description": None, - "tax": None, - }, - "user": {"username": "Dave", "full_name": None}, - }, - ), - ( - "/items/5", - None, - 422, - { - "detail": [ - { - "loc": ["body", "item"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "user"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "importance"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - }, - ), - ( - "/items/5", - [], - 422, - { - "detail": [ - { - "loc": ["body", "item"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "user"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "importance"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - }, - ), - ], -) -def test_post_body(path, body, expected_status, expected_response): - response = client.put(path, json=body) - assert response.status_code == expected_status - assert response.json() == expected_response + +def test_post_body_valid(client: TestClient): + response = client.put( + "/items/5", + json={ + "importance": 2, + "item": {"name": "Foo", "price": 50.5}, + "user": {"username": "Dave"}, + }, + ) + assert response.status_code == 200 + assert response.json() == { + "item_id": 5, + "importance": 2, + "item": { + "name": "Foo", + "price": 50.5, + "description": None, + "tax": None, + }, + "user": {"username": "Dave", "full_name": None}, + } + + +def test_post_body_no_data(client: TestClient): + response = client.put("/items/5", json=None) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "item"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "user"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "importance"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "item"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "user"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "importance"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) -def test_openapi_schema(): +def test_post_body_empty_list(client: TestClient): + response = client.put("/items/5", json=[]) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "item"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "user"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "importance"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "item"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "user"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "importance"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) + + +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { @@ -142,9 +197,27 @@ def test_openapi_schema(): "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, + "description": IsDict( + { + "title": "Description", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Description", "type": "string"} + ), "price": {"title": "Price", "type": "number"}, - "description": {"title": "Description", "type": "string"}, - "tax": {"title": "Tax", "type": "number"}, + "tax": IsDict( + { + "title": "Tax", + "anyOf": [{"type": "number"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Tax", "type": "number"} + ), }, }, "User": { @@ -153,7 +226,16 @@ def test_openapi_schema(): "type": "object", "properties": { "username": {"title": "Username", "type": "string"}, - "full_name": {"title": "Full Name", "type": "string"}, + "full_name": IsDict( + { + "title": "Full Name", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Full Name", "type": "string"} + ), }, }, "Body_update_item_items__item_id__put": { diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an_py310.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an_py310.py index f8af555fcd791..577c079d00fbd 100644 --- a/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an_py310.py +++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an_py310.py @@ -1,5 +1,7 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url from ...utils import needs_py310 @@ -12,85 +14,136 @@ def get_client(): return client -# Test required and embedded body parameters with no bodies sent @needs_py310 -@pytest.mark.parametrize( - "path,body,expected_status,expected_response", - [ - ( - "/items/5", - { - "importance": 2, - "item": {"name": "Foo", "price": 50.5}, - "user": {"username": "Dave"}, - }, - 200, - { - "item_id": 5, - "importance": 2, - "item": { - "name": "Foo", - "price": 50.5, - "description": None, - "tax": None, - }, - "user": {"username": "Dave", "full_name": None}, - }, - ), - ( - "/items/5", - None, - 422, - { - "detail": [ - { - "loc": ["body", "item"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "user"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "importance"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - }, - ), - ( - "/items/5", - [], - 422, - { - "detail": [ - { - "loc": ["body", "item"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "user"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "importance"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - }, - ), - ], -) -def test_post_body(path, body, expected_status, expected_response, client: TestClient): - response = client.put(path, json=body) - assert response.status_code == expected_status - assert response.json() == expected_response +def test_post_body_valid(client: TestClient): + response = client.put( + "/items/5", + json={ + "importance": 2, + "item": {"name": "Foo", "price": 50.5}, + "user": {"username": "Dave"}, + }, + ) + assert response.status_code == 200 + assert response.json() == { + "item_id": 5, + "importance": 2, + "item": { + "name": "Foo", + "price": 50.5, + "description": None, + "tax": None, + }, + "user": {"username": "Dave", "full_name": None}, + } + + +@needs_py310 +def test_post_body_no_data(client: TestClient): + response = client.put("/items/5", json=None) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "item"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "user"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "importance"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "item"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "user"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "importance"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) + + +@needs_py310 +def test_post_body_empty_list(client: TestClient): + response = client.put("/items/5", json=[]) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "item"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "user"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "importance"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "item"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "user"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "importance"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) @needs_py310 @@ -98,7 +151,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { @@ -150,9 +203,27 @@ def test_openapi_schema(client: TestClient): "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, + "description": IsDict( + { + "title": "Description", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Description", "type": "string"} + ), "price": {"title": "Price", "type": "number"}, - "description": {"title": "Description", "type": "string"}, - "tax": {"title": "Tax", "type": "number"}, + "tax": IsDict( + { + "title": "Tax", + "anyOf": [{"type": "number"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Tax", "type": "number"} + ), }, }, "User": { @@ -161,7 +232,16 @@ def test_openapi_schema(client: TestClient): "type": "object", "properties": { "username": {"title": "Username", "type": "string"}, - "full_name": {"title": "Full Name", "type": "string"}, + "full_name": IsDict( + { + "title": "Full Name", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Full Name", "type": "string"} + ), }, }, "Body_update_item_items__item_id__put": { diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an_py39.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an_py39.py index 06e2c3146f699..0ec04151ccf4c 100644 --- a/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an_py39.py +++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an_py39.py @@ -1,5 +1,7 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url from ...utils import needs_py39 @@ -12,85 +14,136 @@ def get_client(): return client -# Test required and embedded body parameters with no bodies sent @needs_py39 -@pytest.mark.parametrize( - "path,body,expected_status,expected_response", - [ - ( - "/items/5", - { - "importance": 2, - "item": {"name": "Foo", "price": 50.5}, - "user": {"username": "Dave"}, - }, - 200, - { - "item_id": 5, - "importance": 2, - "item": { - "name": "Foo", - "price": 50.5, - "description": None, - "tax": None, - }, - "user": {"username": "Dave", "full_name": None}, - }, - ), - ( - "/items/5", - None, - 422, - { - "detail": [ - { - "loc": ["body", "item"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "user"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "importance"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - }, - ), - ( - "/items/5", - [], - 422, - { - "detail": [ - { - "loc": ["body", "item"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "user"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "importance"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - }, - ), - ], -) -def test_post_body(path, body, expected_status, expected_response, client: TestClient): - response = client.put(path, json=body) - assert response.status_code == expected_status - assert response.json() == expected_response +def test_post_body_valid(client: TestClient): + response = client.put( + "/items/5", + json={ + "importance": 2, + "item": {"name": "Foo", "price": 50.5}, + "user": {"username": "Dave"}, + }, + ) + assert response.status_code == 200 + assert response.json() == { + "item_id": 5, + "importance": 2, + "item": { + "name": "Foo", + "price": 50.5, + "description": None, + "tax": None, + }, + "user": {"username": "Dave", "full_name": None}, + } + + +@needs_py39 +def test_post_body_no_data(client: TestClient): + response = client.put("/items/5", json=None) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "item"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "user"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "importance"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "item"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "user"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "importance"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) + + +@needs_py39 +def test_post_body_empty_list(client: TestClient): + response = client.put("/items/5", json=[]) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "item"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "user"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "importance"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "item"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "user"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "importance"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) @needs_py39 @@ -98,7 +151,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { @@ -150,9 +203,27 @@ def test_openapi_schema(client: TestClient): "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, + "description": IsDict( + { + "title": "Description", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Description", "type": "string"} + ), "price": {"title": "Price", "type": "number"}, - "description": {"title": "Description", "type": "string"}, - "tax": {"title": "Tax", "type": "number"}, + "tax": IsDict( + { + "title": "Tax", + "anyOf": [{"type": "number"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Tax", "type": "number"} + ), }, }, "User": { @@ -161,7 +232,16 @@ def test_openapi_schema(client: TestClient): "type": "object", "properties": { "username": {"title": "Username", "type": "string"}, - "full_name": {"title": "Full Name", "type": "string"}, + "full_name": IsDict( + { + "title": "Full Name", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Full Name", "type": "string"} + ), }, }, "Body_update_item_items__item_id__put": { diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial003_py310.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial003_py310.py index 82c5fb1013209..9caf5fe6cbe13 100644 --- a/tests/test_tutorial/test_body_multiple_params/test_tutorial003_py310.py +++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial003_py310.py @@ -1,5 +1,7 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url from ...utils import needs_py310 @@ -12,85 +14,136 @@ def get_client(): return client -# Test required and embedded body parameters with no bodies sent @needs_py310 -@pytest.mark.parametrize( - "path,body,expected_status,expected_response", - [ - ( - "/items/5", - { - "importance": 2, - "item": {"name": "Foo", "price": 50.5}, - "user": {"username": "Dave"}, - }, - 200, - { - "item_id": 5, - "importance": 2, - "item": { - "name": "Foo", - "price": 50.5, - "description": None, - "tax": None, - }, - "user": {"username": "Dave", "full_name": None}, - }, - ), - ( - "/items/5", - None, - 422, - { - "detail": [ - { - "loc": ["body", "item"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "user"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "importance"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - }, - ), - ( - "/items/5", - [], - 422, - { - "detail": [ - { - "loc": ["body", "item"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "user"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "importance"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - }, - ), - ], -) -def test_post_body(path, body, expected_status, expected_response, client: TestClient): - response = client.put(path, json=body) - assert response.status_code == expected_status - assert response.json() == expected_response +def test_post_body_valid(client: TestClient): + response = client.put( + "/items/5", + json={ + "importance": 2, + "item": {"name": "Foo", "price": 50.5}, + "user": {"username": "Dave"}, + }, + ) + assert response.status_code == 200 + assert response.json() == { + "item_id": 5, + "importance": 2, + "item": { + "name": "Foo", + "price": 50.5, + "description": None, + "tax": None, + }, + "user": {"username": "Dave", "full_name": None}, + } + + +@needs_py310 +def test_post_body_no_data(client: TestClient): + response = client.put("/items/5", json=None) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "item"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "user"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "importance"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "item"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "user"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "importance"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) + + +@needs_py310 +def test_post_body_empty_list(client: TestClient): + response = client.put("/items/5", json=[]) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "item"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "user"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "importance"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "item"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "user"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "importance"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) @needs_py310 @@ -98,7 +151,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { @@ -150,9 +203,27 @@ def test_openapi_schema(client: TestClient): "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, + "description": IsDict( + { + "title": "Description", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Description", "type": "string"} + ), "price": {"title": "Price", "type": "number"}, - "description": {"title": "Description", "type": "string"}, - "tax": {"title": "Tax", "type": "number"}, + "tax": IsDict( + { + "title": "Tax", + "anyOf": [{"type": "number"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Tax", "type": "number"} + ), }, }, "User": { @@ -161,7 +232,16 @@ def test_openapi_schema(client: TestClient): "type": "object", "properties": { "username": {"title": "Username", "type": "string"}, - "full_name": {"title": "Full Name", "type": "string"}, + "full_name": IsDict( + { + "title": "Full Name", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Full Name", "type": "string"} + ), }, }, "Body_update_item_items__item_id__put": { diff --git a/tests/test_tutorial/test_body_nested_models/test_tutorial009.py b/tests/test_tutorial/test_body_nested_models/test_tutorial009.py index 378c241975258..f4a76be4496ba 100644 --- a/tests/test_tutorial/test_body_nested_models/test_tutorial009.py +++ b/tests/test_tutorial/test_body_nested_models/test_tutorial009.py @@ -1,37 +1,59 @@ +import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url -from docs_src.body_nested_models.tutorial009 import app -client = TestClient(app) +@pytest.fixture(name="client") +def get_client(): + from docs_src.body_nested_models.tutorial009 import app + client = TestClient(app) + return client -def test_post_body(): + +def test_post_body(client: TestClient): data = {"2": 2.2, "3": 3.3} response = client.post("/index-weights/", json=data) assert response.status_code == 200, response.text assert response.json() == data -def test_post_invalid_body(): +def test_post_invalid_body(client: TestClient): data = {"foo": 2.2, "3": 3.3} response = client.post("/index-weights/", json=data) assert response.status_code == 422, response.text - assert response.json() == { - "detail": [ - { - "loc": ["body", "__key__"], - "msg": "value is not a valid integer", - "type": "type_error.integer", - } - ] - } + assert response.json() == IsDict( + { + "detail": [ + { + "type": "int_parsing", + "loc": ["body", "foo", "[key]"], + "msg": "Input should be a valid integer, unable to parse string as an integer", + "input": "foo", + "url": match_pydantic_error_url("int_parsing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "__key__"], + "msg": "value is not a valid integer", + "type": "type_error.integer", + } + ] + } + ) -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/index-weights/": { diff --git a/tests/test_tutorial/test_body_nested_models/test_tutorial009_py39.py b/tests/test_tutorial/test_body_nested_models/test_tutorial009_py39.py index 5ca63a92bd467..8ab9bcac83b1a 100644 --- a/tests/test_tutorial/test_body_nested_models/test_tutorial009_py39.py +++ b/tests/test_tutorial/test_body_nested_models/test_tutorial009_py39.py @@ -1,5 +1,7 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url from ...utils import needs_py39 @@ -25,15 +27,30 @@ def test_post_invalid_body(client: TestClient): data = {"foo": 2.2, "3": 3.3} response = client.post("/index-weights/", json=data) assert response.status_code == 422, response.text - assert response.json() == { - "detail": [ - { - "loc": ["body", "__key__"], - "msg": "value is not a valid integer", - "type": "type_error.integer", - } - ] - } + assert response.json() == IsDict( + { + "detail": [ + { + "type": "int_parsing", + "loc": ["body", "foo", "[key]"], + "msg": "Input should be a valid integer, unable to parse string as an integer", + "input": "foo", + "url": match_pydantic_error_url("int_parsing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "__key__"], + "msg": "value is not a valid integer", + "type": "type_error.integer", + } + ] + } + ) @needs_py39 @@ -41,7 +58,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/index-weights/": { diff --git a/tests/test_tutorial/test_body_updates/test_tutorial001.py b/tests/test_tutorial/test_body_updates/test_tutorial001.py index 939bf44e0a774..e586534a071b1 100644 --- a/tests/test_tutorial/test_body_updates/test_tutorial001.py +++ b/tests/test_tutorial/test_body_updates/test_tutorial001.py @@ -1,11 +1,18 @@ +import pytest from fastapi.testclient import TestClient -from docs_src.body_updates.tutorial001 import app +from ...utils import needs_pydanticv1, needs_pydanticv2 -client = TestClient(app) +@pytest.fixture(name="client") +def get_client(): + from docs_src.body_updates.tutorial001 import app -def test_get(): + client = TestClient(app) + return client + + +def test_get(client: TestClient): response = client.get("/items/baz") assert response.status_code == 200, response.text assert response.json() == { @@ -17,7 +24,7 @@ def test_get(): } -def test_put(): +def test_put(client: TestClient): response = client.put( "/items/bar", json={"name": "Barz", "price": 3, "description": None} ) @@ -30,11 +37,155 @@ def test_put(): } -def test_openapi_schema(): +@needs_pydanticv2 +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/items/{item_id}": { + "get": { + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Item"} + } + }, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + "summary": "Read Item", + "operationId": "read_item_items__item_id__get", + "parameters": [ + { + "required": True, + "schema": {"title": "Item Id", "type": "string"}, + "name": "item_id", + "in": "path", + } + ], + }, + "put": { + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Item"} + } + }, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + "summary": "Update Item", + "operationId": "update_item_items__item_id__put", + "parameters": [ + { + "required": True, + "schema": {"title": "Item Id", "type": "string"}, + "name": "item_id", + "in": "path", + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Item"} + } + }, + "required": True, + }, + }, + } + }, + "components": { + "schemas": { + "Item": { + "type": "object", + "title": "Item", + "properties": { + "name": { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Name", + }, + "description": { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Description", + }, + "price": { + "anyOf": [{"type": "number"}, {"type": "null"}], + "title": "Price", + }, + "tax": {"title": "Tax", "type": "number", "default": 10.5}, + "tags": { + "title": "Tags", + "type": "array", + "items": {"type": "string"}, + "default": [], + }, + }, + }, + "ValidationError": { + "title": "ValidationError", + "required": ["loc", "msg", "type"], + "type": "object", + "properties": { + "loc": { + "title": "Location", + "type": "array", + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + }, + "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"}, + } + }, + }, + } + }, + } + + +# TODO: remove when deprecating Pydantic v1 +@needs_pydanticv1 +def test_openapi_schema_pv1(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { diff --git a/tests/test_tutorial/test_body_updates/test_tutorial001_py310.py b/tests/test_tutorial/test_body_updates/test_tutorial001_py310.py index 5f50f2071ae43..6bc969d43a831 100644 --- a/tests/test_tutorial/test_body_updates/test_tutorial001_py310.py +++ b/tests/test_tutorial/test_body_updates/test_tutorial001_py310.py @@ -1,7 +1,7 @@ import pytest from fastapi.testclient import TestClient -from ...utils import needs_py310 +from ...utils import needs_py310, needs_pydanticv1, needs_pydanticv2 @pytest.fixture(name="client") @@ -40,11 +40,156 @@ def test_put(client: TestClient): @needs_py310 +@needs_pydanticv2 def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/items/{item_id}": { + "get": { + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Item"} + } + }, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + "summary": "Read Item", + "operationId": "read_item_items__item_id__get", + "parameters": [ + { + "required": True, + "schema": {"title": "Item Id", "type": "string"}, + "name": "item_id", + "in": "path", + } + ], + }, + "put": { + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Item"} + } + }, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + "summary": "Update Item", + "operationId": "update_item_items__item_id__put", + "parameters": [ + { + "required": True, + "schema": {"title": "Item Id", "type": "string"}, + "name": "item_id", + "in": "path", + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Item"} + } + }, + "required": True, + }, + }, + } + }, + "components": { + "schemas": { + "Item": { + "type": "object", + "title": "Item", + "properties": { + "name": { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Name", + }, + "description": { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Description", + }, + "price": { + "anyOf": [{"type": "number"}, {"type": "null"}], + "title": "Price", + }, + "tax": {"title": "Tax", "type": "number", "default": 10.5}, + "tags": { + "title": "Tags", + "type": "array", + "items": {"type": "string"}, + "default": [], + }, + }, + }, + "ValidationError": { + "title": "ValidationError", + "required": ["loc", "msg", "type"], + "type": "object", + "properties": { + "loc": { + "title": "Location", + "type": "array", + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + }, + "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"}, + } + }, + }, + } + }, + } + + +# TODO: remove when deprecating Pydantic v1 +@needs_py310 +@needs_pydanticv1 +def test_openapi_schema_pv1(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { diff --git a/tests/test_tutorial/test_body_updates/test_tutorial001_py39.py b/tests/test_tutorial/test_body_updates/test_tutorial001_py39.py index d4fdabce66c75..a1edb33707fc0 100644 --- a/tests/test_tutorial/test_body_updates/test_tutorial001_py39.py +++ b/tests/test_tutorial/test_body_updates/test_tutorial001_py39.py @@ -1,7 +1,7 @@ import pytest from fastapi.testclient import TestClient -from ...utils import needs_py39 +from ...utils import needs_py39, needs_pydanticv1, needs_pydanticv2 @pytest.fixture(name="client") @@ -40,11 +40,156 @@ def test_put(client: TestClient): @needs_py39 +@needs_pydanticv2 def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/items/{item_id}": { + "get": { + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Item"} + } + }, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + "summary": "Read Item", + "operationId": "read_item_items__item_id__get", + "parameters": [ + { + "required": True, + "schema": {"title": "Item Id", "type": "string"}, + "name": "item_id", + "in": "path", + } + ], + }, + "put": { + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Item"} + } + }, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + "summary": "Update Item", + "operationId": "update_item_items__item_id__put", + "parameters": [ + { + "required": True, + "schema": {"title": "Item Id", "type": "string"}, + "name": "item_id", + "in": "path", + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Item"} + } + }, + "required": True, + }, + }, + } + }, + "components": { + "schemas": { + "Item": { + "type": "object", + "title": "Item", + "properties": { + "name": { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Name", + }, + "description": { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Description", + }, + "price": { + "anyOf": [{"type": "number"}, {"type": "null"}], + "title": "Price", + }, + "tax": {"title": "Tax", "type": "number", "default": 10.5}, + "tags": { + "title": "Tags", + "type": "array", + "items": {"type": "string"}, + "default": [], + }, + }, + }, + "ValidationError": { + "title": "ValidationError", + "required": ["loc", "msg", "type"], + "type": "object", + "properties": { + "loc": { + "title": "Location", + "type": "array", + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + }, + "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"}, + } + }, + }, + } + }, + } + + +# TODO: remove when deprecating Pydantic v1 +@needs_py39 +@needs_pydanticv1 +def test_openapi_schema_pv1(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { diff --git a/tests/test_tutorial/test_conditional_openapi/test_tutorial001.py b/tests/test_tutorial/test_conditional_openapi/test_tutorial001.py index c1d8fd8051e6d..b098f259c2f1a 100644 --- a/tests/test_tutorial/test_conditional_openapi/test_tutorial001.py +++ b/tests/test_tutorial/test_conditional_openapi/test_tutorial001.py @@ -2,13 +2,23 @@ from fastapi.testclient import TestClient -from docs_src.conditional_openapi import tutorial001 +from ...utils import needs_pydanticv2 -def test_disable_openapi(monkeypatch): - monkeypatch.setenv("OPENAPI_URL", "") +def get_client() -> TestClient: + from docs_src.conditional_openapi import tutorial001 + importlib.reload(tutorial001) + client = TestClient(tutorial001.app) + return client + + +@needs_pydanticv2 +def test_disable_openapi(monkeypatch): + monkeypatch.setenv("OPENAPI_URL", "") + # Load the client after setting the env var + client = get_client() response = client.get("/openapi.json") assert response.status_code == 404, response.text response = client.get("/docs") @@ -17,23 +27,24 @@ def test_disable_openapi(monkeypatch): assert response.status_code == 404, response.text +@needs_pydanticv2 def test_root(): - client = TestClient(tutorial001.app) + client = get_client() response = client.get("/") assert response.status_code == 200 assert response.json() == {"message": "Hello World"} +@needs_pydanticv2 def test_default_openapi(): - importlib.reload(tutorial001) - client = TestClient(tutorial001.app) + client = get_client() response = client.get("/docs") assert response.status_code == 200, response.text response = client.get("/redoc") assert response.status_code == 200, response.text response = client.get("/openapi.json") assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/": { diff --git a/tests/test_tutorial/test_sql_databases_peewee/__init__.py b/tests/test_tutorial/test_configure_swagger_ui/__init__.py similarity index 100% rename from tests/test_tutorial/test_sql_databases_peewee/__init__.py rename to tests/test_tutorial/test_configure_swagger_ui/__init__.py diff --git a/tests/test_tutorial/test_extending_openapi/test_tutorial003.py b/tests/test_tutorial/test_configure_swagger_ui/test_tutorial001.py similarity index 95% rename from tests/test_tutorial/test_extending_openapi/test_tutorial003.py rename to tests/test_tutorial/test_configure_swagger_ui/test_tutorial001.py index 0184dd9f8384b..72db54bd20271 100644 --- a/tests/test_tutorial/test_extending_openapi/test_tutorial003.py +++ b/tests/test_tutorial/test_configure_swagger_ui/test_tutorial001.py @@ -1,6 +1,6 @@ from fastapi.testclient import TestClient -from docs_src.extending_openapi.tutorial003 import app +from docs_src.configure_swagger_ui.tutorial001 import app client = TestClient(app) diff --git a/tests/test_tutorial/test_extending_openapi/test_tutorial004.py b/tests/test_tutorial/test_configure_swagger_ui/test_tutorial002.py similarity index 96% rename from tests/test_tutorial/test_extending_openapi/test_tutorial004.py rename to tests/test_tutorial/test_configure_swagger_ui/test_tutorial002.py index 4f7615126a0cd..1669011885043 100644 --- a/tests/test_tutorial/test_extending_openapi/test_tutorial004.py +++ b/tests/test_tutorial/test_configure_swagger_ui/test_tutorial002.py @@ -1,6 +1,6 @@ from fastapi.testclient import TestClient -from docs_src.extending_openapi.tutorial004 import app +from docs_src.configure_swagger_ui.tutorial002 import app client = TestClient(app) diff --git a/tests/test_tutorial/test_extending_openapi/test_tutorial005.py b/tests/test_tutorial/test_configure_swagger_ui/test_tutorial003.py similarity index 96% rename from tests/test_tutorial/test_extending_openapi/test_tutorial005.py rename to tests/test_tutorial/test_configure_swagger_ui/test_tutorial003.py index 24aeb93db32ec..187e89ace0dca 100644 --- a/tests/test_tutorial/test_extending_openapi/test_tutorial005.py +++ b/tests/test_tutorial/test_configure_swagger_ui/test_tutorial003.py @@ -1,6 +1,6 @@ from fastapi.testclient import TestClient -from docs_src.extending_openapi.tutorial005 import app +from docs_src.configure_swagger_ui.tutorial003 import app client = TestClient(app) diff --git a/tests/test_tutorial/test_cookie_params/test_tutorial001.py b/tests/test_tutorial/test_cookie_params/test_tutorial001.py index c3511d129efa9..7d0e669abafd1 100644 --- a/tests/test_tutorial/test_cookie_params/test_tutorial001.py +++ b/tests/test_tutorial/test_cookie_params/test_tutorial001.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient from docs_src.cookie_params.tutorial001 import app @@ -30,7 +31,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200 assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { @@ -56,7 +57,16 @@ def test_openapi_schema(): "parameters": [ { "required": False, - "schema": {"title": "Ads Id", "type": "string"}, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Ads Id", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Ads Id", "type": "string"} + ), "name": "ads_id", "in": "cookie", } diff --git a/tests/test_tutorial/test_cookie_params/test_tutorial001_an.py b/tests/test_tutorial/test_cookie_params/test_tutorial001_an.py index f4f94c09dcc59..2505876c87ec9 100644 --- a/tests/test_tutorial/test_cookie_params/test_tutorial001_an.py +++ b/tests/test_tutorial/test_cookie_params/test_tutorial001_an.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient from docs_src.cookie_params.tutorial001_an import app @@ -30,7 +31,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200 assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { @@ -56,7 +57,16 @@ def test_openapi_schema(): "parameters": [ { "required": False, - "schema": {"title": "Ads Id", "type": "string"}, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Ads Id", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Ads Id", "type": "string"} + ), "name": "ads_id", "in": "cookie", } diff --git a/tests/test_tutorial/test_cookie_params/test_tutorial001_an_py310.py b/tests/test_tutorial/test_cookie_params/test_tutorial001_an_py310.py index a80f10f810564..108f78b9c839a 100644 --- a/tests/test_tutorial/test_cookie_params/test_tutorial001_an_py310.py +++ b/tests/test_tutorial/test_cookie_params/test_tutorial001_an_py310.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient from ...utils import needs_py310 @@ -36,7 +37,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200 assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { @@ -62,7 +63,16 @@ def test_openapi_schema(): "parameters": [ { "required": False, - "schema": {"title": "Ads Id", "type": "string"}, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Ads Id", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Ads Id", "type": "string"} + ), "name": "ads_id", "in": "cookie", } diff --git a/tests/test_tutorial/test_cookie_params/test_tutorial001_an_py39.py b/tests/test_tutorial/test_cookie_params/test_tutorial001_an_py39.py index 1be898c0922c0..8126a105236cc 100644 --- a/tests/test_tutorial/test_cookie_params/test_tutorial001_an_py39.py +++ b/tests/test_tutorial/test_cookie_params/test_tutorial001_an_py39.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient from ...utils import needs_py39 @@ -36,7 +37,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200 assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { @@ -62,7 +63,16 @@ def test_openapi_schema(): "parameters": [ { "required": False, - "schema": {"title": "Ads Id", "type": "string"}, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Ads Id", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Ads Id", "type": "string"} + ), "name": "ads_id", "in": "cookie", } diff --git a/tests/test_tutorial/test_cookie_params/test_tutorial001_py310.py b/tests/test_tutorial/test_cookie_params/test_tutorial001_py310.py index 7ba542c902990..6711fa5818d1f 100644 --- a/tests/test_tutorial/test_cookie_params/test_tutorial001_py310.py +++ b/tests/test_tutorial/test_cookie_params/test_tutorial001_py310.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient from ...utils import needs_py310 @@ -36,7 +37,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200 assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { @@ -62,7 +63,16 @@ def test_openapi_schema(): "parameters": [ { "required": False, - "schema": {"title": "Ads Id", "type": "string"}, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Ads Id", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Ads Id", "type": "string"} + ), "name": "ads_id", "in": "cookie", } diff --git a/tests/test_tutorial/test_custom_docs_ui/__init__.py b/tests/test_tutorial/test_custom_docs_ui/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/tests/test_tutorial/test_custom_docs_ui/test_tutorial001.py b/tests/test_tutorial/test_custom_docs_ui/test_tutorial001.py new file mode 100644 index 0000000000000..34a18b12ca4a7 --- /dev/null +++ b/tests/test_tutorial/test_custom_docs_ui/test_tutorial001.py @@ -0,0 +1,44 @@ +import os +from pathlib import Path + +import pytest +from fastapi.testclient import TestClient + + +@pytest.fixture(scope="module") +def client(): + static_dir: Path = Path(os.getcwd()) / "static" + print(static_dir) + static_dir.mkdir(exist_ok=True) + from docs_src.custom_docs_ui.tutorial001 import app + + with TestClient(app) as client: + yield client + static_dir.rmdir() + + +def test_swagger_ui_html(client: TestClient): + response = client.get("/docs") + assert response.status_code == 200, response.text + assert ( + "https://unpkg.com/swagger-ui-dist@5.9.0/swagger-ui-bundle.js" in response.text + ) + assert "https://unpkg.com/swagger-ui-dist@5.9.0/swagger-ui.css" in response.text + + +def test_swagger_ui_oauth2_redirect_html(client: TestClient): + response = client.get("/docs/oauth2-redirect") + assert response.status_code == 200, response.text + assert "window.opener.swaggerUIRedirectOauth2" in response.text + + +def test_redoc_html(client: TestClient): + response = client.get("/redoc") + assert response.status_code == 200, response.text + assert "https://unpkg.com/redoc@next/bundles/redoc.standalone.js" in response.text + + +def test_api(client: TestClient): + response = client.get("/users/john") + assert response.status_code == 200, response.text + assert response.json()["message"] == "Hello john" diff --git a/tests/test_tutorial/test_extending_openapi/test_tutorial002.py b/tests/test_tutorial/test_custom_docs_ui/test_tutorial002.py similarity index 95% rename from tests/test_tutorial/test_extending_openapi/test_tutorial002.py rename to tests/test_tutorial/test_custom_docs_ui/test_tutorial002.py index 654db2e4c8ab8..712618807c054 100644 --- a/tests/test_tutorial/test_extending_openapi/test_tutorial002.py +++ b/tests/test_tutorial/test_custom_docs_ui/test_tutorial002.py @@ -10,7 +10,7 @@ def client(): static_dir: Path = Path(os.getcwd()) / "static" print(static_dir) static_dir.mkdir(exist_ok=True) - from docs_src.extending_openapi.tutorial002 import app + from docs_src.custom_docs_ui.tutorial002 import app with TestClient(app) as client: yield client diff --git a/tests/test_tutorial/test_custom_request_and_route/test_tutorial002.py b/tests/test_tutorial/test_custom_request_and_route/test_tutorial002.py index d2d27f8a274bd..ad142ec887fae 100644 --- a/tests/test_tutorial/test_custom_request_and_route/test_tutorial002.py +++ b/tests/test_tutorial/test_custom_request_and_route/test_tutorial002.py @@ -1,4 +1,6 @@ +from dirty_equals import IsDict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url from docs_src.custom_request_and_route.tutorial002 import app @@ -12,16 +14,33 @@ def test_endpoint_works(): def test_exception_handler_body_access(): response = client.post("/", json={"numbers": [1, 2, 3]}) - - assert response.json() == { - "detail": { - "body": '{"numbers": [1, 2, 3]}', - "errors": [ - { - "loc": ["body"], - "msg": "value is not a valid list", - "type": "type_error.list", - } - ], + assert response.json() == IsDict( + { + "detail": { + "errors": [ + { + "type": "list_type", + "loc": ["body"], + "msg": "Input should be a valid list", + "input": {"numbers": [1, 2, 3]}, + "url": match_pydantic_error_url("list_type"), + } + ], + "body": '{"numbers": [1, 2, 3]}', + } + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": { + "body": '{"numbers": [1, 2, 3]}', + "errors": [ + { + "loc": ["body"], + "msg": "value is not a valid list", + "type": "type_error.list", + } + ], + } } - } + ) diff --git a/tests/test_tutorial/test_custom_response/test_tutorial001.py b/tests/test_tutorial/test_custom_response/test_tutorial001.py index da2ca8d620391..fc8362467362e 100644 --- a/tests/test_tutorial/test_custom_response/test_tutorial001.py +++ b/tests/test_tutorial/test_custom_response/test_tutorial001.py @@ -15,7 +15,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { diff --git a/tests/test_tutorial/test_custom_response/test_tutorial001b.py b/tests/test_tutorial/test_custom_response/test_tutorial001b.py index f681f5a9d0bd8..91e5c501e3fad 100644 --- a/tests/test_tutorial/test_custom_response/test_tutorial001b.py +++ b/tests/test_tutorial/test_custom_response/test_tutorial001b.py @@ -15,7 +15,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { diff --git a/tests/test_tutorial/test_custom_response/test_tutorial004.py b/tests/test_tutorial/test_custom_response/test_tutorial004.py index ef0ba34469aca..de60574f5e4ee 100644 --- a/tests/test_tutorial/test_custom_response/test_tutorial004.py +++ b/tests/test_tutorial/test_custom_response/test_tutorial004.py @@ -27,7 +27,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { diff --git a/tests/test_tutorial/test_custom_response/test_tutorial005.py b/tests/test_tutorial/test_custom_response/test_tutorial005.py index e4b5c15466949..889bf3e929f4b 100644 --- a/tests/test_tutorial/test_custom_response/test_tutorial005.py +++ b/tests/test_tutorial/test_custom_response/test_tutorial005.py @@ -15,7 +15,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/": { diff --git a/tests/test_tutorial/test_custom_response/test_tutorial006.py b/tests/test_tutorial/test_custom_response/test_tutorial006.py index 9f1b07bee96c9..2d0a2cd3f6517 100644 --- a/tests/test_tutorial/test_custom_response/test_tutorial006.py +++ b/tests/test_tutorial/test_custom_response/test_tutorial006.py @@ -15,7 +15,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/typer": { diff --git a/tests/test_tutorial/test_custom_response/test_tutorial006b.py b/tests/test_tutorial/test_custom_response/test_tutorial006b.py index cf204cbc05437..1739fd457076c 100644 --- a/tests/test_tutorial/test_custom_response/test_tutorial006b.py +++ b/tests/test_tutorial/test_custom_response/test_tutorial006b.py @@ -15,7 +15,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/fastapi": { diff --git a/tests/test_tutorial/test_custom_response/test_tutorial006c.py b/tests/test_tutorial/test_custom_response/test_tutorial006c.py index f196899acaa28..2675f2a93c5ee 100644 --- a/tests/test_tutorial/test_custom_response/test_tutorial006c.py +++ b/tests/test_tutorial/test_custom_response/test_tutorial006c.py @@ -8,14 +8,14 @@ def test_redirect_status_code(): response = client.get("/pydantic", follow_redirects=False) assert response.status_code == 302 - assert response.headers["location"] == "https://pydantic-docs.helpmanual.io/" + assert response.headers["location"] == "https://docs.pydantic.dev/" def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/pydantic": { diff --git a/tests/test_tutorial/test_dataclasses/test_tutorial001.py b/tests/test_tutorial/test_dataclasses/test_tutorial001.py index 26ae04c515441..9f1200f373c91 100644 --- a/tests/test_tutorial/test_dataclasses/test_tutorial001.py +++ b/tests/test_tutorial/test_dataclasses/test_tutorial001.py @@ -1,4 +1,6 @@ +from dirty_equals import IsDict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url from docs_src.dataclasses.tutorial001 import app @@ -19,22 +21,37 @@ def test_post_item(): def test_post_invalid_item(): response = client.post("/items/", json={"name": "Foo", "price": "invalid price"}) assert response.status_code == 422 - assert response.json() == { - "detail": [ - { - "loc": ["body", "price"], - "msg": "value is not a valid float", - "type": "type_error.float", - } - ] - } + assert response.json() == IsDict( + { + "detail": [ + { + "type": "float_parsing", + "loc": ["body", "price"], + "msg": "Input should be a valid number, unable to parse string as a number", + "input": "invalid price", + "url": match_pydantic_error_url("float_parsing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "price"], + "msg": "value is not a valid float", + "type": "type_error.float", + } + ] + } + ) def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200 assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { @@ -88,8 +105,26 @@ def test_openapi_schema(): "properties": { "name": {"title": "Name", "type": "string"}, "price": {"title": "Price", "type": "number"}, - "description": {"title": "Description", "type": "string"}, - "tax": {"title": "Tax", "type": "number"}, + "description": IsDict( + { + "title": "Description", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Description", "type": "string"} + ), + "tax": IsDict( + { + "title": "Tax", + "anyOf": [{"type": "number"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Tax", "type": "number"} + ), }, }, "ValidationError": { diff --git a/tests/test_tutorial/test_dataclasses/test_tutorial002.py b/tests/test_tutorial/test_dataclasses/test_tutorial002.py index 675e826b11eca..4146f4cd65dfe 100644 --- a/tests/test_tutorial/test_dataclasses/test_tutorial002.py +++ b/tests/test_tutorial/test_dataclasses/test_tutorial002.py @@ -1,3 +1,4 @@ +from dirty_equals import IsDict, IsOneOf from fastapi.testclient import TestClient from docs_src.dataclasses.tutorial002 import app @@ -20,9 +21,8 @@ def test_get_item(): def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200 - data = response.json() - assert data == { - "openapi": "3.0.2", + assert response.json() == { + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/next": { @@ -46,18 +46,50 @@ def test_openapi_schema(): "schemas": { "Item": { "title": "Item", - "required": ["name", "price"], + "required": IsOneOf( + ["name", "price", "tags", "description", "tax"], + # TODO: remove when deprecating Pydantic v1 + ["name", "price"], + ), "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, "price": {"title": "Price", "type": "number"}, - "tags": { - "title": "Tags", - "type": "array", - "items": {"type": "string"}, - }, - "description": {"title": "Description", "type": "string"}, - "tax": {"title": "Tax", "type": "number"}, + "tags": IsDict( + { + "title": "Tags", + "type": "array", + "items": {"type": "string"}, + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "Tags", + "type": "array", + "items": {"type": "string"}, + } + ), + "description": IsDict( + { + "title": "Description", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Description", "type": "string"} + ), + "tax": IsDict( + { + "title": "Tax", + "anyOf": [{"type": "number"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Tax", "type": "number"} + ), }, } } diff --git a/tests/test_tutorial/test_dataclasses/test_tutorial003.py b/tests/test_tutorial/test_dataclasses/test_tutorial003.py index f3378fe629978..dd0e36735eecf 100644 --- a/tests/test_tutorial/test_dataclasses/test_tutorial003.py +++ b/tests/test_tutorial/test_dataclasses/test_tutorial003.py @@ -2,6 +2,8 @@ from docs_src.dataclasses.tutorial003 import app +from ...utils import needs_pydanticv1, needs_pydanticv2 + client = TestClient(app) @@ -51,11 +53,149 @@ def test_get_authors(): ] +@needs_pydanticv2 def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200 assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/authors/{author_id}/items/": { + "post": { + "summary": "Create Author Items", + "operationId": "create_author_items_authors__author_id__items__post", + "parameters": [ + { + "required": True, + "schema": {"title": "Author Id", "type": "string"}, + "name": "author_id", + "in": "path", + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "title": "Items", + "type": "array", + "items": {"$ref": "#/components/schemas/Item"}, + } + } + }, + "required": True, + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Author"} + } + }, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + }, + "/authors/": { + "get": { + "summary": "Get Authors", + "operationId": "get_authors_authors__get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "title": "Response Get Authors Authors Get", + "type": "array", + "items": { + "$ref": "#/components/schemas/Author" + }, + } + } + }, + } + }, + } + }, + }, + "components": { + "schemas": { + "Author": { + "title": "Author", + "required": ["name"], + "type": "object", + "properties": { + "name": {"title": "Name", "type": "string"}, + "items": { + "title": "Items", + "type": "array", + "items": {"$ref": "#/components/schemas/Item"}, + }, + }, + }, + "HTTPValidationError": { + "title": "HTTPValidationError", + "type": "object", + "properties": { + "detail": { + "title": "Detail", + "type": "array", + "items": {"$ref": "#/components/schemas/ValidationError"}, + } + }, + }, + "Item": { + "title": "Item", + "required": ["name"], + "type": "object", + "properties": { + "name": {"title": "Name", "type": "string"}, + "description": { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Description", + }, + }, + }, + "ValidationError": { + "title": "ValidationError", + "required": ["loc", "msg", "type"], + "type": "object", + "properties": { + "loc": { + "title": "Location", + "type": "array", + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + }, + "msg": {"title": "Message", "type": "string"}, + "type": {"title": "Error Type", "type": "string"}, + }, + }, + } + }, + } + + +# TODO: remove when deprecating Pydantic v1 +@needs_pydanticv1 +def test_openapi_schema_pv1(): + response = client.get("/openapi.json") + assert response.status_code == 200 + assert response.json() == { + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/authors/{author_id}/items/": { diff --git a/tests/test_tutorial/test_dependencies/test_tutorial001.py b/tests/test_tutorial/test_dependencies/test_tutorial001.py index 974b9304fdbf0..d1324a64113ed 100644 --- a/tests/test_tutorial/test_dependencies/test_tutorial001.py +++ b/tests/test_tutorial/test_dependencies/test_tutorial001.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient from docs_src.dependencies.tutorial001 import app @@ -26,7 +27,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { @@ -52,7 +53,16 @@ def test_openapi_schema(): "parameters": [ { "required": False, - "schema": {"title": "Q", "type": "string"}, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Q", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Q", "type": "string"} + ), "name": "q", "in": "query", }, @@ -102,7 +112,16 @@ def test_openapi_schema(): "parameters": [ { "required": False, - "schema": {"title": "Q", "type": "string"}, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Q", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Q", "type": "string"} + ), "name": "q", "in": "query", }, diff --git a/tests/test_tutorial/test_dependencies/test_tutorial001_an.py b/tests/test_tutorial/test_dependencies/test_tutorial001_an.py index b1ca27ff8b0f9..79c2a1e10e495 100644 --- a/tests/test_tutorial/test_dependencies/test_tutorial001_an.py +++ b/tests/test_tutorial/test_dependencies/test_tutorial001_an.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient from docs_src.dependencies.tutorial001_an import app @@ -26,7 +27,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { @@ -52,7 +53,16 @@ def test_openapi_schema(): "parameters": [ { "required": False, - "schema": {"title": "Q", "type": "string"}, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Q", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Q", "type": "string"} + ), "name": "q", "in": "query", }, @@ -102,7 +112,16 @@ def test_openapi_schema(): "parameters": [ { "required": False, - "schema": {"title": "Q", "type": "string"}, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Q", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Q", "type": "string"} + ), "name": "q", "in": "query", }, diff --git a/tests/test_tutorial/test_dependencies/test_tutorial001_an_py310.py b/tests/test_tutorial/test_dependencies/test_tutorial001_an_py310.py index 70bed03f62862..7db55a1c55a5e 100644 --- a/tests/test_tutorial/test_dependencies/test_tutorial001_an_py310.py +++ b/tests/test_tutorial/test_dependencies/test_tutorial001_an_py310.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient from ...utils import needs_py310 @@ -34,7 +35,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { @@ -60,7 +61,16 @@ def test_openapi_schema(client: TestClient): "parameters": [ { "required": False, - "schema": {"title": "Q", "type": "string"}, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Q", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Q", "type": "string"} + ), "name": "q", "in": "query", }, @@ -110,7 +120,16 @@ def test_openapi_schema(client: TestClient): "parameters": [ { "required": False, - "schema": {"title": "Q", "type": "string"}, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Q", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Q", "type": "string"} + ), "name": "q", "in": "query", }, diff --git a/tests/test_tutorial/test_dependencies/test_tutorial001_an_py39.py b/tests/test_tutorial/test_dependencies/test_tutorial001_an_py39.py index 9c5723be88570..68c2dedb1ba87 100644 --- a/tests/test_tutorial/test_dependencies/test_tutorial001_an_py39.py +++ b/tests/test_tutorial/test_dependencies/test_tutorial001_an_py39.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient from ...utils import needs_py39 @@ -34,7 +35,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { @@ -60,7 +61,16 @@ def test_openapi_schema(client: TestClient): "parameters": [ { "required": False, - "schema": {"title": "Q", "type": "string"}, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Q", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Q", "type": "string"} + ), "name": "q", "in": "query", }, @@ -110,7 +120,16 @@ def test_openapi_schema(client: TestClient): "parameters": [ { "required": False, - "schema": {"title": "Q", "type": "string"}, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Q", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Q", "type": "string"} + ), "name": "q", "in": "query", }, diff --git a/tests/test_tutorial/test_dependencies/test_tutorial001_py310.py b/tests/test_tutorial/test_dependencies/test_tutorial001_py310.py index 1bcde4e9f47ec..381eecb63911c 100644 --- a/tests/test_tutorial/test_dependencies/test_tutorial001_py310.py +++ b/tests/test_tutorial/test_dependencies/test_tutorial001_py310.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient from ...utils import needs_py310 @@ -34,7 +35,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { @@ -60,7 +61,16 @@ def test_openapi_schema(client: TestClient): "parameters": [ { "required": False, - "schema": {"title": "Q", "type": "string"}, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Q", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Q", "type": "string"} + ), "name": "q", "in": "query", }, @@ -110,7 +120,16 @@ def test_openapi_schema(client: TestClient): "parameters": [ { "required": False, - "schema": {"title": "Q", "type": "string"}, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Q", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Q", "type": "string"} + ), "name": "q", "in": "query", }, diff --git a/tests/test_tutorial/test_dependencies/test_tutorial004.py b/tests/test_tutorial/test_dependencies/test_tutorial004.py index 298bc290d291b..5c5d34cfcc6df 100644 --- a/tests/test_tutorial/test_dependencies/test_tutorial004.py +++ b/tests/test_tutorial/test_dependencies/test_tutorial004.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient from docs_src.dependencies.tutorial004 import app @@ -64,7 +65,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { @@ -90,7 +91,16 @@ def test_openapi_schema(): "parameters": [ { "required": False, - "schema": {"title": "Q", "type": "string"}, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Q", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Q", "type": "string"} + ), "name": "q", "in": "query", }, diff --git a/tests/test_tutorial/test_dependencies/test_tutorial004_an.py b/tests/test_tutorial/test_dependencies/test_tutorial004_an.py index f985be8df058e..c5c1a1fb883c1 100644 --- a/tests/test_tutorial/test_dependencies/test_tutorial004_an.py +++ b/tests/test_tutorial/test_dependencies/test_tutorial004_an.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient from docs_src.dependencies.tutorial004_an import app @@ -64,7 +65,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { @@ -90,7 +91,16 @@ def test_openapi_schema(): "parameters": [ { "required": False, - "schema": {"title": "Q", "type": "string"}, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Q", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Q", "type": "string"} + ), "name": "q", "in": "query", }, diff --git a/tests/test_tutorial/test_dependencies/test_tutorial004_an_py310.py b/tests/test_tutorial/test_dependencies/test_tutorial004_an_py310.py index fc028670285c5..6fd093ddb14cb 100644 --- a/tests/test_tutorial/test_dependencies/test_tutorial004_an_py310.py +++ b/tests/test_tutorial/test_dependencies/test_tutorial004_an_py310.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient from ...utils import needs_py310 @@ -72,7 +73,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { @@ -98,7 +99,16 @@ def test_openapi_schema(client: TestClient): "parameters": [ { "required": False, - "schema": {"title": "Q", "type": "string"}, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Q", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Q", "type": "string"} + ), "name": "q", "in": "query", }, diff --git a/tests/test_tutorial/test_dependencies/test_tutorial004_an_py39.py b/tests/test_tutorial/test_dependencies/test_tutorial004_an_py39.py index 1e37673ed8b0e..fbbe84cc9483d 100644 --- a/tests/test_tutorial/test_dependencies/test_tutorial004_an_py39.py +++ b/tests/test_tutorial/test_dependencies/test_tutorial004_an_py39.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient from ...utils import needs_py39 @@ -72,7 +73,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { @@ -98,7 +99,16 @@ def test_openapi_schema(client: TestClient): "parameters": [ { "required": False, - "schema": {"title": "Q", "type": "string"}, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Q", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Q", "type": "string"} + ), "name": "q", "in": "query", }, diff --git a/tests/test_tutorial/test_dependencies/test_tutorial004_py310.py b/tests/test_tutorial/test_dependencies/test_tutorial004_py310.py index ab936ccdc0b30..845b098e79a33 100644 --- a/tests/test_tutorial/test_dependencies/test_tutorial004_py310.py +++ b/tests/test_tutorial/test_dependencies/test_tutorial004_py310.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient from ...utils import needs_py310 @@ -72,7 +73,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { @@ -98,7 +99,16 @@ def test_openapi_schema(client: TestClient): "parameters": [ { "required": False, - "schema": {"title": "Q", "type": "string"}, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Q", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Q", "type": "string"} + ), "name": "q", "in": "query", }, diff --git a/tests/test_tutorial/test_dependencies/test_tutorial006.py b/tests/test_tutorial/test_dependencies/test_tutorial006.py index 2e9c82d711208..704e389a5bbfc 100644 --- a/tests/test_tutorial/test_dependencies/test_tutorial006.py +++ b/tests/test_tutorial/test_dependencies/test_tutorial006.py @@ -1,4 +1,6 @@ +from dirty_equals import IsDict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url from docs_src.dependencies.tutorial006 import app @@ -8,20 +10,42 @@ def test_get_no_headers(): response = client.get("/items/") assert response.status_code == 422, response.text - assert response.json() == { - "detail": [ - { - "loc": ["header", "x-token"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["header", "x-key"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["header", "x-token"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["header", "x-key"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["header", "x-token"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["header", "x-key"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) def test_get_invalid_one_header(): @@ -54,7 +78,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { diff --git a/tests/test_tutorial/test_dependencies/test_tutorial006_an.py b/tests/test_tutorial/test_dependencies/test_tutorial006_an.py index 919066dcad779..5034fceba5e25 100644 --- a/tests/test_tutorial/test_dependencies/test_tutorial006_an.py +++ b/tests/test_tutorial/test_dependencies/test_tutorial006_an.py @@ -1,4 +1,6 @@ +from dirty_equals import IsDict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url from docs_src.dependencies.tutorial006_an import app @@ -8,20 +10,42 @@ def test_get_no_headers(): response = client.get("/items/") assert response.status_code == 422, response.text - assert response.json() == { - "detail": [ - { - "loc": ["header", "x-token"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["header", "x-key"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["header", "x-token"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["header", "x-key"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["header", "x-token"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["header", "x-key"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) def test_get_invalid_one_header(): @@ -54,7 +78,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { diff --git a/tests/test_tutorial/test_dependencies/test_tutorial006_an_py39.py b/tests/test_tutorial/test_dependencies/test_tutorial006_an_py39.py index c237184796ca8..3fc22dd3c2e6f 100644 --- a/tests/test_tutorial/test_dependencies/test_tutorial006_an_py39.py +++ b/tests/test_tutorial/test_dependencies/test_tutorial006_an_py39.py @@ -1,5 +1,7 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url from ...utils import needs_py39 @@ -16,20 +18,42 @@ def get_client(): def test_get_no_headers(client: TestClient): response = client.get("/items/") assert response.status_code == 422, response.text - assert response.json() == { - "detail": [ - { - "loc": ["header", "x-token"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["header", "x-key"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["header", "x-token"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["header", "x-key"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["header", "x-token"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["header", "x-key"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) @needs_py39 @@ -66,7 +90,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { diff --git a/tests/test_tutorial/test_dependencies/test_tutorial008b.py b/tests/test_tutorial/test_dependencies/test_tutorial008b.py new file mode 100644 index 0000000000000..86acba9e4ff95 --- /dev/null +++ b/tests/test_tutorial/test_dependencies/test_tutorial008b.py @@ -0,0 +1,23 @@ +from fastapi.testclient import TestClient + +from docs_src.dependencies.tutorial008b import app + +client = TestClient(app) + + +def test_get_no_item(): + response = client.get("/items/foo") + assert response.status_code == 404, response.text + assert response.json() == {"detail": "Item not found"} + + +def test_owner_error(): + response = client.get("/items/plumbus") + assert response.status_code == 400, response.text + assert response.json() == {"detail": "Owner error: Rick"} + + +def test_get_item(): + response = client.get("/items/portal-gun") + assert response.status_code == 200, response.text + assert response.json() == {"description": "Gun to create portals", "owner": "Rick"} diff --git a/tests/test_tutorial/test_dependencies/test_tutorial008b_an.py b/tests/test_tutorial/test_dependencies/test_tutorial008b_an.py new file mode 100644 index 0000000000000..7f51fc52a5133 --- /dev/null +++ b/tests/test_tutorial/test_dependencies/test_tutorial008b_an.py @@ -0,0 +1,23 @@ +from fastapi.testclient import TestClient + +from docs_src.dependencies.tutorial008b_an import app + +client = TestClient(app) + + +def test_get_no_item(): + response = client.get("/items/foo") + assert response.status_code == 404, response.text + assert response.json() == {"detail": "Item not found"} + + +def test_owner_error(): + response = client.get("/items/plumbus") + assert response.status_code == 400, response.text + assert response.json() == {"detail": "Owner error: Rick"} + + +def test_get_item(): + response = client.get("/items/portal-gun") + assert response.status_code == 200, response.text + assert response.json() == {"description": "Gun to create portals", "owner": "Rick"} diff --git a/tests/test_tutorial/test_dependencies/test_tutorial008b_an_py39.py b/tests/test_tutorial/test_dependencies/test_tutorial008b_an_py39.py new file mode 100644 index 0000000000000..7d24809a8a756 --- /dev/null +++ b/tests/test_tutorial/test_dependencies/test_tutorial008b_an_py39.py @@ -0,0 +1,33 @@ +import pytest +from fastapi.testclient import TestClient + +from ...utils import needs_py39 + + +@pytest.fixture(name="client") +def get_client(): + from docs_src.dependencies.tutorial008b_an_py39 import app + + client = TestClient(app) + return client + + +@needs_py39 +def test_get_no_item(client: TestClient): + response = client.get("/items/foo") + assert response.status_code == 404, response.text + assert response.json() == {"detail": "Item not found"} + + +@needs_py39 +def test_owner_error(client: TestClient): + response = client.get("/items/plumbus") + assert response.status_code == 400, response.text + assert response.json() == {"detail": "Owner error: Rick"} + + +@needs_py39 +def test_get_item(client: TestClient): + response = client.get("/items/portal-gun") + assert response.status_code == 200, response.text + assert response.json() == {"description": "Gun to create portals", "owner": "Rick"} diff --git a/tests/test_tutorial/test_dependencies/test_tutorial008c.py b/tests/test_tutorial/test_dependencies/test_tutorial008c.py new file mode 100644 index 0000000000000..27be8895a9496 --- /dev/null +++ b/tests/test_tutorial/test_dependencies/test_tutorial008c.py @@ -0,0 +1,38 @@ +import pytest +from fastapi.exceptions import FastAPIError +from fastapi.testclient import TestClient + + +@pytest.fixture(name="client") +def get_client(): + from docs_src.dependencies.tutorial008c import app + + client = TestClient(app) + return client + + +def test_get_no_item(client: TestClient): + response = client.get("/items/foo") + assert response.status_code == 404, response.text + assert response.json() == {"detail": "Item not found, there's only a plumbus here"} + + +def test_get(client: TestClient): + response = client.get("/items/plumbus") + assert response.status_code == 200, response.text + assert response.json() == "plumbus" + + +def test_fastapi_error(client: TestClient): + with pytest.raises(FastAPIError) as exc_info: + client.get("/items/portal-gun") + assert "No response object was returned" in exc_info.value.args[0] + + +def test_internal_server_error(): + from docs_src.dependencies.tutorial008c import app + + client = TestClient(app, raise_server_exceptions=False) + response = client.get("/items/portal-gun") + assert response.status_code == 500, response.text + assert response.text == "Internal Server Error" diff --git a/tests/test_tutorial/test_dependencies/test_tutorial008c_an.py b/tests/test_tutorial/test_dependencies/test_tutorial008c_an.py new file mode 100644 index 0000000000000..10fa1ab508112 --- /dev/null +++ b/tests/test_tutorial/test_dependencies/test_tutorial008c_an.py @@ -0,0 +1,38 @@ +import pytest +from fastapi.exceptions import FastAPIError +from fastapi.testclient import TestClient + + +@pytest.fixture(name="client") +def get_client(): + from docs_src.dependencies.tutorial008c_an import app + + client = TestClient(app) + return client + + +def test_get_no_item(client: TestClient): + response = client.get("/items/foo") + assert response.status_code == 404, response.text + assert response.json() == {"detail": "Item not found, there's only a plumbus here"} + + +def test_get(client: TestClient): + response = client.get("/items/plumbus") + assert response.status_code == 200, response.text + assert response.json() == "plumbus" + + +def test_fastapi_error(client: TestClient): + with pytest.raises(FastAPIError) as exc_info: + client.get("/items/portal-gun") + assert "No response object was returned" in exc_info.value.args[0] + + +def test_internal_server_error(): + from docs_src.dependencies.tutorial008c_an import app + + client = TestClient(app, raise_server_exceptions=False) + response = client.get("/items/portal-gun") + assert response.status_code == 500, response.text + assert response.text == "Internal Server Error" diff --git a/tests/test_tutorial/test_dependencies/test_tutorial008c_an_py39.py b/tests/test_tutorial/test_dependencies/test_tutorial008c_an_py39.py new file mode 100644 index 0000000000000..6c3acff5097c9 --- /dev/null +++ b/tests/test_tutorial/test_dependencies/test_tutorial008c_an_py39.py @@ -0,0 +1,44 @@ +import pytest +from fastapi.exceptions import FastAPIError +from fastapi.testclient import TestClient + +from ...utils import needs_py39 + + +@pytest.fixture(name="client") +def get_client(): + from docs_src.dependencies.tutorial008c_an_py39 import app + + client = TestClient(app) + return client + + +@needs_py39 +def test_get_no_item(client: TestClient): + response = client.get("/items/foo") + assert response.status_code == 404, response.text + assert response.json() == {"detail": "Item not found, there's only a plumbus here"} + + +@needs_py39 +def test_get(client: TestClient): + response = client.get("/items/plumbus") + assert response.status_code == 200, response.text + assert response.json() == "plumbus" + + +@needs_py39 +def test_fastapi_error(client: TestClient): + with pytest.raises(FastAPIError) as exc_info: + client.get("/items/portal-gun") + assert "No response object was returned" in exc_info.value.args[0] + + +@needs_py39 +def test_internal_server_error(): + from docs_src.dependencies.tutorial008c_an_py39 import app + + client = TestClient(app, raise_server_exceptions=False) + response = client.get("/items/portal-gun") + assert response.status_code == 500, response.text + assert response.text == "Internal Server Error" diff --git a/tests/test_tutorial/test_dependencies/test_tutorial008d.py b/tests/test_tutorial/test_dependencies/test_tutorial008d.py new file mode 100644 index 0000000000000..0434961123eee --- /dev/null +++ b/tests/test_tutorial/test_dependencies/test_tutorial008d.py @@ -0,0 +1,41 @@ +import pytest +from fastapi.testclient import TestClient + + +@pytest.fixture(name="client") +def get_client(): + from docs_src.dependencies.tutorial008d import app + + client = TestClient(app) + return client + + +def test_get_no_item(client: TestClient): + response = client.get("/items/foo") + assert response.status_code == 404, response.text + assert response.json() == {"detail": "Item not found, there's only a plumbus here"} + + +def test_get(client: TestClient): + response = client.get("/items/plumbus") + assert response.status_code == 200, response.text + assert response.json() == "plumbus" + + +def test_internal_error(client: TestClient): + from docs_src.dependencies.tutorial008d import InternalError + + with pytest.raises(InternalError) as exc_info: + client.get("/items/portal-gun") + assert ( + exc_info.value.args[0] == "The portal gun is too dangerous to be owned by Rick" + ) + + +def test_internal_server_error(): + from docs_src.dependencies.tutorial008d import app + + client = TestClient(app, raise_server_exceptions=False) + response = client.get("/items/portal-gun") + assert response.status_code == 500, response.text + assert response.text == "Internal Server Error" diff --git a/tests/test_tutorial/test_dependencies/test_tutorial008d_an.py b/tests/test_tutorial/test_dependencies/test_tutorial008d_an.py new file mode 100644 index 0000000000000..f29d8cdbe5773 --- /dev/null +++ b/tests/test_tutorial/test_dependencies/test_tutorial008d_an.py @@ -0,0 +1,41 @@ +import pytest +from fastapi.testclient import TestClient + + +@pytest.fixture(name="client") +def get_client(): + from docs_src.dependencies.tutorial008d_an import app + + client = TestClient(app) + return client + + +def test_get_no_item(client: TestClient): + response = client.get("/items/foo") + assert response.status_code == 404, response.text + assert response.json() == {"detail": "Item not found, there's only a plumbus here"} + + +def test_get(client: TestClient): + response = client.get("/items/plumbus") + assert response.status_code == 200, response.text + assert response.json() == "plumbus" + + +def test_internal_error(client: TestClient): + from docs_src.dependencies.tutorial008d_an import InternalError + + with pytest.raises(InternalError) as exc_info: + client.get("/items/portal-gun") + assert ( + exc_info.value.args[0] == "The portal gun is too dangerous to be owned by Rick" + ) + + +def test_internal_server_error(): + from docs_src.dependencies.tutorial008d_an import app + + client = TestClient(app, raise_server_exceptions=False) + response = client.get("/items/portal-gun") + assert response.status_code == 500, response.text + assert response.text == "Internal Server Error" diff --git a/tests/test_tutorial/test_dependencies/test_tutorial008d_an_py39.py b/tests/test_tutorial/test_dependencies/test_tutorial008d_an_py39.py new file mode 100644 index 0000000000000..0a585f4adb265 --- /dev/null +++ b/tests/test_tutorial/test_dependencies/test_tutorial008d_an_py39.py @@ -0,0 +1,47 @@ +import pytest +from fastapi.testclient import TestClient + +from ...utils import needs_py39 + + +@pytest.fixture(name="client") +def get_client(): + from docs_src.dependencies.tutorial008d_an_py39 import app + + client = TestClient(app) + return client + + +@needs_py39 +def test_get_no_item(client: TestClient): + response = client.get("/items/foo") + assert response.status_code == 404, response.text + assert response.json() == {"detail": "Item not found, there's only a plumbus here"} + + +@needs_py39 +def test_get(client: TestClient): + response = client.get("/items/plumbus") + assert response.status_code == 200, response.text + assert response.json() == "plumbus" + + +@needs_py39 +def test_internal_error(client: TestClient): + from docs_src.dependencies.tutorial008d_an_py39 import InternalError + + with pytest.raises(InternalError) as exc_info: + client.get("/items/portal-gun") + assert ( + exc_info.value.args[0] == "The portal gun is too dangerous to be owned by Rick" + ) + + +@needs_py39 +def test_internal_server_error(): + from docs_src.dependencies.tutorial008d_an_py39 import app + + client = TestClient(app, raise_server_exceptions=False) + response = client.get("/items/portal-gun") + assert response.status_code == 500, response.text + assert response.text == "Internal Server Error" diff --git a/tests/test_tutorial/test_dependencies/test_tutorial012.py b/tests/test_tutorial/test_dependencies/test_tutorial012.py index b92b96c0194e9..753e62e43e408 100644 --- a/tests/test_tutorial/test_dependencies/test_tutorial012.py +++ b/tests/test_tutorial/test_dependencies/test_tutorial012.py @@ -1,4 +1,6 @@ +from dirty_equals import IsDict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url from docs_src.dependencies.tutorial012 import app @@ -8,39 +10,83 @@ def test_get_no_headers_items(): response = client.get("/items/") assert response.status_code == 422, response.text - assert response.json() == { - "detail": [ - { - "loc": ["header", "x-token"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["header", "x-key"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["header", "x-token"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["header", "x-key"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["header", "x-token"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["header", "x-key"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) def test_get_no_headers_users(): response = client.get("/users/") assert response.status_code == 422, response.text - assert response.json() == { - "detail": [ - { - "loc": ["header", "x-token"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["header", "x-key"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["header", "x-token"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["header", "x-key"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["header", "x-token"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["header", "x-key"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) def test_get_invalid_one_header_items(): @@ -99,7 +145,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { diff --git a/tests/test_tutorial/test_dependencies/test_tutorial012_an.py b/tests/test_tutorial/test_dependencies/test_tutorial012_an.py index 2ddb7bb53285e..4157d46128bf6 100644 --- a/tests/test_tutorial/test_dependencies/test_tutorial012_an.py +++ b/tests/test_tutorial/test_dependencies/test_tutorial012_an.py @@ -1,4 +1,6 @@ +from dirty_equals import IsDict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url from docs_src.dependencies.tutorial012_an import app @@ -8,39 +10,83 @@ def test_get_no_headers_items(): response = client.get("/items/") assert response.status_code == 422, response.text - assert response.json() == { - "detail": [ - { - "loc": ["header", "x-token"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["header", "x-key"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["header", "x-token"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["header", "x-key"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["header", "x-token"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["header", "x-key"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) def test_get_no_headers_users(): response = client.get("/users/") assert response.status_code == 422, response.text - assert response.json() == { - "detail": [ - { - "loc": ["header", "x-token"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["header", "x-key"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["header", "x-token"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["header", "x-key"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["header", "x-token"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["header", "x-key"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) def test_get_invalid_one_header_items(): @@ -99,7 +145,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { diff --git a/tests/test_tutorial/test_dependencies/test_tutorial012_an_py39.py b/tests/test_tutorial/test_dependencies/test_tutorial012_an_py39.py index 595c83a5310ea..9e46758cbdd76 100644 --- a/tests/test_tutorial/test_dependencies/test_tutorial012_an_py39.py +++ b/tests/test_tutorial/test_dependencies/test_tutorial012_an_py39.py @@ -1,5 +1,7 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url from ...utils import needs_py39 @@ -16,40 +18,84 @@ def get_client(): def test_get_no_headers_items(client: TestClient): response = client.get("/items/") assert response.status_code == 422, response.text - assert response.json() == { - "detail": [ - { - "loc": ["header", "x-token"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["header", "x-key"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["header", "x-token"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["header", "x-key"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["header", "x-token"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["header", "x-key"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) @needs_py39 def test_get_no_headers_users(client: TestClient): response = client.get("/users/") assert response.status_code == 422, response.text - assert response.json() == { - "detail": [ - { - "loc": ["header", "x-token"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["header", "x-key"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["header", "x-token"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["header", "x-key"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["header", "x-token"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["header", "x-key"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) @needs_py39 @@ -115,7 +161,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { diff --git a/tests/test_tutorial/test_events/test_tutorial001.py b/tests/test_tutorial/test_events/test_tutorial001.py index 52f9beed5daa3..f65b92d127ff1 100644 --- a/tests/test_tutorial/test_events/test_tutorial001.py +++ b/tests/test_tutorial/test_events/test_tutorial001.py @@ -1,21 +1,28 @@ +import pytest +from fastapi import FastAPI from fastapi.testclient import TestClient -from docs_src.events.tutorial001 import app +@pytest.fixture(name="app", scope="module") +def get_app(): + with pytest.warns(DeprecationWarning): + from docs_src.events.tutorial001 import app + yield app -def test_events(): + +def test_events(app: FastAPI): with TestClient(app) as client: response = client.get("/items/foo") assert response.status_code == 200, response.text assert response.json() == {"name": "Fighters"} -def test_openapi_schema(): +def test_openapi_schema(app: FastAPI): with TestClient(app) as client: response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { diff --git a/tests/test_tutorial/test_events/test_tutorial002.py b/tests/test_tutorial/test_events/test_tutorial002.py index 882d41aa517be..137294d737d8b 100644 --- a/tests/test_tutorial/test_events/test_tutorial002.py +++ b/tests/test_tutorial/test_events/test_tutorial002.py @@ -1,9 +1,16 @@ +import pytest +from fastapi import FastAPI from fastapi.testclient import TestClient -from docs_src.events.tutorial002 import app +@pytest.fixture(name="app", scope="module") +def get_app(): + with pytest.warns(DeprecationWarning): + from docs_src.events.tutorial002 import app + yield app -def test_events(): + +def test_events(app: FastAPI): with TestClient(app) as client: response = client.get("/items/") assert response.status_code == 200, response.text @@ -12,12 +19,12 @@ def test_events(): assert "Application shutdown" in log.read() -def test_openapi_schema(): +def test_openapi_schema(app: FastAPI): with TestClient(app) as client: response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { diff --git a/tests/test_tutorial/test_events/test_tutorial003.py b/tests/test_tutorial/test_events/test_tutorial003.py index b2820b63c6865..0ad1a1f8b24bd 100644 --- a/tests/test_tutorial/test_events/test_tutorial003.py +++ b/tests/test_tutorial/test_events/test_tutorial003.py @@ -22,7 +22,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/predict": { diff --git a/tests/test_tutorial/test_extending_openapi/test_tutorial001.py b/tests/test_tutorial/test_extending_openapi/test_tutorial001.py index 6e71bb2debc7e..a85a313501428 100644 --- a/tests/test_tutorial/test_extending_openapi/test_tutorial001.py +++ b/tests/test_tutorial/test_extending_openapi/test_tutorial001.py @@ -15,11 +15,12 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": { "title": "Custom title", + "summary": "This is a very custom OpenAPI schema", + "description": "Here's a longer description of the custom **OpenAPI** schema", "version": "2.5.0", - "description": "This is a very custom OpenAPI schema", "x-logo": { "url": "https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" }, diff --git a/tests/test_tutorial/test_extra_data_types/test_tutorial001.py b/tests/test_tutorial/test_extra_data_types/test_tutorial001.py index 07a8349903852..7710446ce34d9 100644 --- a/tests/test_tutorial/test_extra_data_types/test_tutorial001.py +++ b/tests/test_tutorial/test_extra_data_types/test_tutorial001.py @@ -1,3 +1,4 @@ +from dirty_equals import IsDict from fastapi.testclient import TestClient from docs_src.extra_data_types.tutorial001 import app @@ -30,7 +31,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { @@ -68,9 +69,22 @@ def test_openapi_schema(): "requestBody": { "content": { "application/json": { - "schema": { - "$ref": "#/components/schemas/Body_read_items_items__item_id__put" - } + "schema": IsDict( + { + "allOf": [ + { + "$ref": "#/components/schemas/Body_read_items_items__item_id__put" + } + ], + "title": "Body", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "$ref": "#/components/schemas/Body_read_items_items__item_id__put" + } + ) } } }, @@ -83,26 +97,74 @@ def test_openapi_schema(): "title": "Body_read_items_items__item_id__put", "type": "object", "properties": { - "start_datetime": { - "title": "Start Datetime", - "type": "string", - "format": "date-time", - }, - "end_datetime": { - "title": "End Datetime", - "type": "string", - "format": "date-time", - }, - "repeat_at": { - "title": "Repeat At", - "type": "string", - "format": "time", - }, - "process_after": { - "title": "Process After", - "type": "number", - "format": "time-delta", - }, + "start_datetime": IsDict( + { + "title": "Start Datetime", + "anyOf": [ + {"type": "string", "format": "date-time"}, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "Start Datetime", + "type": "string", + "format": "date-time", + } + ), + "end_datetime": IsDict( + { + "title": "End Datetime", + "anyOf": [ + {"type": "string", "format": "date-time"}, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "End Datetime", + "type": "string", + "format": "date-time", + } + ), + "repeat_at": IsDict( + { + "title": "Repeat At", + "anyOf": [ + {"type": "string", "format": "time"}, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "Repeat At", + "type": "string", + "format": "time", + } + ), + "process_after": IsDict( + { + "title": "Process After", + "anyOf": [ + {"type": "string", "format": "duration"}, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "Process After", + "type": "number", + "format": "time-delta", + } + ), }, }, "ValidationError": { diff --git a/tests/test_tutorial/test_extra_data_types/test_tutorial001_an.py b/tests/test_tutorial/test_extra_data_types/test_tutorial001_an.py index 76836d447d891..9951b3b51173a 100644 --- a/tests/test_tutorial/test_extra_data_types/test_tutorial001_an.py +++ b/tests/test_tutorial/test_extra_data_types/test_tutorial001_an.py @@ -1,3 +1,4 @@ +from dirty_equals import IsDict from fastapi.testclient import TestClient from docs_src.extra_data_types.tutorial001_an import app @@ -30,7 +31,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { @@ -68,9 +69,22 @@ def test_openapi_schema(): "requestBody": { "content": { "application/json": { - "schema": { - "$ref": "#/components/schemas/Body_read_items_items__item_id__put" - } + "schema": IsDict( + { + "allOf": [ + { + "$ref": "#/components/schemas/Body_read_items_items__item_id__put" + } + ], + "title": "Body", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "$ref": "#/components/schemas/Body_read_items_items__item_id__put" + } + ) } } }, @@ -83,26 +97,74 @@ def test_openapi_schema(): "title": "Body_read_items_items__item_id__put", "type": "object", "properties": { - "start_datetime": { - "title": "Start Datetime", - "type": "string", - "format": "date-time", - }, - "end_datetime": { - "title": "End Datetime", - "type": "string", - "format": "date-time", - }, - "repeat_at": { - "title": "Repeat At", - "type": "string", - "format": "time", - }, - "process_after": { - "title": "Process After", - "type": "number", - "format": "time-delta", - }, + "start_datetime": IsDict( + { + "title": "Start Datetime", + "anyOf": [ + {"type": "string", "format": "date-time"}, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "Start Datetime", + "type": "string", + "format": "date-time", + } + ), + "end_datetime": IsDict( + { + "title": "End Datetime", + "anyOf": [ + {"type": "string", "format": "date-time"}, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "End Datetime", + "type": "string", + "format": "date-time", + } + ), + "repeat_at": IsDict( + { + "title": "Repeat At", + "anyOf": [ + {"type": "string", "format": "time"}, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "Repeat At", + "type": "string", + "format": "time", + } + ), + "process_after": IsDict( + { + "title": "Process After", + "anyOf": [ + {"type": "string", "format": "duration"}, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "Process After", + "type": "number", + "format": "time-delta", + } + ), }, }, "ValidationError": { diff --git a/tests/test_tutorial/test_extra_data_types/test_tutorial001_an_py310.py b/tests/test_tutorial/test_extra_data_types/test_tutorial001_an_py310.py index 158ee01b389a3..7c482b8cb2384 100644 --- a/tests/test_tutorial/test_extra_data_types/test_tutorial001_an_py310.py +++ b/tests/test_tutorial/test_extra_data_types/test_tutorial001_an_py310.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient from ...utils import needs_py310 @@ -39,7 +40,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { @@ -77,9 +78,22 @@ def test_openapi_schema(client: TestClient): "requestBody": { "content": { "application/json": { - "schema": { - "$ref": "#/components/schemas/Body_read_items_items__item_id__put" - } + "schema": IsDict( + { + "allOf": [ + { + "$ref": "#/components/schemas/Body_read_items_items__item_id__put" + } + ], + "title": "Body", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "$ref": "#/components/schemas/Body_read_items_items__item_id__put" + } + ) } } }, @@ -92,26 +106,74 @@ def test_openapi_schema(client: TestClient): "title": "Body_read_items_items__item_id__put", "type": "object", "properties": { - "start_datetime": { - "title": "Start Datetime", - "type": "string", - "format": "date-time", - }, - "end_datetime": { - "title": "End Datetime", - "type": "string", - "format": "date-time", - }, - "repeat_at": { - "title": "Repeat At", - "type": "string", - "format": "time", - }, - "process_after": { - "title": "Process After", - "type": "number", - "format": "time-delta", - }, + "start_datetime": IsDict( + { + "title": "Start Datetime", + "anyOf": [ + {"type": "string", "format": "date-time"}, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "Start Datetime", + "type": "string", + "format": "date-time", + } + ), + "end_datetime": IsDict( + { + "title": "End Datetime", + "anyOf": [ + {"type": "string", "format": "date-time"}, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "End Datetime", + "type": "string", + "format": "date-time", + } + ), + "repeat_at": IsDict( + { + "title": "Repeat At", + "anyOf": [ + {"type": "string", "format": "time"}, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "Repeat At", + "type": "string", + "format": "time", + } + ), + "process_after": IsDict( + { + "title": "Process After", + "anyOf": [ + {"type": "string", "format": "duration"}, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "Process After", + "type": "number", + "format": "time-delta", + } + ), }, }, "ValidationError": { diff --git a/tests/test_tutorial/test_extra_data_types/test_tutorial001_an_py39.py b/tests/test_tutorial/test_extra_data_types/test_tutorial001_an_py39.py index 5be6452ee56ca..87473867b02fc 100644 --- a/tests/test_tutorial/test_extra_data_types/test_tutorial001_an_py39.py +++ b/tests/test_tutorial/test_extra_data_types/test_tutorial001_an_py39.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient from ...utils import needs_py39 @@ -39,7 +40,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { @@ -77,9 +78,22 @@ def test_openapi_schema(client: TestClient): "requestBody": { "content": { "application/json": { - "schema": { - "$ref": "#/components/schemas/Body_read_items_items__item_id__put" - } + "schema": IsDict( + { + "allOf": [ + { + "$ref": "#/components/schemas/Body_read_items_items__item_id__put" + } + ], + "title": "Body", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "$ref": "#/components/schemas/Body_read_items_items__item_id__put" + } + ) } } }, @@ -92,26 +106,74 @@ def test_openapi_schema(client: TestClient): "title": "Body_read_items_items__item_id__put", "type": "object", "properties": { - "start_datetime": { - "title": "Start Datetime", - "type": "string", - "format": "date-time", - }, - "end_datetime": { - "title": "End Datetime", - "type": "string", - "format": "date-time", - }, - "repeat_at": { - "title": "Repeat At", - "type": "string", - "format": "time", - }, - "process_after": { - "title": "Process After", - "type": "number", - "format": "time-delta", - }, + "start_datetime": IsDict( + { + "title": "Start Datetime", + "anyOf": [ + {"type": "string", "format": "date-time"}, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "Start Datetime", + "type": "string", + "format": "date-time", + } + ), + "end_datetime": IsDict( + { + "title": "End Datetime", + "anyOf": [ + {"type": "string", "format": "date-time"}, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "End Datetime", + "type": "string", + "format": "date-time", + } + ), + "repeat_at": IsDict( + { + "title": "Repeat At", + "anyOf": [ + {"type": "string", "format": "time"}, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "Repeat At", + "type": "string", + "format": "time", + } + ), + "process_after": IsDict( + { + "title": "Process After", + "anyOf": [ + {"type": "string", "format": "duration"}, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "Process After", + "type": "number", + "format": "time-delta", + } + ), }, }, "ValidationError": { diff --git a/tests/test_tutorial/test_extra_data_types/test_tutorial001_py310.py b/tests/test_tutorial/test_extra_data_types/test_tutorial001_py310.py index 5413fe428b72f..0b71d91773329 100644 --- a/tests/test_tutorial/test_extra_data_types/test_tutorial001_py310.py +++ b/tests/test_tutorial/test_extra_data_types/test_tutorial001_py310.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient from ...utils import needs_py310 @@ -39,7 +40,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { @@ -77,9 +78,22 @@ def test_openapi_schema(client: TestClient): "requestBody": { "content": { "application/json": { - "schema": { - "$ref": "#/components/schemas/Body_read_items_items__item_id__put" - } + "schema": IsDict( + { + "allOf": [ + { + "$ref": "#/components/schemas/Body_read_items_items__item_id__put" + } + ], + "title": "Body", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "$ref": "#/components/schemas/Body_read_items_items__item_id__put" + } + ) } } }, @@ -92,26 +106,74 @@ def test_openapi_schema(client: TestClient): "title": "Body_read_items_items__item_id__put", "type": "object", "properties": { - "start_datetime": { - "title": "Start Datetime", - "type": "string", - "format": "date-time", - }, - "end_datetime": { - "title": "End Datetime", - "type": "string", - "format": "date-time", - }, - "repeat_at": { - "title": "Repeat At", - "type": "string", - "format": "time", - }, - "process_after": { - "title": "Process After", - "type": "number", - "format": "time-delta", - }, + "start_datetime": IsDict( + { + "title": "Start Datetime", + "anyOf": [ + {"type": "string", "format": "date-time"}, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "Start Datetime", + "type": "string", + "format": "date-time", + } + ), + "end_datetime": IsDict( + { + "title": "End Datetime", + "anyOf": [ + {"type": "string", "format": "date-time"}, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "End Datetime", + "type": "string", + "format": "date-time", + } + ), + "repeat_at": IsDict( + { + "title": "Repeat At", + "anyOf": [ + {"type": "string", "format": "time"}, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "Repeat At", + "type": "string", + "format": "time", + } + ), + "process_after": IsDict( + { + "title": "Process After", + "anyOf": [ + {"type": "string", "format": "duration"}, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "Process After", + "type": "number", + "format": "time-delta", + } + ), }, }, "ValidationError": { diff --git a/tests/test_tutorial/test_extra_models/test_tutorial003.py b/tests/test_tutorial/test_extra_models/test_tutorial003.py index f08bf4c509708..0ccb99948f381 100644 --- a/tests/test_tutorial/test_extra_models/test_tutorial003.py +++ b/tests/test_tutorial/test_extra_models/test_tutorial003.py @@ -1,3 +1,4 @@ +from dirty_equals import IsOneOf from fastapi.testclient import TestClient from docs_src.extra_models.tutorial003 import app @@ -28,7 +29,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { @@ -76,7 +77,11 @@ def test_openapi_schema(): "schemas": { "PlaneItem": { "title": "PlaneItem", - "required": ["description", "size"], + "required": IsOneOf( + ["description", "type", "size"], + # TODO: remove when deprecating Pydantic v1 + ["description", "size"], + ), "type": "object", "properties": { "description": {"title": "Description", "type": "string"}, @@ -86,7 +91,11 @@ def test_openapi_schema(): }, "CarItem": { "title": "CarItem", - "required": ["description"], + "required": IsOneOf( + ["description", "type"], + # TODO: remove when deprecating Pydantic v1 + ["description"], + ), "type": "object", "properties": { "description": {"title": "Description", "type": "string"}, diff --git a/tests/test_tutorial/test_extra_models/test_tutorial003_py310.py b/tests/test_tutorial/test_extra_models/test_tutorial003_py310.py index 407c717873a83..b2fe65fd9ffb6 100644 --- a/tests/test_tutorial/test_extra_models/test_tutorial003_py310.py +++ b/tests/test_tutorial/test_extra_models/test_tutorial003_py310.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsOneOf from fastapi.testclient import TestClient from ...utils import needs_py310 @@ -38,7 +39,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { @@ -86,7 +87,11 @@ def test_openapi_schema(client: TestClient): "schemas": { "PlaneItem": { "title": "PlaneItem", - "required": ["description", "size"], + "required": IsOneOf( + ["description", "type", "size"], + # TODO: remove when deprecating Pydantic v1 + ["description", "size"], + ), "type": "object", "properties": { "description": {"title": "Description", "type": "string"}, @@ -96,7 +101,11 @@ def test_openapi_schema(client: TestClient): }, "CarItem": { "title": "CarItem", - "required": ["description"], + "required": IsOneOf( + ["description", "type"], + # TODO: remove when deprecating Pydantic v1 + ["description"], + ), "type": "object", "properties": { "description": {"title": "Description", "type": "string"}, diff --git a/tests/test_tutorial/test_extra_models/test_tutorial004.py b/tests/test_tutorial/test_extra_models/test_tutorial004.py index 47790ba8f94dd..71f6a8c700b35 100644 --- a/tests/test_tutorial/test_extra_models/test_tutorial004.py +++ b/tests/test_tutorial/test_extra_models/test_tutorial004.py @@ -18,7 +18,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { diff --git a/tests/test_tutorial/test_extra_models/test_tutorial004_py39.py b/tests/test_tutorial/test_extra_models/test_tutorial004_py39.py index a98700172a1b6..5475b92e10fee 100644 --- a/tests/test_tutorial/test_extra_models/test_tutorial004_py39.py +++ b/tests/test_tutorial/test_extra_models/test_tutorial004_py39.py @@ -27,7 +27,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { diff --git a/tests/test_tutorial/test_extra_models/test_tutorial005.py b/tests/test_tutorial/test_extra_models/test_tutorial005.py index 7c094b2538365..b0861c37f7dff 100644 --- a/tests/test_tutorial/test_extra_models/test_tutorial005.py +++ b/tests/test_tutorial/test_extra_models/test_tutorial005.py @@ -15,7 +15,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/keyword-weights/": { diff --git a/tests/test_tutorial/test_extra_models/test_tutorial005_py39.py b/tests/test_tutorial/test_extra_models/test_tutorial005_py39.py index b403864501ee1..7278e93c36ae4 100644 --- a/tests/test_tutorial/test_extra_models/test_tutorial005_py39.py +++ b/tests/test_tutorial/test_extra_models/test_tutorial005_py39.py @@ -24,7 +24,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/keyword-weights/": { diff --git a/tests/test_tutorial/test_first_steps/test_tutorial001.py b/tests/test_tutorial/test_first_steps/test_tutorial001.py index ea37aec53a95f..6cc9fc22826dd 100644 --- a/tests/test_tutorial/test_first_steps/test_tutorial001.py +++ b/tests/test_tutorial/test_first_steps/test_tutorial001.py @@ -23,7 +23,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200 assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/": { diff --git a/tests/test_tutorial/test_generate_clients/test_tutorial003.py b/tests/test_tutorial/test_generate_clients/test_tutorial003.py index 8b22eab9eec38..1cd9678a1c8e4 100644 --- a/tests/test_tutorial/test_generate_clients/test_tutorial003.py +++ b/tests/test_tutorial/test_generate_clients/test_tutorial003.py @@ -32,7 +32,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { diff --git a/tests/test_tutorial/test_handling_errors/test_tutorial001.py b/tests/test_tutorial/test_handling_errors/test_tutorial001.py index 99a1053caba28..8809c135bd706 100644 --- a/tests/test_tutorial/test_handling_errors/test_tutorial001.py +++ b/tests/test_tutorial/test_handling_errors/test_tutorial001.py @@ -22,7 +22,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { diff --git a/tests/test_tutorial/test_handling_errors/test_tutorial002.py b/tests/test_tutorial/test_handling_errors/test_tutorial002.py index 091c74f4de9a0..efd86ebdecd46 100644 --- a/tests/test_tutorial/test_handling_errors/test_tutorial002.py +++ b/tests/test_tutorial/test_handling_errors/test_tutorial002.py @@ -22,7 +22,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items-header/{item_id}": { diff --git a/tests/test_tutorial/test_handling_errors/test_tutorial003.py b/tests/test_tutorial/test_handling_errors/test_tutorial003.py index 1639cb1d8b67b..4763f68f3fabb 100644 --- a/tests/test_tutorial/test_handling_errors/test_tutorial003.py +++ b/tests/test_tutorial/test_handling_errors/test_tutorial003.py @@ -23,7 +23,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/unicorns/{name}": { diff --git a/tests/test_tutorial/test_handling_errors/test_tutorial004.py b/tests/test_tutorial/test_handling_errors/test_tutorial004.py index 246f3b94c18f3..217159a59685e 100644 --- a/tests/test_tutorial/test_handling_errors/test_tutorial004.py +++ b/tests/test_tutorial/test_handling_errors/test_tutorial004.py @@ -8,12 +8,18 @@ def test_get_validation_error(): response = client.get("/items/foo") assert response.status_code == 400, response.text - validation_error_str_lines = [ - b"1 validation error for Request", - b"path -> item_id", - b" value is not a valid integer (type=type_error.integer)", - ] - assert response.content == b"\n".join(validation_error_str_lines) + # TODO: remove when deprecating Pydantic v1 + assert ( + # TODO: remove when deprecating Pydantic v1 + "path -> item_id" in response.text + or "'loc': ('path', 'item_id')" in response.text + ) + assert ( + # TODO: remove when deprecating Pydantic v1 + "value is not a valid integer" in response.text + or "Input should be a valid integer, unable to parse string as an integer" + in response.text + ) def test_get_http_error(): @@ -32,7 +38,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { diff --git a/tests/test_tutorial/test_handling_errors/test_tutorial005.py b/tests/test_tutorial/test_handling_errors/test_tutorial005.py index af47fd1a4f52c..494c317cabe62 100644 --- a/tests/test_tutorial/test_handling_errors/test_tutorial005.py +++ b/tests/test_tutorial/test_handling_errors/test_tutorial005.py @@ -1,4 +1,6 @@ +from dirty_equals import IsDict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url from docs_src.handling_errors.tutorial005 import app @@ -8,16 +10,32 @@ def test_post_validation_error(): response = client.post("/items/", json={"title": "towel", "size": "XL"}) assert response.status_code == 422, response.text - assert response.json() == { - "detail": [ - { - "loc": ["body", "size"], - "msg": "value is not a valid integer", - "type": "type_error.integer", - } - ], - "body": {"title": "towel", "size": "XL"}, - } + assert response.json() == IsDict( + { + "detail": [ + { + "type": "int_parsing", + "loc": ["body", "size"], + "msg": "Input should be a valid integer, unable to parse string as an integer", + "input": "XL", + "url": match_pydantic_error_url("int_parsing"), + } + ], + "body": {"title": "towel", "size": "XL"}, + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "size"], + "msg": "value is not a valid integer", + "type": "type_error.integer", + } + ], + "body": {"title": "towel", "size": "XL"}, + } + ) def test_post(): @@ -31,7 +49,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { diff --git a/tests/test_tutorial/test_handling_errors/test_tutorial006.py b/tests/test_tutorial/test_handling_errors/test_tutorial006.py index 4a39bd102268a..cc2b496a839af 100644 --- a/tests/test_tutorial/test_handling_errors/test_tutorial006.py +++ b/tests/test_tutorial/test_handling_errors/test_tutorial006.py @@ -1,4 +1,6 @@ +from dirty_equals import IsDict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url from docs_src.handling_errors.tutorial006 import app @@ -8,15 +10,30 @@ def test_get_validation_error(): response = client.get("/items/foo") assert response.status_code == 422, response.text - assert response.json() == { - "detail": [ - { - "loc": ["path", "item_id"], - "msg": "value is not a valid integer", - "type": "type_error.integer", - } - ] - } + assert response.json() == IsDict( + { + "detail": [ + { + "type": "int_parsing", + "loc": ["path", "item_id"], + "msg": "Input should be a valid integer, unable to parse string as an integer", + "input": "foo", + "url": match_pydantic_error_url("int_parsing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["path", "item_id"], + "msg": "value is not a valid integer", + "type": "type_error.integer", + } + ] + } + ) def test_get_http_error(): @@ -35,7 +52,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { diff --git a/tests/test_tutorial/test_header_params/test_tutorial001.py b/tests/test_tutorial/test_header_params/test_tutorial001.py index 80f502d6a8cc2..746fc05024f17 100644 --- a/tests/test_tutorial/test_header_params/test_tutorial001.py +++ b/tests/test_tutorial/test_header_params/test_tutorial001.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient from docs_src.header_params.tutorial001 import app @@ -20,11 +21,11 @@ def test(path, headers, expected_status, expected_response): assert response.json() == expected_response -def test_openapi(): +def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200 assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { @@ -50,7 +51,16 @@ def test_openapi(): "parameters": [ { "required": False, - "schema": {"title": "User-Agent", "type": "string"}, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "User-Agent", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "User-Agent", "type": "string"} + ), "name": "user-agent", "in": "header", } diff --git a/tests/test_tutorial/test_header_params/test_tutorial001_an.py b/tests/test_tutorial/test_header_params/test_tutorial001_an.py index f0ad7b8160081..a715228aa298b 100644 --- a/tests/test_tutorial/test_header_params/test_tutorial001_an.py +++ b/tests/test_tutorial/test_header_params/test_tutorial001_an.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient from docs_src.header_params.tutorial001_an import app @@ -24,7 +25,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200 assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { @@ -50,7 +51,16 @@ def test_openapi_schema(): "parameters": [ { "required": False, - "schema": {"title": "User-Agent", "type": "string"}, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "User-Agent", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "User-Agent", "type": "string"} + ), "name": "user-agent", "in": "header", } diff --git a/tests/test_tutorial/test_header_params/test_tutorial001_an_py310.py b/tests/test_tutorial/test_header_params/test_tutorial001_an_py310.py index d095c71233037..caf85bc6ca157 100644 --- a/tests/test_tutorial/test_header_params/test_tutorial001_an_py310.py +++ b/tests/test_tutorial/test_header_params/test_tutorial001_an_py310.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient from ...utils import needs_py310 @@ -32,7 +33,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200 assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { @@ -58,7 +59,16 @@ def test_openapi_schema(client: TestClient): "parameters": [ { "required": False, - "schema": {"title": "User-Agent", "type": "string"}, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "User-Agent", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "User-Agent", "type": "string"} + ), "name": "user-agent", "in": "header", } diff --git a/tests/test_tutorial/test_header_params/test_tutorial001_py310.py b/tests/test_tutorial/test_header_params/test_tutorial001_py310.py index bf176bba27694..57e0a296af00e 100644 --- a/tests/test_tutorial/test_header_params/test_tutorial001_py310.py +++ b/tests/test_tutorial/test_header_params/test_tutorial001_py310.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient from ...utils import needs_py310 @@ -32,7 +33,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200 assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { @@ -58,7 +59,16 @@ def test_openapi_schema(client: TestClient): "parameters": [ { "required": False, - "schema": {"title": "User-Agent", "type": "string"}, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "User-Agent", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "User-Agent", "type": "string"} + ), "name": "user-agent", "in": "header", } diff --git a/tests/test_tutorial/test_header_params/test_tutorial002.py b/tests/test_tutorial/test_header_params/test_tutorial002.py index 516abda8bf45f..78bac838cfe6a 100644 --- a/tests/test_tutorial/test_header_params/test_tutorial002.py +++ b/tests/test_tutorial/test_header_params/test_tutorial002.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient from docs_src.header_params.tutorial002 import app @@ -35,7 +36,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200 assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { @@ -61,7 +62,16 @@ def test_openapi_schema(): "parameters": [ { "required": False, - "schema": {"title": "Strange Header", "type": "string"}, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Strange Header", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Strange Header", "type": "string"} + ), "name": "strange_header", "in": "header", } diff --git a/tests/test_tutorial/test_header_params/test_tutorial002_an.py b/tests/test_tutorial/test_header_params/test_tutorial002_an.py index 97493e60402cc..ffda8158fc326 100644 --- a/tests/test_tutorial/test_header_params/test_tutorial002_an.py +++ b/tests/test_tutorial/test_header_params/test_tutorial002_an.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient from docs_src.header_params.tutorial002_an import app @@ -35,7 +36,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200 assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { @@ -61,7 +62,16 @@ def test_openapi_schema(): "parameters": [ { "required": False, - "schema": {"title": "Strange Header", "type": "string"}, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Strange Header", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Strange Header", "type": "string"} + ), "name": "strange_header", "in": "header", } diff --git a/tests/test_tutorial/test_header_params/test_tutorial002_an_py310.py b/tests/test_tutorial/test_header_params/test_tutorial002_an_py310.py index e0c60342a79be..6f332f3bac7a8 100644 --- a/tests/test_tutorial/test_header_params/test_tutorial002_an_py310.py +++ b/tests/test_tutorial/test_header_params/test_tutorial002_an_py310.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient from ...utils import needs_py310 @@ -43,7 +44,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200 assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { @@ -69,7 +70,16 @@ def test_openapi_schema(client: TestClient): "parameters": [ { "required": False, - "schema": {"title": "Strange Header", "type": "string"}, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Strange Header", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Strange Header", "type": "string"} + ), "name": "strange_header", "in": "header", } diff --git a/tests/test_tutorial/test_header_params/test_tutorial002_an_py39.py b/tests/test_tutorial/test_header_params/test_tutorial002_an_py39.py index c1bc5faf8a7d9..8202bc671eba5 100644 --- a/tests/test_tutorial/test_header_params/test_tutorial002_an_py39.py +++ b/tests/test_tutorial/test_header_params/test_tutorial002_an_py39.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient from ...utils import needs_py39 @@ -46,7 +47,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200 assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { @@ -72,7 +73,16 @@ def test_openapi_schema(): "parameters": [ { "required": False, - "schema": {"title": "Strange Header", "type": "string"}, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Strange Header", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Strange Header", "type": "string"} + ), "name": "strange_header", "in": "header", } diff --git a/tests/test_tutorial/test_header_params/test_tutorial002_py310.py b/tests/test_tutorial/test_header_params/test_tutorial002_py310.py index 81871b8c6d857..c113ed23e12bb 100644 --- a/tests/test_tutorial/test_header_params/test_tutorial002_py310.py +++ b/tests/test_tutorial/test_header_params/test_tutorial002_py310.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient from ...utils import needs_py310 @@ -46,7 +47,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200 assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { @@ -72,7 +73,16 @@ def test_openapi_schema(): "parameters": [ { "required": False, - "schema": {"title": "Strange Header", "type": "string"}, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Strange Header", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Strange Header", "type": "string"} + ), "name": "strange_header", "in": "header", } diff --git a/tests/test_tutorial/test_header_params/test_tutorial003.py b/tests/test_tutorial/test_header_params/test_tutorial003.py index 99dd9e25feb37..6f7de8ed41acd 100644 --- a/tests/test_tutorial/test_header_params/test_tutorial003.py +++ b/tests/test_tutorial/test_header_params/test_tutorial003.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient from docs_src.header_params.tutorial003 import app @@ -11,8 +12,12 @@ [ ("/items", None, 200, {"X-Token values": None}), ("/items", {"x-token": "foo"}, 200, {"X-Token values": ["foo"]}), - # TODO: fix this, is it a bug? - # ("/items", [("x-token", "foo"), ("x-token", "bar")], 200, {"X-Token values": ["foo", "bar"]}), + ( + "/items", + [("x-token", "foo"), ("x-token", "bar")], + 200, + {"X-Token values": ["foo", "bar"]}, + ), ], ) def test(path, headers, expected_status, expected_response): @@ -24,9 +29,8 @@ def test(path, headers, expected_status, expected_response): def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200 - # insert_assert(response.json()) assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { @@ -36,11 +40,23 @@ def test_openapi_schema(): "parameters": [ { "required": False, - "schema": { - "title": "X-Token", - "type": "array", - "items": {"type": "string"}, - }, + "schema": IsDict( + { + "title": "X-Token", + "anyOf": [ + {"type": "array", "items": {"type": "string"}}, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "X-Token", + "type": "array", + "items": {"type": "string"}, + } + ), "name": "x-token", "in": "header", } diff --git a/tests/test_tutorial/test_header_params/test_tutorial003_an.py b/tests/test_tutorial/test_header_params/test_tutorial003_an.py index 4477da7a89ffe..742ed41f489f0 100644 --- a/tests/test_tutorial/test_header_params/test_tutorial003_an.py +++ b/tests/test_tutorial/test_header_params/test_tutorial003_an.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient from docs_src.header_params.tutorial003_an import app @@ -24,9 +25,8 @@ def test(path, headers, expected_status, expected_response): def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200 - # insert_assert(response.json()) assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { @@ -36,11 +36,23 @@ def test_openapi_schema(): "parameters": [ { "required": False, - "schema": { - "title": "X-Token", - "type": "array", - "items": {"type": "string"}, - }, + "schema": IsDict( + { + "title": "X-Token", + "anyOf": [ + {"type": "array", "items": {"type": "string"}}, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "X-Token", + "type": "array", + "items": {"type": "string"}, + } + ), "name": "x-token", "in": "header", } diff --git a/tests/test_tutorial/test_header_params/test_tutorial003_an_py310.py b/tests/test_tutorial/test_header_params/test_tutorial003_an_py310.py index b52304a2b9d3f..fdac4a416cec5 100644 --- a/tests/test_tutorial/test_header_params/test_tutorial003_an_py310.py +++ b/tests/test_tutorial/test_header_params/test_tutorial003_an_py310.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient from ...utils import needs_py310 @@ -32,9 +33,8 @@ def test(path, headers, expected_status, expected_response, client: TestClient): def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200 - # insert_assert(response.json()) assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { @@ -44,11 +44,23 @@ def test_openapi_schema(client: TestClient): "parameters": [ { "required": False, - "schema": { - "title": "X-Token", - "type": "array", - "items": {"type": "string"}, - }, + "schema": IsDict( + { + "title": "X-Token", + "anyOf": [ + {"type": "array", "items": {"type": "string"}}, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "X-Token", + "type": "array", + "items": {"type": "string"}, + } + ), "name": "x-token", "in": "header", } diff --git a/tests/test_tutorial/test_header_params/test_tutorial003_an_py39.py b/tests/test_tutorial/test_header_params/test_tutorial003_an_py39.py index dffdd16228630..c50543cc88d01 100644 --- a/tests/test_tutorial/test_header_params/test_tutorial003_an_py39.py +++ b/tests/test_tutorial/test_header_params/test_tutorial003_an_py39.py @@ -1,7 +1,8 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient -from ...utils import needs_py310 +from ...utils import needs_py39 @pytest.fixture(name="client") @@ -12,7 +13,7 @@ def get_client(): return client -@needs_py310 +@needs_py39 @pytest.mark.parametrize( "path,headers,expected_status,expected_response", [ @@ -28,13 +29,12 @@ def test(path, headers, expected_status, expected_response, client: TestClient): assert response.json() == expected_response -@needs_py310 +@needs_py39 def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200 - # insert_assert(response.json()) assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { @@ -44,11 +44,23 @@ def test_openapi_schema(client: TestClient): "parameters": [ { "required": False, - "schema": { - "title": "X-Token", - "type": "array", - "items": {"type": "string"}, - }, + "schema": IsDict( + { + "title": "X-Token", + "anyOf": [ + {"type": "array", "items": {"type": "string"}}, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "X-Token", + "type": "array", + "items": {"type": "string"}, + } + ), "name": "x-token", "in": "header", } diff --git a/tests/test_tutorial/test_header_params/test_tutorial003_py310.py b/tests/test_tutorial/test_header_params/test_tutorial003_py310.py index 64ef7b22a2758..3afb355e948ae 100644 --- a/tests/test_tutorial/test_header_params/test_tutorial003_py310.py +++ b/tests/test_tutorial/test_header_params/test_tutorial003_py310.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient from ...utils import needs_py310 @@ -32,9 +33,8 @@ def test(path, headers, expected_status, expected_response, client: TestClient): def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200 - # insert_assert(response.json()) assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { @@ -44,11 +44,23 @@ def test_openapi_schema(client: TestClient): "parameters": [ { "required": False, - "schema": { - "title": "X-Token", - "type": "array", - "items": {"type": "string"}, - }, + "schema": IsDict( + { + "title": "X-Token", + "anyOf": [ + {"type": "array", "items": {"type": "string"}}, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "X-Token", + "type": "array", + "items": {"type": "string"}, + } + ), "name": "x-token", "in": "header", } diff --git a/tests/test_tutorial/test_metadata/test_tutorial001.py b/tests/test_tutorial/test_metadata/test_tutorial001.py index f1ddc32595225..04e8ff82b09c0 100644 --- a/tests/test_tutorial/test_metadata/test_tutorial001.py +++ b/tests/test_tutorial/test_metadata/test_tutorial001.py @@ -15,9 +15,10 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": { "title": "ChimichangApp", + "summary": "Deadpool's favorite app. Nuff said.", "description": "\nChimichangApp API helps you do awesome stuff. 🚀\n\n## Items\n\nYou can **read items**.\n\n## Users\n\nYou will be able to:\n\n* **Create users** (_not implemented_).\n* **Read users** (_not implemented_).\n", "termsOfService": "http://example.com/terms/", "contact": { diff --git a/tests/test_tutorial/test_metadata/test_tutorial001_1.py b/tests/test_tutorial/test_metadata/test_tutorial001_1.py new file mode 100644 index 0000000000000..3efb1c432932b --- /dev/null +++ b/tests/test_tutorial/test_metadata/test_tutorial001_1.py @@ -0,0 +1,49 @@ +from fastapi.testclient import TestClient + +from docs_src.metadata.tutorial001_1 import app + +client = TestClient(app) + + +def test_items(): + response = client.get("/items/") + assert response.status_code == 200, response.text + assert response.json() == [{"name": "Katana"}] + + +def test_openapi_schema(): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "openapi": "3.1.0", + "info": { + "title": "ChimichangApp", + "summary": "Deadpool's favorite app. Nuff said.", + "description": "\nChimichangApp API helps you do awesome stuff. 🚀\n\n## Items\n\nYou can **read items**.\n\n## Users\n\nYou will be able to:\n\n* **Create users** (_not implemented_).\n* **Read users** (_not implemented_).\n", + "termsOfService": "http://example.com/terms/", + "contact": { + "name": "Deadpoolio the Amazing", + "url": "http://x-force.example.com/contact/", + "email": "dp@x-force.example.com", + }, + "license": { + "name": "Apache 2.0", + "identifier": "MIT", + }, + "version": "0.0.1", + }, + "paths": { + "/items/": { + "get": { + "summary": "Read Items", + "operationId": "read_items_items__get", + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + } + }, + } + } + }, + } diff --git a/tests/test_tutorial/test_metadata/test_tutorial004.py b/tests/test_tutorial/test_metadata/test_tutorial004.py index f7f47a558eab2..5072203712cf6 100644 --- a/tests/test_tutorial/test_metadata/test_tutorial004.py +++ b/tests/test_tutorial/test_metadata/test_tutorial004.py @@ -16,7 +16,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/": { diff --git a/tests/test_tutorial/test_openapi_callbacks/test_tutorial001.py b/tests/test_tutorial/test_openapi_callbacks/test_tutorial001.py index c6cdc60648c00..73af420ae1eff 100644 --- a/tests/test_tutorial/test_openapi_callbacks/test_tutorial001.py +++ b/tests/test_tutorial/test_openapi_callbacks/test_tutorial001.py @@ -1,3 +1,4 @@ +from dirty_equals import IsDict from fastapi.testclient import TestClient from docs_src.openapi_callbacks.tutorial001 import app, invoice_notification @@ -22,7 +23,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/invoices/": { @@ -33,13 +34,30 @@ def test_openapi_schema(): "parameters": [ { "required": False, - "schema": { - "title": "Callback Url", - "maxLength": 2083, - "minLength": 1, - "type": "string", - "format": "uri", - }, + "schema": IsDict( + { + "anyOf": [ + { + "type": "string", + "format": "uri", + "minLength": 1, + "maxLength": 2083, + }, + {"type": "null"}, + ], + "title": "Callback Url", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "Callback Url", + "maxLength": 2083, + "minLength": 1, + "type": "string", + "format": "uri", + } + ), "name": "callback_url", "in": "query", } @@ -132,7 +150,16 @@ def test_openapi_schema(): "type": "object", "properties": { "id": {"title": "Id", "type": "string"}, - "title": {"title": "Title", "type": "string"}, + "title": IsDict( + { + "title": "Title", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Title", "type": "string"} + ), "customer": {"title": "Customer", "type": "string"}, "total": {"title": "Total", "type": "number"}, }, diff --git a/tests/test_tutorial/test_openapi_webhooks/__init__.py b/tests/test_tutorial/test_openapi_webhooks/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/tests/test_tutorial/test_openapi_webhooks/test_tutorial001.py b/tests/test_tutorial/test_openapi_webhooks/test_tutorial001.py new file mode 100644 index 0000000000000..dc67ec401d28b --- /dev/null +++ b/tests/test_tutorial/test_openapi_webhooks/test_tutorial001.py @@ -0,0 +1,117 @@ +from fastapi.testclient import TestClient + +from docs_src.openapi_webhooks.tutorial001 import app + +client = TestClient(app) + + +def test_get(): + response = client.get("/users/") + assert response.status_code == 200, response.text + assert response.json() == ["Rick", "Morty"] + + +def test_dummy_webhook(): + # Just for coverage + app.webhooks.routes[0].endpoint({}) + + +def test_openapi_schema(): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/users/": { + "get": { + "summary": "Read Users", + "operationId": "read_users_users__get", + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + } + }, + } + } + }, + "webhooks": { + "new-subscription": { + "post": { + "summary": "New Subscription", + "description": "When a new user subscribes to your service we'll send you a POST request with this\ndata to the URL that you register for the event `new-subscription` in the dashboard.", + "operationId": "new_subscriptionnew_subscription_post", + "requestBody": { + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Subscription"} + } + }, + "required": True, + }, + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + } + }, + "components": { + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": {"$ref": "#/components/schemas/ValidationError"}, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "Subscription": { + "properties": { + "username": {"type": "string", "title": "Username"}, + "monthly_fee": {"type": "number", "title": "Monthly Fee"}, + "start_date": { + "type": "string", + "format": "date-time", + "title": "Start Date", + }, + }, + "type": "object", + "required": ["username", "monthly_fee", "start_date"], + "title": "Subscription", + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + } + }, + } diff --git a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial001.py b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial001.py index c1cdbee2411dc..95542398e44f7 100644 --- a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial001.py +++ b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial001.py @@ -15,7 +15,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { diff --git a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial002.py b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial002.py index fdaddd01878eb..d1388c367019e 100644 --- a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial002.py +++ b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial002.py @@ -15,7 +15,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { diff --git a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial003.py b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial003.py index 782c64a845ad8..313bb2a04aaca 100644 --- a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial003.py +++ b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial003.py @@ -15,7 +15,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": {}, } diff --git a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial004.py b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial004.py index f5fd868eb7ce8..4f69e4646c980 100644 --- a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial004.py +++ b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial004.py @@ -2,6 +2,8 @@ from docs_src.path_operation_advanced_configuration.tutorial004 import app +from ...utils import needs_pydanticv1, needs_pydanticv2 + client = TestClient(app) @@ -17,11 +19,12 @@ def test_query_params_str_validations(): } +@needs_pydanticv2 def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { @@ -68,8 +71,111 @@ def test_openapi_schema(): "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, + "description": { + "title": "Description", + "anyOf": [{"type": "string"}, {"type": "null"}], + }, "price": {"title": "Price", "type": "number"}, + "tax": { + "title": "Tax", + "anyOf": [{"type": "number"}, {"type": "null"}], + }, + "tags": { + "title": "Tags", + "uniqueItems": True, + "type": "array", + "items": {"type": "string"}, + "default": [], + }, + }, + }, + "ValidationError": { + "title": "ValidationError", + "required": ["loc", "msg", "type"], + "type": "object", + "properties": { + "loc": { + "title": "Location", + "type": "array", + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + }, + "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"}, + } + }, + }, + } + }, + } + + +# TODO: remove when deprecating Pydantic v1 +@needs_pydanticv1 +def test_openapi_schema_pv1(): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/items/": { + "post": { + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Item"} + } + }, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + "summary": "Create an item", + "description": "Create an item with all the information:\n\n- **name**: each item must have a name\n- **description**: a long description\n- **price**: required\n- **tax**: if the item doesn't have tax, you can omit this\n- **tags**: a set of unique tag strings for this item", + "operationId": "create_item_items__post", + "requestBody": { + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Item"} + } + }, + "required": True, + }, + } + } + }, + "components": { + "schemas": { + "Item": { + "title": "Item", + "required": ["name", "price"], + "type": "object", + "properties": { + "name": {"title": "Name", "type": "string"}, "description": {"title": "Description", "type": "string"}, + "price": {"title": "Price", "type": "number"}, "tax": {"title": "Tax", "type": "number"}, "tags": { "title": "Tags", diff --git a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial005.py b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial005.py index 52379c01e1511..07e2d7d202c0d 100644 --- a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial005.py +++ b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial005.py @@ -14,7 +14,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { diff --git a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial006.py b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial006.py index deb6b09101702..f92c59015e099 100644 --- a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial006.py +++ b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial006.py @@ -22,7 +22,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { diff --git a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial007.py b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial007.py index 470956a77df7a..2d28022691429 100644 --- a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial007.py +++ b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial007.py @@ -1,11 +1,20 @@ +import pytest from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url -from docs_src.path_operation_advanced_configuration.tutorial007 import app +from ...utils import needs_pydanticv2 -client = TestClient(app) +@pytest.fixture(name="client") +def get_client(): + from docs_src.path_operation_advanced_configuration.tutorial007 import app -def test_post(): + client = TestClient(app) + return client + + +@needs_pydanticv2 +def test_post(client: TestClient): yaml_data = """ name: Deadpoolio tags: @@ -21,7 +30,8 @@ def test_post(): } -def test_post_broken_yaml(): +@needs_pydanticv2 +def test_post_broken_yaml(client: TestClient): yaml_data = """ name: Deadpoolio tags: @@ -34,7 +44,8 @@ def test_post_broken_yaml(): assert response.json() == {"detail": "Invalid YAML"} -def test_post_invalid(): +@needs_pydanticv2 +def test_post_invalid(client: TestClient): yaml_data = """ name: Deadpoolio tags: @@ -45,18 +56,26 @@ def test_post_invalid(): """ response = client.post("/items/", content=yaml_data) assert response.status_code == 422, response.text + # insert_assert(response.json()) assert response.json() == { "detail": [ - {"loc": ["tags", 3], "msg": "str type expected", "type": "type_error.str"} + { + "type": "string_type", + "loc": ["tags", 3], + "msg": "Input should be a valid string", + "input": {"sneaky": "object"}, + "url": match_pydantic_error_url("string_type"), + } ] } -def test_openapi_schema(): +@needs_pydanticv2 +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { diff --git a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial007_pv1.py b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial007_pv1.py new file mode 100644 index 0000000000000..ef012f8a6cc8c --- /dev/null +++ b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial007_pv1.py @@ -0,0 +1,106 @@ +import pytest +from fastapi.testclient import TestClient + +from ...utils import needs_pydanticv1 + + +@pytest.fixture(name="client") +def get_client(): + from docs_src.path_operation_advanced_configuration.tutorial007_pv1 import app + + client = TestClient(app) + return client + + +@needs_pydanticv1 +def test_post(client: TestClient): + yaml_data = """ + name: Deadpoolio + tags: + - x-force + - x-men + - x-avengers + """ + response = client.post("/items/", content=yaml_data) + assert response.status_code == 200, response.text + assert response.json() == { + "name": "Deadpoolio", + "tags": ["x-force", "x-men", "x-avengers"], + } + + +@needs_pydanticv1 +def test_post_broken_yaml(client: TestClient): + yaml_data = """ + name: Deadpoolio + tags: + x - x-force + x - x-men + x - x-avengers + """ + response = client.post("/items/", content=yaml_data) + assert response.status_code == 422, response.text + assert response.json() == {"detail": "Invalid YAML"} + + +@needs_pydanticv1 +def test_post_invalid(client: TestClient): + yaml_data = """ + name: Deadpoolio + tags: + - x-force + - x-men + - x-avengers + - sneaky: object + """ + response = client.post("/items/", content=yaml_data) + assert response.status_code == 422, response.text + assert response.json() == { + "detail": [ + {"loc": ["tags", 3], "msg": "str type expected", "type": "type_error.str"} + ] + } + + +@needs_pydanticv1 +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/items/": { + "post": { + "summary": "Create Item", + "operationId": "create_item_items__post", + "requestBody": { + "content": { + "application/x-yaml": { + "schema": { + "title": "Item", + "required": ["name", "tags"], + "type": "object", + "properties": { + "name": {"title": "Name", "type": "string"}, + "tags": { + "title": "Tags", + "type": "array", + "items": {"type": "string"}, + }, + }, + } + } + }, + "required": True, + }, + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + } + }, + } + } + }, + } diff --git a/tests/test_tutorial/test_path_operation_configurations/test_tutorial002b.py b/tests/test_tutorial/test_path_operation_configurations/test_tutorial002b.py index 76e44b5e59c3a..58dec5769d0d1 100644 --- a/tests/test_tutorial/test_path_operation_configurations/test_tutorial002b.py +++ b/tests/test_tutorial/test_path_operation_configurations/test_tutorial002b.py @@ -21,7 +21,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { diff --git a/tests/test_tutorial/test_path_operation_configurations/test_tutorial005.py b/tests/test_tutorial/test_path_operation_configurations/test_tutorial005.py index cf8e203a0e158..d3792e701fcba 100644 --- a/tests/test_tutorial/test_path_operation_configurations/test_tutorial005.py +++ b/tests/test_tutorial/test_path_operation_configurations/test_tutorial005.py @@ -2,6 +2,8 @@ from docs_src.path_operation_configuration.tutorial005 import app +from ...utils import needs_pydanticv1, needs_pydanticv2 + client = TestClient(app) @@ -17,11 +19,12 @@ def test_query_params_str_validations(): } +@needs_pydanticv2 def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { @@ -68,8 +71,111 @@ def test_openapi_schema(): "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, + "description": { + "title": "Description", + "anyOf": [{"type": "string"}, {"type": "null"}], + }, "price": {"title": "Price", "type": "number"}, + "tax": { + "title": "Tax", + "anyOf": [{"type": "number"}, {"type": "null"}], + }, + "tags": { + "title": "Tags", + "uniqueItems": True, + "type": "array", + "items": {"type": "string"}, + "default": [], + }, + }, + }, + "ValidationError": { + "title": "ValidationError", + "required": ["loc", "msg", "type"], + "type": "object", + "properties": { + "loc": { + "title": "Location", + "type": "array", + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + }, + "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"}, + } + }, + }, + } + }, + } + + +# TODO: remove when deprecating Pydantic v1 +@needs_pydanticv1 +def test_openapi_schema_pv1(): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/items/": { + "post": { + "responses": { + "200": { + "description": "The created item", + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Item"} + } + }, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + "summary": "Create an item", + "description": "Create an item with all the information:\n\n- **name**: each item must have a name\n- **description**: a long description\n- **price**: required\n- **tax**: if the item doesn't have tax, you can omit this\n- **tags**: a set of unique tag strings for this item", + "operationId": "create_item_items__post", + "requestBody": { + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Item"} + } + }, + "required": True, + }, + } + } + }, + "components": { + "schemas": { + "Item": { + "title": "Item", + "required": ["name", "price"], + "type": "object", + "properties": { + "name": {"title": "Name", "type": "string"}, "description": {"title": "Description", "type": "string"}, + "price": {"title": "Price", "type": "number"}, "tax": {"title": "Tax", "type": "number"}, "tags": { "title": "Tags", diff --git a/tests/test_tutorial/test_path_operation_configurations/test_tutorial005_py310.py b/tests/test_tutorial/test_path_operation_configurations/test_tutorial005_py310.py index 497fc90242715..a68deb3df5784 100644 --- a/tests/test_tutorial/test_path_operation_configurations/test_tutorial005_py310.py +++ b/tests/test_tutorial/test_path_operation_configurations/test_tutorial005_py310.py @@ -1,7 +1,7 @@ import pytest from fastapi.testclient import TestClient -from ...utils import needs_py310 +from ...utils import needs_py310, needs_pydanticv1, needs_pydanticv2 @pytest.fixture(name="client") @@ -26,11 +26,12 @@ def test_query_params_str_validations(client: TestClient): @needs_py310 +@needs_pydanticv2 def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { @@ -77,8 +78,112 @@ def test_openapi_schema(client: TestClient): "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, + "description": { + "title": "Description", + "anyOf": [{"type": "string"}, {"type": "null"}], + }, "price": {"title": "Price", "type": "number"}, + "tax": { + "title": "Tax", + "anyOf": [{"type": "number"}, {"type": "null"}], + }, + "tags": { + "title": "Tags", + "uniqueItems": True, + "type": "array", + "items": {"type": "string"}, + "default": [], + }, + }, + }, + "ValidationError": { + "title": "ValidationError", + "required": ["loc", "msg", "type"], + "type": "object", + "properties": { + "loc": { + "title": "Location", + "type": "array", + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + }, + "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"}, + } + }, + }, + } + }, + } + + +# TODO: remove when deprecating Pydantic v1 +@needs_py310 +@needs_pydanticv1 +def test_openapi_schema_pv1(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/items/": { + "post": { + "responses": { + "200": { + "description": "The created item", + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Item"} + } + }, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + "summary": "Create an item", + "description": "Create an item with all the information:\n\n- **name**: each item must have a name\n- **description**: a long description\n- **price**: required\n- **tax**: if the item doesn't have tax, you can omit this\n- **tags**: a set of unique tag strings for this item", + "operationId": "create_item_items__post", + "requestBody": { + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Item"} + } + }, + "required": True, + }, + } + } + }, + "components": { + "schemas": { + "Item": { + "title": "Item", + "required": ["name", "price"], + "type": "object", + "properties": { + "name": {"title": "Name", "type": "string"}, "description": {"title": "Description", "type": "string"}, + "price": {"title": "Price", "type": "number"}, "tax": {"title": "Tax", "type": "number"}, "tags": { "title": "Tags", diff --git a/tests/test_tutorial/test_path_operation_configurations/test_tutorial005_py39.py b/tests/test_tutorial/test_path_operation_configurations/test_tutorial005_py39.py index 09fac44c4d9dd..e17f2592dc73b 100644 --- a/tests/test_tutorial/test_path_operation_configurations/test_tutorial005_py39.py +++ b/tests/test_tutorial/test_path_operation_configurations/test_tutorial005_py39.py @@ -1,7 +1,7 @@ import pytest from fastapi.testclient import TestClient -from ...utils import needs_py39 +from ...utils import needs_py39, needs_pydanticv1, needs_pydanticv2 @pytest.fixture(name="client") @@ -26,11 +26,12 @@ def test_query_params_str_validations(client: TestClient): @needs_py39 +@needs_pydanticv2 def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { @@ -77,8 +78,112 @@ def test_openapi_schema(client: TestClient): "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, + "description": { + "title": "Description", + "anyOf": [{"type": "string"}, {"type": "null"}], + }, "price": {"title": "Price", "type": "number"}, + "tax": { + "title": "Tax", + "anyOf": [{"type": "number"}, {"type": "null"}], + }, + "tags": { + "title": "Tags", + "uniqueItems": True, + "type": "array", + "items": {"type": "string"}, + "default": [], + }, + }, + }, + "ValidationError": { + "title": "ValidationError", + "required": ["loc", "msg", "type"], + "type": "object", + "properties": { + "loc": { + "title": "Location", + "type": "array", + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + }, + "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"}, + } + }, + }, + } + }, + } + + +# TODO: remove when deprecating Pydantic v1 +@needs_py39 +@needs_pydanticv1 +def test_openapi_schema_pv1(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/items/": { + "post": { + "responses": { + "200": { + "description": "The created item", + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Item"} + } + }, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + "summary": "Create an item", + "description": "Create an item with all the information:\n\n- **name**: each item must have a name\n- **description**: a long description\n- **price**: required\n- **tax**: if the item doesn't have tax, you can omit this\n- **tags**: a set of unique tag strings for this item", + "operationId": "create_item_items__post", + "requestBody": { + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Item"} + } + }, + "required": True, + }, + } + } + }, + "components": { + "schemas": { + "Item": { + "title": "Item", + "required": ["name", "price"], + "type": "object", + "properties": { + "name": {"title": "Name", "type": "string"}, "description": {"title": "Description", "type": "string"}, + "price": {"title": "Price", "type": "number"}, "tax": {"title": "Tax", "type": "number"}, "tags": { "title": "Tags", diff --git a/tests/test_tutorial/test_path_operation_configurations/test_tutorial006.py b/tests/test_tutorial/test_path_operation_configurations/test_tutorial006.py index e90771f24b6d8..91180d10973ce 100644 --- a/tests/test_tutorial/test_path_operation_configurations/test_tutorial006.py +++ b/tests/test_tutorial/test_path_operation_configurations/test_tutorial006.py @@ -24,7 +24,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { diff --git a/tests/test_tutorial/test_path_params/test_tutorial004.py b/tests/test_tutorial/test_path_params/test_tutorial004.py index ab0455bf5d359..acbeaca769895 100644 --- a/tests/test_tutorial/test_path_params/test_tutorial004.py +++ b/tests/test_tutorial/test_path_params/test_tutorial004.py @@ -23,7 +23,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/files/{file_path}": { diff --git a/tests/test_tutorial/test_path_params/test_tutorial005.py b/tests/test_tutorial/test_path_params/test_tutorial005.py index 3401f22534106..2e4b0146bee5f 100644 --- a/tests/test_tutorial/test_path_params/test_tutorial005.py +++ b/tests/test_tutorial/test_path_params/test_tutorial005.py @@ -1,4 +1,4 @@ -import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient from docs_src.path_params.tutorial005 import app @@ -6,52 +6,60 @@ client = TestClient(app) -@pytest.mark.parametrize( - "url,status_code,expected", - [ - ( - "/models/alexnet", - 200, - {"model_name": "alexnet", "message": "Deep Learning FTW!"}, - ), - ( - "/models/lenet", - 200, - {"model_name": "lenet", "message": "LeCNN all the images"}, - ), - ( - "/models/resnet", - 200, - {"model_name": "resnet", "message": "Have some residuals"}, - ), - ( - "/models/foo", - 422, - { - "detail": [ - { - "ctx": {"enum_values": ["alexnet", "resnet", "lenet"]}, - "loc": ["path", "model_name"], - "msg": "value is not a valid enumeration member; permitted: 'alexnet', 'resnet', 'lenet'", - "type": "type_error.enum", - } - ] - }, - ), - ], -) -def test_get_enums(url, status_code, expected): - response = client.get(url) - assert response.status_code == status_code - assert response.json() == expected +def test_get_enums_alexnet(): + response = client.get("/models/alexnet") + assert response.status_code == 200 + assert response.json() == {"model_name": "alexnet", "message": "Deep Learning FTW!"} + + +def test_get_enums_lenet(): + response = client.get("/models/lenet") + assert response.status_code == 200 + assert response.json() == {"model_name": "lenet", "message": "LeCNN all the images"} -def test_openapi(): +def test_get_enums_resnet(): + response = client.get("/models/resnet") + assert response.status_code == 200 + assert response.json() == {"model_name": "resnet", "message": "Have some residuals"} + + +def test_get_enums_invalid(): + response = client.get("/models/foo") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "enum", + "loc": ["path", "model_name"], + "msg": "Input should be 'alexnet', 'resnet' or 'lenet'", + "input": "foo", + "ctx": {"expected": "'alexnet', 'resnet' or 'lenet'"}, + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "ctx": {"enum_values": ["alexnet", "resnet", "lenet"]}, + "loc": ["path", "model_name"], + "msg": "value is not a valid enumeration member; permitted: 'alexnet', 'resnet', 'lenet'", + "type": "type_error.enum", + } + ] + } + ) + + +def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text data = response.json() assert data == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/models/{model_name}": { @@ -98,12 +106,22 @@ def test_openapi(): } }, }, - "ModelName": { - "title": "ModelName", - "enum": ["alexnet", "resnet", "lenet"], - "type": "string", - "description": "An enumeration.", - }, + "ModelName": IsDict( + { + "title": "ModelName", + "enum": ["alexnet", "resnet", "lenet"], + "type": "string", + } + ) + | IsDict( + { + # TODO: remove when deprecating Pydantic v1 + "title": "ModelName", + "enum": ["alexnet", "resnet", "lenet"], + "type": "string", + "description": "An enumeration.", + } + ), "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], diff --git a/tests/test_tutorial/test_query_params/test_tutorial005.py b/tests/test_tutorial/test_query_params/test_tutorial005.py index 3c408449b8116..9215863576349 100644 --- a/tests/test_tutorial/test_query_params/test_tutorial005.py +++ b/tests/test_tutorial/test_query_params/test_tutorial005.py @@ -1,41 +1,52 @@ -import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url from docs_src.query_params.tutorial005 import app client = TestClient(app) -query_required = { - "detail": [ - { - "loc": ["query", "needy"], - "msg": "field required", - "type": "value_error.missing", - } - ] -} +def test_foo_needy_very(): + response = client.get("/items/foo?needy=very") + assert response.status_code == 200 + assert response.json() == {"item_id": "foo", "needy": "very"} -@pytest.mark.parametrize( - "path,expected_status,expected_response", - [ - ("/items/foo?needy=very", 200, {"item_id": "foo", "needy": "very"}), - ("/items/foo", 422, query_required), - ("/items/foo", 422, query_required), - ], -) -def test(path, expected_status, expected_response): - response = client.get(path) - assert response.status_code == expected_status - assert response.json() == expected_response +def test_foo_no_needy(): + response = client.get("/items/foo") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["query", "needy"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["query", "needy"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200 assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { diff --git a/tests/test_tutorial/test_query_params/test_tutorial006.py b/tests/test_tutorial/test_query_params/test_tutorial006.py index 7fe58a99008ee..e07803d6c9b5f 100644 --- a/tests/test_tutorial/test_query_params/test_tutorial006.py +++ b/tests/test_tutorial/test_query_params/test_tutorial006.py @@ -1,66 +1,86 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url -from docs_src.query_params.tutorial006 import app -client = TestClient(app) +@pytest.fixture(name="client") +def get_client(): + from docs_src.query_params.tutorial006 import app + c = TestClient(app) + return c -query_required = { - "detail": [ - { - "loc": ["query", "needy"], - "msg": "field required", - "type": "value_error.missing", - } - ] -} + +def test_foo_needy_very(client: TestClient): + response = client.get("/items/foo?needy=very") + assert response.status_code == 200 + assert response.json() == { + "item_id": "foo", + "needy": "very", + "skip": 0, + "limit": None, + } -@pytest.mark.parametrize( - "path,expected_status,expected_response", - [ - ( - "/items/foo?needy=very", - 200, - {"item_id": "foo", "needy": "very", "skip": 0, "limit": None}, - ), - ( - "/items/foo?skip=a&limit=b", - 422, - { - "detail": [ - { - "loc": ["query", "needy"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["query", "skip"], - "msg": "value is not a valid integer", - "type": "type_error.integer", - }, - { - "loc": ["query", "limit"], - "msg": "value is not a valid integer", - "type": "type_error.integer", - }, - ] - }, - ), - ], -) -def test(path, expected_status, expected_response): - response = client.get(path) - assert response.status_code == expected_status - assert response.json() == expected_response +def test_foo_no_needy(client: TestClient): + response = client.get("/items/foo?skip=a&limit=b") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["query", "needy"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "int_parsing", + "loc": ["query", "skip"], + "msg": "Input should be a valid integer, unable to parse string as an integer", + "input": "a", + "url": match_pydantic_error_url("int_parsing"), + }, + { + "type": "int_parsing", + "loc": ["query", "limit"], + "msg": "Input should be a valid integer, unable to parse string as an integer", + "input": "b", + "url": match_pydantic_error_url("int_parsing"), + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["query", "needy"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["query", "skip"], + "msg": "value is not a valid integer", + "type": "type_error.integer", + }, + { + "loc": ["query", "limit"], + "msg": "value is not a valid integer", + "type": "type_error.integer", + }, + ] + } + ) -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200 assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { @@ -108,7 +128,16 @@ def test_openapi_schema(): }, { "required": False, - "schema": {"title": "Limit", "type": "integer"}, + "schema": IsDict( + { + "anyOf": [{"type": "integer"}, {"type": "null"}], + "title": "Limit", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Limit", "type": "integer"} + ), "name": "limit", "in": "query", }, diff --git a/tests/test_tutorial/test_query_params/test_tutorial006_py310.py b/tests/test_tutorial/test_query_params/test_tutorial006_py310.py index b90c0a6c8ea9b..6c4c0b4dc8927 100644 --- a/tests/test_tutorial/test_query_params/test_tutorial006_py310.py +++ b/tests/test_tutorial/test_query_params/test_tutorial006_py310.py @@ -1,18 +1,10 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url from ...utils import needs_py310 -query_required = { - "detail": [ - { - "loc": ["query", "needy"], - "msg": "field required", - "type": "value_error.missing", - } - ] -} - @pytest.fixture(name="client") def get_client(): @@ -23,43 +15,69 @@ def get_client(): @needs_py310 -@pytest.mark.parametrize( - "path,expected_status,expected_response", - [ - ( - "/items/foo?needy=very", - 200, - {"item_id": "foo", "needy": "very", "skip": 0, "limit": None}, - ), - ( - "/items/foo?skip=a&limit=b", - 422, - { - "detail": [ - { - "loc": ["query", "needy"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["query", "skip"], - "msg": "value is not a valid integer", - "type": "type_error.integer", - }, - { - "loc": ["query", "limit"], - "msg": "value is not a valid integer", - "type": "type_error.integer", - }, - ] - }, - ), - ], -) -def test(path, expected_status, expected_response, client: TestClient): - response = client.get(path) - assert response.status_code == expected_status - assert response.json() == expected_response +def test_foo_needy_very(client: TestClient): + response = client.get("/items/foo?needy=very") + assert response.status_code == 200 + assert response.json() == { + "item_id": "foo", + "needy": "very", + "skip": 0, + "limit": None, + } + + +@needs_py310 +def test_foo_no_needy(client: TestClient): + response = client.get("/items/foo?skip=a&limit=b") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["query", "needy"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "int_parsing", + "loc": ["query", "skip"], + "msg": "Input should be a valid integer, unable to parse string as an integer", + "input": "a", + "url": match_pydantic_error_url("int_parsing"), + }, + { + "type": "int_parsing", + "loc": ["query", "limit"], + "msg": "Input should be a valid integer, unable to parse string as an integer", + "input": "b", + "url": match_pydantic_error_url("int_parsing"), + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["query", "needy"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["query", "skip"], + "msg": "value is not a valid integer", + "type": "type_error.integer", + }, + { + "loc": ["query", "limit"], + "msg": "value is not a valid integer", + "type": "type_error.integer", + }, + ] + } + ) @needs_py310 @@ -67,7 +85,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200 assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { @@ -115,7 +133,16 @@ def test_openapi_schema(client: TestClient): }, { "required": False, - "schema": {"title": "Limit", "type": "integer"}, + "schema": IsDict( + { + "anyOf": [{"type": "integer"}, {"type": "null"}], + "title": "Limit", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Limit", "type": "integer"} + ), "name": "limit", "in": "query", }, diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010.py index c41f554ba374b..287c2e8f8e9e0 100644 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010.py +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010.py @@ -1,51 +1,74 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url -from docs_src.query_params_str_validations.tutorial010 import app -client = TestClient(app) +@pytest.fixture(name="client") +def get_client(): + from docs_src.query_params_str_validations.tutorial010 import app + client = TestClient(app) + return client -regex_error = { - "detail": [ - { - "ctx": {"pattern": "^fixedquery$"}, - "loc": ["query", "item-query"], - "msg": 'string does not match regex "^fixedquery$"', - "type": "value_error.str.regex", - } - ] -} + +def test_query_params_str_validations_no_query(client: TestClient): + response = client.get("/items/") + assert response.status_code == 200 + assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} + + +def test_query_params_str_validations_item_query_fixedquery(client: TestClient): + response = client.get("/items/", params={"item-query": "fixedquery"}) + assert response.status_code == 200 + assert response.json() == { + "items": [{"item_id": "Foo"}, {"item_id": "Bar"}], + "q": "fixedquery", + } + + +def test_query_params_str_validations_q_fixedquery(client: TestClient): + response = client.get("/items/", params={"q": "fixedquery"}) + assert response.status_code == 200 + assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} -@pytest.mark.parametrize( - "q_name,q,expected_status,expected_response", - [ - (None, None, 200, {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}), - ( - "item-query", - "fixedquery", - 200, - {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}], "q": "fixedquery"}, - ), - ("q", "fixedquery", 200, {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}), - ("item-query", "nonregexquery", 422, regex_error), - ], -) -def test_query_params_str_validations(q_name, q, expected_status, expected_response): - url = "/items/" - if q_name and q: - url = f"{url}?{q_name}={q}" - response = client.get(url) - assert response.status_code == expected_status - assert response.json() == expected_response +def test_query_params_str_validations_item_query_nonregexquery(client: TestClient): + response = client.get("/items/", params={"item-query": "nonregexquery"}) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "string_pattern_mismatch", + "loc": ["query", "item-query"], + "msg": "String should match pattern '^fixedquery$'", + "input": "nonregexquery", + "ctx": {"pattern": "^fixedquery$"}, + "url": match_pydantic_error_url("string_pattern_mismatch"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "ctx": {"pattern": "^fixedquery$"}, + "loc": ["query", "item-query"], + "msg": 'string does not match regex "^fixedquery$"', + "type": "value_error.str.regex", + } + ] + } + ) -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { @@ -73,14 +96,32 @@ def test_openapi_schema(): "description": "Query string for the items to search in the database that have a good match", "required": False, "deprecated": True, - "schema": { - "title": "Query string", - "maxLength": 50, - "minLength": 3, - "pattern": "^fixedquery$", - "type": "string", - "description": "Query string for the items to search in the database that have a good match", - }, + "schema": IsDict( + { + "anyOf": [ + { + "type": "string", + "minLength": 3, + "maxLength": 50, + "pattern": "^fixedquery$", + }, + {"type": "null"}, + ], + "title": "Query string", + "description": "Query string for the items to search in the database that have a good match", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "Query string", + "maxLength": 50, + "minLength": 3, + "pattern": "^fixedquery$", + "type": "string", + "description": "Query string for the items to search in the database that have a good match", + } + ), "name": "item-query", "in": "query", } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an.py index dc8028f81199e..5b0515070ab60 100644 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an.py +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an.py @@ -1,51 +1,74 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url -from docs_src.query_params_str_validations.tutorial010_an import app -client = TestClient(app) +@pytest.fixture(name="client") +def get_client(): + from docs_src.query_params_str_validations.tutorial010_an import app + client = TestClient(app) + return client -regex_error = { - "detail": [ - { - "ctx": {"pattern": "^fixedquery$"}, - "loc": ["query", "item-query"], - "msg": 'string does not match regex "^fixedquery$"', - "type": "value_error.str.regex", - } - ] -} + +def test_query_params_str_validations_no_query(client: TestClient): + response = client.get("/items/") + assert response.status_code == 200 + assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} + + +def test_query_params_str_validations_item_query_fixedquery(client: TestClient): + response = client.get("/items/", params={"item-query": "fixedquery"}) + assert response.status_code == 200 + assert response.json() == { + "items": [{"item_id": "Foo"}, {"item_id": "Bar"}], + "q": "fixedquery", + } + + +def test_query_params_str_validations_q_fixedquery(client: TestClient): + response = client.get("/items/", params={"q": "fixedquery"}) + assert response.status_code == 200 + assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} -@pytest.mark.parametrize( - "q_name,q,expected_status,expected_response", - [ - (None, None, 200, {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}), - ( - "item-query", - "fixedquery", - 200, - {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}], "q": "fixedquery"}, - ), - ("q", "fixedquery", 200, {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}), - ("item-query", "nonregexquery", 422, regex_error), - ], -) -def test_query_params_str_validations(q_name, q, expected_status, expected_response): - url = "/items/" - if q_name and q: - url = f"{url}?{q_name}={q}" - response = client.get(url) - assert response.status_code == expected_status - assert response.json() == expected_response +def test_query_params_str_validations_item_query_nonregexquery(client: TestClient): + response = client.get("/items/", params={"item-query": "nonregexquery"}) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "string_pattern_mismatch", + "loc": ["query", "item-query"], + "msg": "String should match pattern '^fixedquery$'", + "input": "nonregexquery", + "ctx": {"pattern": "^fixedquery$"}, + "url": match_pydantic_error_url("string_pattern_mismatch"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "ctx": {"pattern": "^fixedquery$"}, + "loc": ["query", "item-query"], + "msg": 'string does not match regex "^fixedquery$"', + "type": "value_error.str.regex", + } + ] + } + ) -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { @@ -73,14 +96,32 @@ def test_openapi_schema(): "description": "Query string for the items to search in the database that have a good match", "required": False, "deprecated": True, - "schema": { - "title": "Query string", - "maxLength": 50, - "minLength": 3, - "pattern": "^fixedquery$", - "type": "string", - "description": "Query string for the items to search in the database that have a good match", - }, + "schema": IsDict( + { + "anyOf": [ + { + "type": "string", + "minLength": 3, + "maxLength": 50, + "pattern": "^fixedquery$", + }, + {"type": "null"}, + ], + "title": "Query string", + "description": "Query string for the items to search in the database that have a good match", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "Query string", + "maxLength": 50, + "minLength": 3, + "pattern": "^fixedquery$", + "type": "string", + "description": "Query string for the items to search in the database that have a good match", + } + ), "name": "item-query", "in": "query", } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py310.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py310.py index 496b95b797a2a..d22b1ce204a11 100644 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py310.py +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py310.py @@ -1,5 +1,7 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url from ...utils import needs_py310 @@ -12,42 +14,60 @@ def get_client(): return client -regex_error = { - "detail": [ - { - "ctx": {"pattern": "^fixedquery$"}, - "loc": ["query", "item-query"], - "msg": 'string does not match regex "^fixedquery$"', - "type": "value_error.str.regex", - } - ] -} +@needs_py310 +def test_query_params_str_validations_no_query(client: TestClient): + response = client.get("/items/") + assert response.status_code == 200 + assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} + + +@needs_py310 +def test_query_params_str_validations_item_query_fixedquery(client: TestClient): + response = client.get("/items/", params={"item-query": "fixedquery"}) + assert response.status_code == 200 + assert response.json() == { + "items": [{"item_id": "Foo"}, {"item_id": "Bar"}], + "q": "fixedquery", + } + + +@needs_py310 +def test_query_params_str_validations_q_fixedquery(client: TestClient): + response = client.get("/items/", params={"q": "fixedquery"}) + assert response.status_code == 200 + assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} @needs_py310 -@pytest.mark.parametrize( - "q_name,q,expected_status,expected_response", - [ - (None, None, 200, {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}), - ( - "item-query", - "fixedquery", - 200, - {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}], "q": "fixedquery"}, - ), - ("q", "fixedquery", 200, {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}), - ("item-query", "nonregexquery", 422, regex_error), - ], -) -def test_query_params_str_validations( - q_name, q, expected_status, expected_response, client: TestClient -): - url = "/items/" - if q_name and q: - url = f"{url}?{q_name}={q}" - response = client.get(url) - assert response.status_code == expected_status - assert response.json() == expected_response +def test_query_params_str_validations_item_query_nonregexquery(client: TestClient): + response = client.get("/items/", params={"item-query": "nonregexquery"}) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "string_pattern_mismatch", + "loc": ["query", "item-query"], + "msg": "String should match pattern '^fixedquery$'", + "input": "nonregexquery", + "ctx": {"pattern": "^fixedquery$"}, + "url": match_pydantic_error_url("string_pattern_mismatch"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "ctx": {"pattern": "^fixedquery$"}, + "loc": ["query", "item-query"], + "msg": 'string does not match regex "^fixedquery$"', + "type": "value_error.str.regex", + } + ] + } + ) @needs_py310 @@ -55,7 +75,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { @@ -83,14 +103,32 @@ def test_openapi_schema(client: TestClient): "description": "Query string for the items to search in the database that have a good match", "required": False, "deprecated": True, - "schema": { - "title": "Query string", - "maxLength": 50, - "minLength": 3, - "pattern": "^fixedquery$", - "type": "string", - "description": "Query string for the items to search in the database that have a good match", - }, + "schema": IsDict( + { + "anyOf": [ + { + "type": "string", + "minLength": 3, + "maxLength": 50, + "pattern": "^fixedquery$", + }, + {"type": "null"}, + ], + "title": "Query string", + "description": "Query string for the items to search in the database that have a good match", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "Query string", + "maxLength": 50, + "minLength": 3, + "pattern": "^fixedquery$", + "type": "string", + "description": "Query string for the items to search in the database that have a good match", + } + ), "name": "item-query", "in": "query", } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py39.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py39.py index 2005e50433731..3e7d5d3adbe63 100644 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py39.py +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py39.py @@ -1,5 +1,7 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url from ...utils import needs_py39 @@ -12,42 +14,60 @@ def get_client(): return client -regex_error = { - "detail": [ - { - "ctx": {"pattern": "^fixedquery$"}, - "loc": ["query", "item-query"], - "msg": 'string does not match regex "^fixedquery$"', - "type": "value_error.str.regex", - } - ] -} +@needs_py39 +def test_query_params_str_validations_no_query(client: TestClient): + response = client.get("/items/") + assert response.status_code == 200 + assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} + + +@needs_py39 +def test_query_params_str_validations_item_query_fixedquery(client: TestClient): + response = client.get("/items/", params={"item-query": "fixedquery"}) + assert response.status_code == 200 + assert response.json() == { + "items": [{"item_id": "Foo"}, {"item_id": "Bar"}], + "q": "fixedquery", + } + + +@needs_py39 +def test_query_params_str_validations_q_fixedquery(client: TestClient): + response = client.get("/items/", params={"q": "fixedquery"}) + assert response.status_code == 200 + assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} @needs_py39 -@pytest.mark.parametrize( - "q_name,q,expected_status,expected_response", - [ - (None, None, 200, {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}), - ( - "item-query", - "fixedquery", - 200, - {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}], "q": "fixedquery"}, - ), - ("q", "fixedquery", 200, {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}), - ("item-query", "nonregexquery", 422, regex_error), - ], -) -def test_query_params_str_validations( - q_name, q, expected_status, expected_response, client: TestClient -): - url = "/items/" - if q_name and q: - url = f"{url}?{q_name}={q}" - response = client.get(url) - assert response.status_code == expected_status - assert response.json() == expected_response +def test_query_params_str_validations_item_query_nonregexquery(client: TestClient): + response = client.get("/items/", params={"item-query": "nonregexquery"}) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "string_pattern_mismatch", + "loc": ["query", "item-query"], + "msg": "String should match pattern '^fixedquery$'", + "input": "nonregexquery", + "ctx": {"pattern": "^fixedquery$"}, + "url": match_pydantic_error_url("string_pattern_mismatch"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "ctx": {"pattern": "^fixedquery$"}, + "loc": ["query", "item-query"], + "msg": 'string does not match regex "^fixedquery$"', + "type": "value_error.str.regex", + } + ] + } + ) @needs_py39 @@ -55,7 +75,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { @@ -83,14 +103,32 @@ def test_openapi_schema(client: TestClient): "description": "Query string for the items to search in the database that have a good match", "required": False, "deprecated": True, - "schema": { - "title": "Query string", - "maxLength": 50, - "minLength": 3, - "pattern": "^fixedquery$", - "type": "string", - "description": "Query string for the items to search in the database that have a good match", - }, + "schema": IsDict( + { + "anyOf": [ + { + "type": "string", + "minLength": 3, + "maxLength": 50, + "pattern": "^fixedquery$", + }, + {"type": "null"}, + ], + "title": "Query string", + "description": "Query string for the items to search in the database that have a good match", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "Query string", + "maxLength": 50, + "minLength": 3, + "pattern": "^fixedquery$", + "type": "string", + "description": "Query string for the items to search in the database that have a good match", + } + ), "name": "item-query", "in": "query", } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_py310.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_py310.py index 8147d768e0f39..1c3a09d399f46 100644 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_py310.py +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_py310.py @@ -1,5 +1,7 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url from ...utils import needs_py310 @@ -12,42 +14,60 @@ def get_client(): return client -regex_error = { - "detail": [ - { - "ctx": {"pattern": "^fixedquery$"}, - "loc": ["query", "item-query"], - "msg": 'string does not match regex "^fixedquery$"', - "type": "value_error.str.regex", - } - ] -} +@needs_py310 +def test_query_params_str_validations_no_query(client: TestClient): + response = client.get("/items/") + assert response.status_code == 200 + assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} + + +@needs_py310 +def test_query_params_str_validations_item_query_fixedquery(client: TestClient): + response = client.get("/items/", params={"item-query": "fixedquery"}) + assert response.status_code == 200 + assert response.json() == { + "items": [{"item_id": "Foo"}, {"item_id": "Bar"}], + "q": "fixedquery", + } + + +@needs_py310 +def test_query_params_str_validations_q_fixedquery(client: TestClient): + response = client.get("/items/", params={"q": "fixedquery"}) + assert response.status_code == 200 + assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} @needs_py310 -@pytest.mark.parametrize( - "q_name,q,expected_status,expected_response", - [ - (None, None, 200, {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}), - ( - "item-query", - "fixedquery", - 200, - {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}], "q": "fixedquery"}, - ), - ("q", "fixedquery", 200, {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}), - ("item-query", "nonregexquery", 422, regex_error), - ], -) -def test_query_params_str_validations( - q_name, q, expected_status, expected_response, client: TestClient -): - url = "/items/" - if q_name and q: - url = f"{url}?{q_name}={q}" - response = client.get(url) - assert response.status_code == expected_status - assert response.json() == expected_response +def test_query_params_str_validations_item_query_nonregexquery(client: TestClient): + response = client.get("/items/", params={"item-query": "nonregexquery"}) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "string_pattern_mismatch", + "loc": ["query", "item-query"], + "msg": "String should match pattern '^fixedquery$'", + "input": "nonregexquery", + "ctx": {"pattern": "^fixedquery$"}, + "url": match_pydantic_error_url("string_pattern_mismatch"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "ctx": {"pattern": "^fixedquery$"}, + "loc": ["query", "item-query"], + "msg": 'string does not match regex "^fixedquery$"', + "type": "value_error.str.regex", + } + ] + } + ) @needs_py310 @@ -55,7 +75,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { @@ -83,14 +103,32 @@ def test_openapi_schema(client: TestClient): "description": "Query string for the items to search in the database that have a good match", "required": False, "deprecated": True, - "schema": { - "title": "Query string", - "maxLength": 50, - "minLength": 3, - "pattern": "^fixedquery$", - "type": "string", - "description": "Query string for the items to search in the database that have a good match", - }, + "schema": IsDict( + { + "anyOf": [ + { + "type": "string", + "minLength": 3, + "maxLength": 50, + "pattern": "^fixedquery$", + }, + {"type": "null"}, + ], + "title": "Query string", + "description": "Query string for the items to search in the database that have a good match", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "Query string", + "maxLength": 50, + "minLength": 3, + "pattern": "^fixedquery$", + "type": "string", + "description": "Query string for the items to search in the database that have a good match", + } + ), "name": "item-query", "in": "query", } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial011.py index d6d69c1691232..5ba39b05d612b 100644 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011.py +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial011.py @@ -1,3 +1,4 @@ +from dirty_equals import IsDict from fastapi.testclient import TestClient from docs_src.query_params_str_validations.tutorial011 import app @@ -23,7 +24,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { @@ -49,11 +50,23 @@ def test_openapi_schema(): "parameters": [ { "required": False, - "schema": { - "title": "Q", - "type": "array", - "items": {"type": "string"}, - }, + "schema": IsDict( + { + "anyOf": [ + {"type": "array", "items": {"type": "string"}}, + {"type": "null"}, + ], + "title": "Q", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "Q", + "type": "array", + "items": {"type": "string"}, + } + ), "name": "q", "in": "query", } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_an.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_an.py index 3a53d422e0f1d..3942ea77a9385 100644 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_an.py +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_an.py @@ -1,3 +1,4 @@ +from dirty_equals import IsDict from fastapi.testclient import TestClient from docs_src.query_params_str_validations.tutorial011_an import app @@ -23,7 +24,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { @@ -49,11 +50,23 @@ def test_openapi_schema(): "parameters": [ { "required": False, - "schema": { - "title": "Q", - "type": "array", - "items": {"type": "string"}, - }, + "schema": IsDict( + { + "anyOf": [ + {"type": "array", "items": {"type": "string"}}, + {"type": "null"}, + ], + "title": "Q", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "Q", + "type": "array", + "items": {"type": "string"}, + } + ), "name": "q", "in": "query", } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_an_py310.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_an_py310.py index f00df28791810..f2ec38c950415 100644 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_an_py310.py +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_an_py310.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient from ...utils import needs_py310 @@ -33,7 +34,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { @@ -59,11 +60,23 @@ def test_openapi_schema(client: TestClient): "parameters": [ { "required": False, - "schema": { - "title": "Q", - "type": "array", - "items": {"type": "string"}, - }, + "schema": IsDict( + { + "anyOf": [ + {"type": "array", "items": {"type": "string"}}, + {"type": "null"}, + ], + "title": "Q", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "Q", + "type": "array", + "items": {"type": "string"}, + } + ), "name": "q", "in": "query", } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_an_py39.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_an_py39.py index 895fb8e9f4e17..cd7b156798981 100644 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_an_py39.py +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_an_py39.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient from ...utils import needs_py39 @@ -33,7 +34,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { @@ -59,11 +60,23 @@ def test_openapi_schema(client: TestClient): "parameters": [ { "required": False, - "schema": { - "title": "Q", - "type": "array", - "items": {"type": "string"}, - }, + "schema": IsDict( + { + "anyOf": [ + {"type": "array", "items": {"type": "string"}}, + {"type": "null"}, + ], + "title": "Q", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "Q", + "type": "array", + "items": {"type": "string"}, + } + ), "name": "q", "in": "query", } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_py310.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_py310.py index 4f4b1fd558b65..bdc7295162515 100644 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_py310.py +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_py310.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient from ...utils import needs_py310 @@ -33,7 +34,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { @@ -59,11 +60,23 @@ def test_openapi_schema(client: TestClient): "parameters": [ { "required": False, - "schema": { - "title": "Q", - "type": "array", - "items": {"type": "string"}, - }, + "schema": IsDict( + { + "anyOf": [ + {"type": "array", "items": {"type": "string"}}, + {"type": "null"}, + ], + "title": "Q", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "Q", + "type": "array", + "items": {"type": "string"}, + } + ), "name": "q", "in": "query", } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_py39.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_py39.py index d85bb623123e3..26ac56b2f1bd8 100644 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_py39.py +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_py39.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient from ...utils import needs_py39 @@ -33,7 +34,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { @@ -59,11 +60,23 @@ def test_openapi_schema(client: TestClient): "parameters": [ { "required": False, - "schema": { - "title": "Q", - "type": "array", - "items": {"type": "string"}, - }, + "schema": IsDict( + { + "anyOf": [ + {"type": "array", "items": {"type": "string"}}, + {"type": "null"}, + ], + "title": "Q", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "Q", + "type": "array", + "items": {"type": "string"}, + } + ), "name": "q", "in": "query", } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial012.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial012.py index 7bc020540ab24..1436db384c992 100644 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial012.py +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial012.py @@ -23,7 +23,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial012_an.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial012_an.py index be5557f6ad3c6..270763f1d1125 100644 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial012_an.py +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial012_an.py @@ -23,7 +23,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial012_an_py39.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial012_an_py39.py index d9512e193f91f..5483916839532 100644 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial012_an_py39.py +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial012_an_py39.py @@ -33,7 +33,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial012_py39.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial012_py39.py index b2a2c8d1d190d..e7d74515482a8 100644 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial012_py39.py +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial012_py39.py @@ -33,7 +33,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial013.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial013.py index 4a0b9e8b5fcee..1ba1fdf618caf 100644 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial013.py +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial013.py @@ -23,7 +23,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial013_an.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial013_an.py index 71e4638ae4f5a..3432617481d86 100644 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial013_an.py +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial013_an.py @@ -23,7 +23,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial013_an_py39.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial013_an_py39.py index 4e90db358b4b6..537d6325b3598 100644 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial013_an_py39.py +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial013_an_py39.py @@ -33,7 +33,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial014.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial014.py index 7686c07b39f42..7bce7590c20b1 100644 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial014.py +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial014.py @@ -21,7 +21,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_an.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_an.py index e739044a83fad..2182e87b75434 100644 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_an.py +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_an.py @@ -21,7 +21,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_an_py310.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_an_py310.py index 73f0ba78b80fa..344004d01b221 100644 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_an_py310.py +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_an_py310.py @@ -31,7 +31,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_an_py39.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_an_py39.py index e2c14999212bc..5d4f6df3d0af9 100644 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_an_py39.py +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_an_py39.py @@ -31,7 +31,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_py310.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_py310.py index 07f30b7395b2a..dad49fb12d501 100644 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_py310.py +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_py310.py @@ -31,7 +31,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { diff --git a/tests/test_tutorial/test_request_files/test_tutorial001.py b/tests/test_tutorial/test_request_files/test_tutorial001.py index 3269801efcd7b..91cc2b6365a16 100644 --- a/tests/test_tutorial/test_request_files/test_tutorial001.py +++ b/tests/test_tutorial/test_request_files/test_tutorial001.py @@ -1,4 +1,6 @@ +from dirty_equals import IsDict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url from docs_src.request_files.tutorial001 import app @@ -19,13 +21,59 @@ def test_post_form_no_body(): response = client.post("/files/") assert response.status_code == 422, response.text - assert response.json() == file_required + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "file"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "file"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) def test_post_body_json(): response = client.post("/files/", json={"file": "Foo"}) assert response.status_code == 422, response.text - assert response.json() == file_required + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "file"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "file"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) def test_post_file(tmp_path): @@ -66,7 +114,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/files/": { diff --git a/tests/test_tutorial/test_request_files/test_tutorial001_02.py b/tests/test_tutorial/test_request_files/test_tutorial001_02.py index 4b6edfa066699..42f75442a5489 100644 --- a/tests/test_tutorial/test_request_files/test_tutorial001_02.py +++ b/tests/test_tutorial/test_request_files/test_tutorial001_02.py @@ -1,3 +1,4 @@ +from dirty_equals import IsDict from fastapi.testclient import TestClient from docs_src.request_files.tutorial001_02 import app @@ -43,7 +44,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/files/": { @@ -53,9 +54,22 @@ def test_openapi_schema(): "requestBody": { "content": { "multipart/form-data": { - "schema": { - "$ref": "#/components/schemas/Body_create_file_files__post" - } + "schema": IsDict( + { + "allOf": [ + { + "$ref": "#/components/schemas/Body_create_file_files__post" + } + ], + "title": "Body", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "$ref": "#/components/schemas/Body_create_file_files__post" + } + ) } } }, @@ -84,9 +98,22 @@ def test_openapi_schema(): "requestBody": { "content": { "multipart/form-data": { - "schema": { - "$ref": "#/components/schemas/Body_create_upload_file_uploadfile__post" - } + "schema": IsDict( + { + "allOf": [ + { + "$ref": "#/components/schemas/Body_create_upload_file_uploadfile__post" + } + ], + "title": "Body", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "$ref": "#/components/schemas/Body_create_upload_file_uploadfile__post" + } + ) } } }, @@ -115,14 +142,38 @@ def test_openapi_schema(): "title": "Body_create_file_files__post", "type": "object", "properties": { - "file": {"title": "File", "type": "string", "format": "binary"} + "file": IsDict( + { + "title": "File", + "anyOf": [ + {"type": "string", "format": "binary"}, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "File", "type": "string", "format": "binary"} + ) }, }, "Body_create_upload_file_uploadfile__post": { "title": "Body_create_upload_file_uploadfile__post", "type": "object", "properties": { - "file": {"title": "File", "type": "string", "format": "binary"} + "file": IsDict( + { + "title": "File", + "anyOf": [ + {"type": "string", "format": "binary"}, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "File", "type": "string", "format": "binary"} + ) }, }, "HTTPValidationError": { diff --git a/tests/test_tutorial/test_request_files/test_tutorial001_02_an.py b/tests/test_tutorial/test_request_files/test_tutorial001_02_an.py index 0c34620e38d84..f63eb339c4263 100644 --- a/tests/test_tutorial/test_request_files/test_tutorial001_02_an.py +++ b/tests/test_tutorial/test_request_files/test_tutorial001_02_an.py @@ -1,3 +1,4 @@ +from dirty_equals import IsDict from fastapi.testclient import TestClient from docs_src.request_files.tutorial001_02_an import app @@ -43,7 +44,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/files/": { @@ -53,9 +54,22 @@ def test_openapi_schema(): "requestBody": { "content": { "multipart/form-data": { - "schema": { - "$ref": "#/components/schemas/Body_create_file_files__post" - } + "schema": IsDict( + { + "allOf": [ + { + "$ref": "#/components/schemas/Body_create_file_files__post" + } + ], + "title": "Body", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "$ref": "#/components/schemas/Body_create_file_files__post" + } + ) } } }, @@ -84,9 +98,22 @@ def test_openapi_schema(): "requestBody": { "content": { "multipart/form-data": { - "schema": { - "$ref": "#/components/schemas/Body_create_upload_file_uploadfile__post" - } + "schema": IsDict( + { + "allOf": [ + { + "$ref": "#/components/schemas/Body_create_upload_file_uploadfile__post" + } + ], + "title": "Body", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "$ref": "#/components/schemas/Body_create_upload_file_uploadfile__post" + } + ) } } }, @@ -115,14 +142,38 @@ def test_openapi_schema(): "title": "Body_create_file_files__post", "type": "object", "properties": { - "file": {"title": "File", "type": "string", "format": "binary"} + "file": IsDict( + { + "title": "File", + "anyOf": [ + {"type": "string", "format": "binary"}, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "File", "type": "string", "format": "binary"} + ) }, }, "Body_create_upload_file_uploadfile__post": { "title": "Body_create_upload_file_uploadfile__post", "type": "object", "properties": { - "file": {"title": "File", "type": "string", "format": "binary"} + "file": IsDict( + { + "title": "File", + "anyOf": [ + {"type": "string", "format": "binary"}, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "File", "type": "string", "format": "binary"} + ) }, }, "HTTPValidationError": { diff --git a/tests/test_tutorial/test_request_files/test_tutorial001_02_an_py310.py b/tests/test_tutorial/test_request_files/test_tutorial001_02_an_py310.py index 04442c76f451d..94b6ac67ee02c 100644 --- a/tests/test_tutorial/test_request_files/test_tutorial001_02_an_py310.py +++ b/tests/test_tutorial/test_request_files/test_tutorial001_02_an_py310.py @@ -1,6 +1,7 @@ from pathlib import Path import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient from ...utils import needs_py310 @@ -55,7 +56,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/files/": { @@ -65,9 +66,22 @@ def test_openapi_schema(client: TestClient): "requestBody": { "content": { "multipart/form-data": { - "schema": { - "$ref": "#/components/schemas/Body_create_file_files__post" - } + "schema": IsDict( + { + "allOf": [ + { + "$ref": "#/components/schemas/Body_create_file_files__post" + } + ], + "title": "Body", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "$ref": "#/components/schemas/Body_create_file_files__post" + } + ) } } }, @@ -96,9 +110,22 @@ def test_openapi_schema(client: TestClient): "requestBody": { "content": { "multipart/form-data": { - "schema": { - "$ref": "#/components/schemas/Body_create_upload_file_uploadfile__post" - } + "schema": IsDict( + { + "allOf": [ + { + "$ref": "#/components/schemas/Body_create_upload_file_uploadfile__post" + } + ], + "title": "Body", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "$ref": "#/components/schemas/Body_create_upload_file_uploadfile__post" + } + ) } } }, @@ -127,14 +154,38 @@ def test_openapi_schema(client: TestClient): "title": "Body_create_file_files__post", "type": "object", "properties": { - "file": {"title": "File", "type": "string", "format": "binary"} + "file": IsDict( + { + "title": "File", + "anyOf": [ + {"type": "string", "format": "binary"}, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "File", "type": "string", "format": "binary"} + ) }, }, "Body_create_upload_file_uploadfile__post": { "title": "Body_create_upload_file_uploadfile__post", "type": "object", "properties": { - "file": {"title": "File", "type": "string", "format": "binary"} + "file": IsDict( + { + "title": "File", + "anyOf": [ + {"type": "string", "format": "binary"}, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "File", "type": "string", "format": "binary"} + ) }, }, "HTTPValidationError": { diff --git a/tests/test_tutorial/test_request_files/test_tutorial001_02_an_py39.py b/tests/test_tutorial/test_request_files/test_tutorial001_02_an_py39.py index f5249ef5bf324..fcb39f8f18575 100644 --- a/tests/test_tutorial/test_request_files/test_tutorial001_02_an_py39.py +++ b/tests/test_tutorial/test_request_files/test_tutorial001_02_an_py39.py @@ -1,6 +1,7 @@ from pathlib import Path import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient from ...utils import needs_py39 @@ -55,7 +56,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/files/": { @@ -65,9 +66,22 @@ def test_openapi_schema(client: TestClient): "requestBody": { "content": { "multipart/form-data": { - "schema": { - "$ref": "#/components/schemas/Body_create_file_files__post" - } + "schema": IsDict( + { + "allOf": [ + { + "$ref": "#/components/schemas/Body_create_file_files__post" + } + ], + "title": "Body", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "$ref": "#/components/schemas/Body_create_file_files__post" + } + ) } } }, @@ -96,9 +110,22 @@ def test_openapi_schema(client: TestClient): "requestBody": { "content": { "multipart/form-data": { - "schema": { - "$ref": "#/components/schemas/Body_create_upload_file_uploadfile__post" - } + "schema": IsDict( + { + "allOf": [ + { + "$ref": "#/components/schemas/Body_create_upload_file_uploadfile__post" + } + ], + "title": "Body", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "$ref": "#/components/schemas/Body_create_upload_file_uploadfile__post" + } + ) } } }, @@ -127,14 +154,38 @@ def test_openapi_schema(client: TestClient): "title": "Body_create_file_files__post", "type": "object", "properties": { - "file": {"title": "File", "type": "string", "format": "binary"} + "file": IsDict( + { + "title": "File", + "anyOf": [ + {"type": "string", "format": "binary"}, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "File", "type": "string", "format": "binary"} + ) }, }, "Body_create_upload_file_uploadfile__post": { "title": "Body_create_upload_file_uploadfile__post", "type": "object", "properties": { - "file": {"title": "File", "type": "string", "format": "binary"} + "file": IsDict( + { + "title": "File", + "anyOf": [ + {"type": "string", "format": "binary"}, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "File", "type": "string", "format": "binary"} + ) }, }, "HTTPValidationError": { diff --git a/tests/test_tutorial/test_request_files/test_tutorial001_02_py310.py b/tests/test_tutorial/test_request_files/test_tutorial001_02_py310.py index f690d107bae36..a700752a302b9 100644 --- a/tests/test_tutorial/test_request_files/test_tutorial001_02_py310.py +++ b/tests/test_tutorial/test_request_files/test_tutorial001_02_py310.py @@ -1,6 +1,7 @@ from pathlib import Path import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient from ...utils import needs_py310 @@ -55,7 +56,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/files/": { @@ -65,9 +66,22 @@ def test_openapi_schema(client: TestClient): "requestBody": { "content": { "multipart/form-data": { - "schema": { - "$ref": "#/components/schemas/Body_create_file_files__post" - } + "schema": IsDict( + { + "allOf": [ + { + "$ref": "#/components/schemas/Body_create_file_files__post" + } + ], + "title": "Body", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "$ref": "#/components/schemas/Body_create_file_files__post" + } + ) } } }, @@ -96,9 +110,22 @@ def test_openapi_schema(client: TestClient): "requestBody": { "content": { "multipart/form-data": { - "schema": { - "$ref": "#/components/schemas/Body_create_upload_file_uploadfile__post" - } + "schema": IsDict( + { + "allOf": [ + { + "$ref": "#/components/schemas/Body_create_upload_file_uploadfile__post" + } + ], + "title": "Body", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "$ref": "#/components/schemas/Body_create_upload_file_uploadfile__post" + } + ) } } }, @@ -127,14 +154,38 @@ def test_openapi_schema(client: TestClient): "title": "Body_create_file_files__post", "type": "object", "properties": { - "file": {"title": "File", "type": "string", "format": "binary"} + "file": IsDict( + { + "title": "File", + "anyOf": [ + {"type": "string", "format": "binary"}, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "File", "type": "string", "format": "binary"} + ) }, }, "Body_create_upload_file_uploadfile__post": { "title": "Body_create_upload_file_uploadfile__post", "type": "object", "properties": { - "file": {"title": "File", "type": "string", "format": "binary"} + "file": IsDict( + { + "title": "File", + "anyOf": [ + {"type": "string", "format": "binary"}, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "File", "type": "string", "format": "binary"} + ) }, }, "HTTPValidationError": { diff --git a/tests/test_tutorial/test_request_files/test_tutorial001_03.py b/tests/test_tutorial/test_request_files/test_tutorial001_03.py index 4af659a1113a1..f02170814c9eb 100644 --- a/tests/test_tutorial/test_request_files/test_tutorial001_03.py +++ b/tests/test_tutorial/test_request_files/test_tutorial001_03.py @@ -31,7 +31,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/files/": { diff --git a/tests/test_tutorial/test_request_files/test_tutorial001_03_an.py b/tests/test_tutorial/test_request_files/test_tutorial001_03_an.py index 91dbc60b909a5..acfb749ce2acc 100644 --- a/tests/test_tutorial/test_request_files/test_tutorial001_03_an.py +++ b/tests/test_tutorial/test_request_files/test_tutorial001_03_an.py @@ -31,7 +31,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/files/": { diff --git a/tests/test_tutorial/test_request_files/test_tutorial001_03_an_py39.py b/tests/test_tutorial/test_request_files/test_tutorial001_03_an_py39.py index 7c4ad326c4659..36e5faac1815b 100644 --- a/tests/test_tutorial/test_request_files/test_tutorial001_03_an_py39.py +++ b/tests/test_tutorial/test_request_files/test_tutorial001_03_an_py39.py @@ -39,7 +39,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/files/": { diff --git a/tests/test_tutorial/test_request_files/test_tutorial001_an.py b/tests/test_tutorial/test_request_files/test_tutorial001_an.py index 80c288ed6e355..3021eb3c3c98e 100644 --- a/tests/test_tutorial/test_request_files/test_tutorial001_an.py +++ b/tests/test_tutorial/test_request_files/test_tutorial001_an.py @@ -1,31 +1,68 @@ +from dirty_equals import IsDict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url from docs_src.request_files.tutorial001_an import app client = TestClient(app) -file_required = { - "detail": [ - { - "loc": ["body", "file"], - "msg": "field required", - "type": "value_error.missing", - } - ] -} - - def test_post_form_no_body(): response = client.post("/files/") assert response.status_code == 422, response.text - assert response.json() == file_required + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "file"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "file"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) def test_post_body_json(): response = client.post("/files/", json={"file": "Foo"}) assert response.status_code == 422, response.text - assert response.json() == file_required + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "file"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "file"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) def test_post_file(tmp_path): @@ -66,7 +103,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/files/": { diff --git a/tests/test_tutorial/test_request_files/test_tutorial001_an_py39.py b/tests/test_tutorial/test_request_files/test_tutorial001_an_py39.py index 4dc1f752ce697..04f3a4693bfcf 100644 --- a/tests/test_tutorial/test_request_files/test_tutorial001_an_py39.py +++ b/tests/test_tutorial/test_request_files/test_tutorial001_an_py39.py @@ -1,5 +1,7 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url from ...utils import needs_py39 @@ -12,29 +14,64 @@ def get_client(): return client -file_required = { - "detail": [ - { - "loc": ["body", "file"], - "msg": "field required", - "type": "value_error.missing", - } - ] -} - - @needs_py39 def test_post_form_no_body(client: TestClient): response = client.post("/files/") assert response.status_code == 422, response.text - assert response.json() == file_required + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "file"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "file"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) @needs_py39 def test_post_body_json(client: TestClient): response = client.post("/files/", json={"file": "Foo"}) assert response.status_code == 422, response.text - assert response.json() == file_required + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "file"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "file"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) @needs_py39 @@ -76,7 +113,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/files/": { diff --git a/tests/test_tutorial/test_request_files/test_tutorial002.py b/tests/test_tutorial/test_request_files/test_tutorial002.py index 6868be32847a2..ed9680b62b78e 100644 --- a/tests/test_tutorial/test_request_files/test_tutorial002.py +++ b/tests/test_tutorial/test_request_files/test_tutorial002.py @@ -1,31 +1,68 @@ +from dirty_equals import IsDict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url from docs_src.request_files.tutorial002 import app client = TestClient(app) -file_required = { - "detail": [ - { - "loc": ["body", "files"], - "msg": "field required", - "type": "value_error.missing", - } - ] -} - - def test_post_form_no_body(): response = client.post("/files/") assert response.status_code == 422, response.text - assert response.json() == file_required + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "files"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "files"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) def test_post_body_json(): response = client.post("/files/", json={"file": "Foo"}) assert response.status_code == 422, response.text - assert response.json() == file_required + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "files"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "files"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) def test_post_files(tmp_path): @@ -77,7 +114,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/files/": { diff --git a/tests/test_tutorial/test_request_files/test_tutorial002_an.py b/tests/test_tutorial/test_request_files/test_tutorial002_an.py index ca1f62ea39521..ea8c1216c0e42 100644 --- a/tests/test_tutorial/test_request_files/test_tutorial002_an.py +++ b/tests/test_tutorial/test_request_files/test_tutorial002_an.py @@ -1,31 +1,68 @@ +from dirty_equals import IsDict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url from docs_src.request_files.tutorial002_an import app client = TestClient(app) -file_required = { - "detail": [ - { - "loc": ["body", "files"], - "msg": "field required", - "type": "value_error.missing", - } - ] -} - - def test_post_form_no_body(): response = client.post("/files/") assert response.status_code == 422, response.text - assert response.json() == file_required + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "files"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "files"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) def test_post_body_json(): response = client.post("/files/", json={"file": "Foo"}) assert response.status_code == 422, response.text - assert response.json() == file_required + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "files"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "files"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) def test_post_files(tmp_path): @@ -77,7 +114,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/files/": { diff --git a/tests/test_tutorial/test_request_files/test_tutorial002_an_py39.py b/tests/test_tutorial/test_request_files/test_tutorial002_an_py39.py index e593ae75de43b..6d587783677ec 100644 --- a/tests/test_tutorial/test_request_files/test_tutorial002_an_py39.py +++ b/tests/test_tutorial/test_request_files/test_tutorial002_an_py39.py @@ -1,6 +1,8 @@ import pytest +from dirty_equals import IsDict from fastapi import FastAPI from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url from ...utils import needs_py39 @@ -18,29 +20,64 @@ def get_client(app: FastAPI): return client -file_required = { - "detail": [ - { - "loc": ["body", "files"], - "msg": "field required", - "type": "value_error.missing", - } - ] -} - - @needs_py39 def test_post_form_no_body(client: TestClient): response = client.post("/files/") assert response.status_code == 422, response.text - assert response.json() == file_required + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "files"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "files"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) @needs_py39 def test_post_body_json(client: TestClient): response = client.post("/files/", json={"file": "Foo"}) assert response.status_code == 422, response.text - assert response.json() == file_required + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "files"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "files"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) @needs_py39 @@ -96,7 +133,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/files/": { diff --git a/tests/test_tutorial/test_request_files/test_tutorial002_py39.py b/tests/test_tutorial/test_request_files/test_tutorial002_py39.py index bacd25b97e480..2d0445421b54b 100644 --- a/tests/test_tutorial/test_request_files/test_tutorial002_py39.py +++ b/tests/test_tutorial/test_request_files/test_tutorial002_py39.py @@ -1,6 +1,8 @@ import pytest +from dirty_equals import IsDict from fastapi import FastAPI from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url from ...utils import needs_py39 @@ -33,14 +35,60 @@ def get_client(app: FastAPI): def test_post_form_no_body(client: TestClient): response = client.post("/files/") assert response.status_code == 422, response.text - assert response.json() == file_required + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "files"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "files"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) @needs_py39 def test_post_body_json(client: TestClient): response = client.post("/files/", json={"file": "Foo"}) assert response.status_code == 422, response.text - assert response.json() == file_required + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "files"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "files"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) @needs_py39 @@ -96,7 +144,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/files/": { diff --git a/tests/test_tutorial/test_request_files/test_tutorial003.py b/tests/test_tutorial/test_request_files/test_tutorial003.py index e2d69184b9d68..85cd03a590e62 100644 --- a/tests/test_tutorial/test_request_files/test_tutorial003.py +++ b/tests/test_tutorial/test_request_files/test_tutorial003.py @@ -54,7 +54,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/files/": { diff --git a/tests/test_tutorial/test_request_files/test_tutorial003_an.py b/tests/test_tutorial/test_request_files/test_tutorial003_an.py index f199d4d2fd674..0327a2db6c827 100644 --- a/tests/test_tutorial/test_request_files/test_tutorial003_an.py +++ b/tests/test_tutorial/test_request_files/test_tutorial003_an.py @@ -54,7 +54,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/files/": { diff --git a/tests/test_tutorial/test_request_files/test_tutorial003_an_py39.py b/tests/test_tutorial/test_request_files/test_tutorial003_an_py39.py index 51fa8347057ae..3aa68c6215e95 100644 --- a/tests/test_tutorial/test_request_files/test_tutorial003_an_py39.py +++ b/tests/test_tutorial/test_request_files/test_tutorial003_an_py39.py @@ -82,7 +82,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/files/": { diff --git a/tests/test_tutorial/test_request_files/test_tutorial003_py39.py b/tests/test_tutorial/test_request_files/test_tutorial003_py39.py index 32b0289096ff5..238bb39cd0536 100644 --- a/tests/test_tutorial/test_request_files/test_tutorial003_py39.py +++ b/tests/test_tutorial/test_request_files/test_tutorial003_py39.py @@ -82,7 +82,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/files/": { diff --git a/tests/test_tutorial/test_request_forms/test_tutorial001.py b/tests/test_tutorial/test_request_forms/test_tutorial001.py index 721c97fb181e4..805daeb10ff2e 100644 --- a/tests/test_tutorial/test_request_forms/test_tutorial001.py +++ b/tests/test_tutorial/test_request_forms/test_tutorial001.py @@ -1,76 +1,168 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url -from docs_src.request_forms.tutorial001 import app -client = TestClient(app) +@pytest.fixture(name="client") +def get_client(): + from docs_src.request_forms.tutorial001 import app + client = TestClient(app) + return client -password_required = { - "detail": [ + +def test_post_body_form(client: TestClient): + response = client.post("/login/", data={"username": "Foo", "password": "secret"}) + assert response.status_code == 200 + assert response.json() == {"username": "Foo"} + + +def test_post_body_form_no_password(client: TestClient): + response = client.post("/login/", data={"username": "Foo"}) + assert response.status_code == 422 + assert response.json() == IsDict( { - "loc": ["body", "password"], - "msg": "field required", - "type": "value_error.missing", + "detail": [ + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] } - ] -} -username_required = { - "detail": [ + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 { - "loc": ["body", "username"], - "msg": "field required", - "type": "value_error.missing", + "detail": [ + { + "loc": ["body", "password"], + "msg": "field required", + "type": "value_error.missing", + } + ] } - ] -} -username_and_password_required = { - "detail": [ + ) + + +def test_post_body_form_no_username(client: TestClient): + response = client.post("/login/", data={"password": "secret"}) + assert response.status_code == 422 + assert response.json() == IsDict( { - "loc": ["body", "username"], - "msg": "field required", - "type": "value_error.missing", - }, + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 { - "loc": ["body", "password"], - "msg": "field required", - "type": "value_error.missing", - }, - ] -} + "detail": [ + { + "loc": ["body", "username"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) -@pytest.mark.parametrize( - "path,body,expected_status,expected_response", - [ - ( - "/login/", - {"username": "Foo", "password": "secret"}, - 200, - {"username": "Foo"}, - ), - ("/login/", {"username": "Foo"}, 422, password_required), - ("/login/", {"password": "secret"}, 422, username_required), - ("/login/", None, 422, username_and_password_required), - ], -) -def test_post_body_form(path, body, expected_status, expected_response): - response = client.post(path, data=body) - assert response.status_code == expected_status - assert response.json() == expected_response +def test_post_body_form_no_data(client: TestClient): + response = client.post("/login/") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "username"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "password"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) -def test_post_body_json(): +def test_post_body_json(client: TestClient): response = client.post("/login/", json={"username": "Foo", "password": "secret"}) assert response.status_code == 422, response.text - assert response.json() == username_and_password_required + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "username"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "password"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/login/": { diff --git a/tests/test_tutorial/test_request_forms/test_tutorial001_an.py b/tests/test_tutorial/test_request_forms/test_tutorial001_an.py index 6b8abab1934eb..c43a0b6955802 100644 --- a/tests/test_tutorial/test_request_forms/test_tutorial001_an.py +++ b/tests/test_tutorial/test_request_forms/test_tutorial001_an.py @@ -1,76 +1,168 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url -from docs_src.request_forms.tutorial001_an import app -client = TestClient(app) +@pytest.fixture(name="client") +def get_client(): + from docs_src.request_forms.tutorial001_an import app + client = TestClient(app) + return client -password_required = { - "detail": [ + +def test_post_body_form(client: TestClient): + response = client.post("/login/", data={"username": "Foo", "password": "secret"}) + assert response.status_code == 200 + assert response.json() == {"username": "Foo"} + + +def test_post_body_form_no_password(client: TestClient): + response = client.post("/login/", data={"username": "Foo"}) + assert response.status_code == 422 + assert response.json() == IsDict( { - "loc": ["body", "password"], - "msg": "field required", - "type": "value_error.missing", + "detail": [ + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] } - ] -} -username_required = { - "detail": [ + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 { - "loc": ["body", "username"], - "msg": "field required", - "type": "value_error.missing", + "detail": [ + { + "loc": ["body", "password"], + "msg": "field required", + "type": "value_error.missing", + } + ] } - ] -} -username_and_password_required = { - "detail": [ + ) + + +def test_post_body_form_no_username(client: TestClient): + response = client.post("/login/", data={"password": "secret"}) + assert response.status_code == 422 + assert response.json() == IsDict( { - "loc": ["body", "username"], - "msg": "field required", - "type": "value_error.missing", - }, + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 { - "loc": ["body", "password"], - "msg": "field required", - "type": "value_error.missing", - }, - ] -} + "detail": [ + { + "loc": ["body", "username"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) -@pytest.mark.parametrize( - "path,body,expected_status,expected_response", - [ - ( - "/login/", - {"username": "Foo", "password": "secret"}, - 200, - {"username": "Foo"}, - ), - ("/login/", {"username": "Foo"}, 422, password_required), - ("/login/", {"password": "secret"}, 422, username_required), - ("/login/", None, 422, username_and_password_required), - ], -) -def test_post_body_form(path, body, expected_status, expected_response): - response = client.post(path, data=body) - assert response.status_code == expected_status - assert response.json() == expected_response +def test_post_body_form_no_data(client: TestClient): + response = client.post("/login/") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "username"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "password"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) -def test_post_body_json(): +def test_post_body_json(client: TestClient): response = client.post("/login/", json={"username": "Foo", "password": "secret"}) assert response.status_code == 422, response.text - assert response.json() == username_and_password_required + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "username"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "password"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/login/": { diff --git a/tests/test_tutorial/test_request_forms/test_tutorial001_an_py39.py b/tests/test_tutorial/test_request_forms/test_tutorial001_an_py39.py index 5862524add5f2..078b812aa5b28 100644 --- a/tests/test_tutorial/test_request_forms/test_tutorial001_an_py39.py +++ b/tests/test_tutorial/test_request_forms/test_tutorial001_an_py39.py @@ -1,5 +1,7 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url from ...utils import needs_py39 @@ -12,68 +14,155 @@ def get_client(): return client -password_required = { - "detail": [ +@needs_py39 +def test_post_body_form(client: TestClient): + response = client.post("/login/", data={"username": "Foo", "password": "secret"}) + assert response.status_code == 200 + assert response.json() == {"username": "Foo"} + + +@needs_py39 +def test_post_body_form_no_password(client: TestClient): + response = client.post("/login/", data={"username": "Foo"}) + assert response.status_code == 422 + assert response.json() == IsDict( { - "loc": ["body", "password"], - "msg": "field required", - "type": "value_error.missing", + "detail": [ + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] } - ] -} -username_required = { - "detail": [ + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 { - "loc": ["body", "username"], - "msg": "field required", - "type": "value_error.missing", + "detail": [ + { + "loc": ["body", "password"], + "msg": "field required", + "type": "value_error.missing", + } + ] } - ] -} -username_and_password_required = { - "detail": [ + ) + + +@needs_py39 +def test_post_body_form_no_username(client: TestClient): + response = client.post("/login/", data={"password": "secret"}) + assert response.status_code == 422 + assert response.json() == IsDict( { - "loc": ["body", "username"], - "msg": "field required", - "type": "value_error.missing", - }, + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 { - "loc": ["body", "password"], - "msg": "field required", - "type": "value_error.missing", - }, - ] -} + "detail": [ + { + "loc": ["body", "username"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) @needs_py39 -@pytest.mark.parametrize( - "path,body,expected_status,expected_response", - [ - ( - "/login/", - {"username": "Foo", "password": "secret"}, - 200, - {"username": "Foo"}, - ), - ("/login/", {"username": "Foo"}, 422, password_required), - ("/login/", {"password": "secret"}, 422, username_required), - ("/login/", None, 422, username_and_password_required), - ], -) -def test_post_body_form( - path, body, expected_status, expected_response, client: TestClient -): - response = client.post(path, data=body) - assert response.status_code == expected_status - assert response.json() == expected_response +def test_post_body_form_no_data(client: TestClient): + response = client.post("/login/") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "username"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "password"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) @needs_py39 def test_post_body_json(client: TestClient): response = client.post("/login/", json={"username": "Foo", "password": "secret"}) assert response.status_code == 422, response.text - assert response.json() == username_and_password_required + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "username"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "password"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) @needs_py39 @@ -81,7 +170,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/login/": { diff --git a/tests/test_tutorial/test_request_forms_and_files/test_tutorial001.py b/tests/test_tutorial/test_request_forms_and_files/test_tutorial001.py index dcc44cf092e84..cac58639f1fcd 100644 --- a/tests/test_tutorial/test_request_forms_and_files/test_tutorial001.py +++ b/tests/test_tutorial/test_request_forms_and_files/test_tutorial001.py @@ -1,82 +1,171 @@ +import pytest +from dirty_equals import IsDict +from fastapi import FastAPI from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url -from docs_src.request_forms_and_files.tutorial001 import app -client = TestClient(app) +@pytest.fixture(name="app") +def get_app(): + from docs_src.request_forms_and_files.tutorial001 import app + return app -file_required = { - "detail": [ - { - "loc": ["body", "file"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "fileb"], - "msg": "field required", - "type": "value_error.missing", - }, - ] -} - -token_required = { - "detail": [ - { - "loc": ["body", "fileb"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "token"], - "msg": "field required", - "type": "value_error.missing", - }, - ] -} -# {'detail': [, {'loc': ['body', 'token'], 'msg': 'field required', 'type': 'value_error.missing'}]} - -file_and_token_required = { - "detail": [ - { - "loc": ["body", "file"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "fileb"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "token"], - "msg": "field required", - "type": "value_error.missing", - }, - ] -} +@pytest.fixture(name="client") +def get_client(app: FastAPI): + client = TestClient(app) + return client -def test_post_form_no_body(): +def test_post_form_no_body(client: TestClient): response = client.post("/files/") assert response.status_code == 422, response.text - assert response.json() == file_and_token_required + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "file"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "fileb"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "token"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "file"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "fileb"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "token"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) -def test_post_form_no_file(): +def test_post_form_no_file(client: TestClient): response = client.post("/files/", data={"token": "foo"}) assert response.status_code == 422, response.text - assert response.json() == file_required + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "file"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "fileb"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "file"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "fileb"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) -def test_post_body_json(): +def test_post_body_json(client: TestClient): response = client.post("/files/", json={"file": "Foo", "token": "Bar"}) assert response.status_code == 422, response.text - assert response.json() == file_and_token_required + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "file"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "fileb"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "token"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "file"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "fileb"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "token"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) -def test_post_file_no_token(tmp_path): +def test_post_file_no_token(tmp_path, app: FastAPI): path = tmp_path / "test.txt" path.write_bytes(b"<file content>") @@ -84,10 +173,45 @@ def test_post_file_no_token(tmp_path): with path.open("rb") as file: response = client.post("/files/", files={"file": file}) assert response.status_code == 422, response.text - assert response.json() == token_required + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "fileb"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "token"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "fileb"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "token"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) -def test_post_files_and_token(tmp_path): +def test_post_files_and_token(tmp_path, app: FastAPI): patha = tmp_path / "test.txt" pathb = tmp_path / "testb.txt" patha.write_text("<file content>") @@ -108,11 +232,11 @@ def test_post_files_and_token(tmp_path): } -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/files/": { diff --git a/tests/test_tutorial/test_request_forms_and_files/test_tutorial001_an.py b/tests/test_tutorial/test_request_forms_and_files/test_tutorial001_an.py index f11e3698448db..009568048ee40 100644 --- a/tests/test_tutorial/test_request_forms_and_files/test_tutorial001_an.py +++ b/tests/test_tutorial/test_request_forms_and_files/test_tutorial001_an.py @@ -1,82 +1,171 @@ +import pytest +from dirty_equals import IsDict +from fastapi import FastAPI from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url -from docs_src.request_forms_and_files.tutorial001_an import app -client = TestClient(app) +@pytest.fixture(name="app") +def get_app(): + from docs_src.request_forms_and_files.tutorial001_an import app + return app -file_required = { - "detail": [ - { - "loc": ["body", "file"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "fileb"], - "msg": "field required", - "type": "value_error.missing", - }, - ] -} - -token_required = { - "detail": [ - { - "loc": ["body", "fileb"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "token"], - "msg": "field required", - "type": "value_error.missing", - }, - ] -} -# {'detail': [, {'loc': ['body', 'token'], 'msg': 'field required', 'type': 'value_error.missing'}]} - -file_and_token_required = { - "detail": [ - { - "loc": ["body", "file"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "fileb"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "token"], - "msg": "field required", - "type": "value_error.missing", - }, - ] -} +@pytest.fixture(name="client") +def get_client(app: FastAPI): + client = TestClient(app) + return client -def test_post_form_no_body(): +def test_post_form_no_body(client: TestClient): response = client.post("/files/") assert response.status_code == 422, response.text - assert response.json() == file_and_token_required + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "file"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "fileb"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "token"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "file"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "fileb"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "token"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) -def test_post_form_no_file(): +def test_post_form_no_file(client: TestClient): response = client.post("/files/", data={"token": "foo"}) assert response.status_code == 422, response.text - assert response.json() == file_required + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "file"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "fileb"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "file"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "fileb"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) -def test_post_body_json(): +def test_post_body_json(client: TestClient): response = client.post("/files/", json={"file": "Foo", "token": "Bar"}) assert response.status_code == 422, response.text - assert response.json() == file_and_token_required + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "file"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "fileb"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "token"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "file"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "fileb"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "token"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) -def test_post_file_no_token(tmp_path): +def test_post_file_no_token(tmp_path, app: FastAPI): path = tmp_path / "test.txt" path.write_bytes(b"<file content>") @@ -84,10 +173,45 @@ def test_post_file_no_token(tmp_path): with path.open("rb") as file: response = client.post("/files/", files={"file": file}) assert response.status_code == 422, response.text - assert response.json() == token_required + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "fileb"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "token"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "fileb"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "token"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) -def test_post_files_and_token(tmp_path): +def test_post_files_and_token(tmp_path, app: FastAPI): patha = tmp_path / "test.txt" pathb = tmp_path / "testb.txt" patha.write_text("<file content>") @@ -108,11 +232,11 @@ def test_post_files_and_token(tmp_path): } -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/files/": { diff --git a/tests/test_tutorial/test_request_forms_and_files/test_tutorial001_an_py39.py b/tests/test_tutorial/test_request_forms_and_files/test_tutorial001_an_py39.py index 9b5e8681c61c1..3d007e90ba4f9 100644 --- a/tests/test_tutorial/test_request_forms_and_files/test_tutorial001_an_py39.py +++ b/tests/test_tutorial/test_request_forms_and_files/test_tutorial001_an_py39.py @@ -1,6 +1,8 @@ import pytest +from dirty_equals import IsDict from fastapi import FastAPI from fastapi.testclient import TestClient +from fastapi.utils import match_pydantic_error_url from ...utils import needs_py39 @@ -18,78 +20,154 @@ def get_client(app: FastAPI): return client -file_required = { - "detail": [ - { - "loc": ["body", "file"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "fileb"], - "msg": "field required", - "type": "value_error.missing", - }, - ] -} - -token_required = { - "detail": [ - { - "loc": ["body", "fileb"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "token"], - "msg": "field required", - "type": "value_error.missing", - }, - ] -} - -# {'detail': [, {'loc': ['body', 'token'], 'msg': 'field required', 'type': 'value_error.missing'}]} - -file_and_token_required = { - "detail": [ - { - "loc": ["body", "file"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "fileb"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "token"], - "msg": "field required", - "type": "value_error.missing", - }, - ] -} - - @needs_py39 def test_post_form_no_body(client: TestClient): response = client.post("/files/") assert response.status_code == 422, response.text - assert response.json() == file_and_token_required + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "file"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "fileb"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "token"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "file"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "fileb"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "token"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) @needs_py39 def test_post_form_no_file(client: TestClient): response = client.post("/files/", data={"token": "foo"}) assert response.status_code == 422, response.text - assert response.json() == file_required + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "file"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "fileb"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "file"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "fileb"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) @needs_py39 def test_post_body_json(client: TestClient): response = client.post("/files/", json={"file": "Foo", "token": "Bar"}) assert response.status_code == 422, response.text - assert response.json() == file_and_token_required + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "file"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "fileb"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "token"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "file"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "fileb"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "token"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) @needs_py39 @@ -101,7 +179,42 @@ def test_post_file_no_token(tmp_path, app: FastAPI): with path.open("rb") as file: response = client.post("/files/", files={"file": file}) assert response.status_code == 422, response.text - assert response.json() == token_required + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "fileb"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + { + "type": "missing", + "loc": ["body", "token"], + "msg": "Field required", + "input": None, + "url": match_pydantic_error_url("missing"), + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "fileb"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "token"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) @needs_py39 @@ -131,7 +244,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/files/": { diff --git a/tests/test_tutorial/test_response_model/test_tutorial003.py b/tests/test_tutorial/test_response_model/test_tutorial003.py index 4a95cb2b5628f..384c8e0f146d0 100644 --- a/tests/test_tutorial/test_response_model/test_tutorial003.py +++ b/tests/test_tutorial/test_response_model/test_tutorial003.py @@ -1,3 +1,4 @@ +from dirty_equals import IsDict, IsOneOf from fastapi.testclient import TestClient from docs_src.response_model.tutorial003 import app @@ -27,7 +28,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/user/": { @@ -69,7 +70,11 @@ def test_openapi_schema(): "schemas": { "UserOut": { "title": "UserOut", - "required": ["username", "email"], + "required": IsOneOf( + ["username", "email", "full_name"], + # TODO: remove when deprecating Pydantic v1 + ["username", "email"], + ), "type": "object", "properties": { "username": {"title": "Username", "type": "string"}, @@ -78,7 +83,16 @@ def test_openapi_schema(): "type": "string", "format": "email", }, - "full_name": {"title": "Full Name", "type": "string"}, + "full_name": IsDict( + { + "title": "Full Name", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Full Name", "type": "string"} + ), }, }, "UserIn": { @@ -93,7 +107,16 @@ def test_openapi_schema(): "type": "string", "format": "email", }, - "full_name": {"title": "Full Name", "type": "string"}, + "full_name": IsDict( + { + "title": "Full Name", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Full Name", "type": "string"} + ), }, }, "ValidationError": { diff --git a/tests/test_tutorial/test_response_model/test_tutorial003_01.py b/tests/test_tutorial/test_response_model/test_tutorial003_01.py index a055bc6885841..3a6a0b20d9d20 100644 --- a/tests/test_tutorial/test_response_model/test_tutorial003_01.py +++ b/tests/test_tutorial/test_response_model/test_tutorial003_01.py @@ -1,3 +1,4 @@ +from dirty_equals import IsDict, IsOneOf from fastapi.testclient import TestClient from docs_src.response_model.tutorial003_01 import app @@ -27,7 +28,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/user/": { @@ -69,7 +70,11 @@ def test_openapi_schema(): "schemas": { "BaseUser": { "title": "BaseUser", - "required": ["username", "email"], + "required": IsOneOf( + ["username", "email", "full_name"], + # TODO: remove when deprecating Pydantic v1 + ["username", "email"], + ), "type": "object", "properties": { "username": {"title": "Username", "type": "string"}, @@ -78,7 +83,16 @@ def test_openapi_schema(): "type": "string", "format": "email", }, - "full_name": {"title": "Full Name", "type": "string"}, + "full_name": IsDict( + { + "title": "Full Name", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Full Name", "type": "string"} + ), }, }, "HTTPValidationError": { @@ -103,7 +117,16 @@ def test_openapi_schema(): "type": "string", "format": "email", }, - "full_name": {"title": "Full Name", "type": "string"}, + "full_name": IsDict( + { + "title": "Full Name", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Full Name", "type": "string"} + ), "password": {"title": "Password", "type": "string"}, }, }, diff --git a/tests/test_tutorial/test_response_model/test_tutorial003_01_py310.py b/tests/test_tutorial/test_response_model/test_tutorial003_01_py310.py index 8cb4ac208e947..6985b9de6af74 100644 --- a/tests/test_tutorial/test_response_model/test_tutorial003_01_py310.py +++ b/tests/test_tutorial/test_response_model/test_tutorial003_01_py310.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict, IsOneOf from fastapi.testclient import TestClient from ...utils import needs_py310 @@ -36,7 +37,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/user/": { @@ -78,7 +79,11 @@ def test_openapi_schema(client: TestClient): "schemas": { "BaseUser": { "title": "BaseUser", - "required": ["username", "email"], + "required": IsOneOf( + ["username", "email", "full_name"], + # TODO: remove when deprecating Pydantic v1 + ["username", "email"], + ), "type": "object", "properties": { "username": {"title": "Username", "type": "string"}, @@ -87,7 +92,16 @@ def test_openapi_schema(client: TestClient): "type": "string", "format": "email", }, - "full_name": {"title": "Full Name", "type": "string"}, + "full_name": IsDict( + { + "title": "Full Name", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Full Name", "type": "string"} + ), }, }, "HTTPValidationError": { @@ -112,7 +126,16 @@ def test_openapi_schema(client: TestClient): "type": "string", "format": "email", }, - "full_name": {"title": "Full Name", "type": "string"}, + "full_name": IsDict( + { + "title": "Full Name", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Full Name", "type": "string"} + ), "password": {"title": "Password", "type": "string"}, }, }, diff --git a/tests/test_tutorial/test_response_model/test_tutorial003_02.py b/tests/test_tutorial/test_response_model/test_tutorial003_02.py index 6ccb054b8336b..eabd203456583 100644 --- a/tests/test_tutorial/test_response_model/test_tutorial003_02.py +++ b/tests/test_tutorial/test_response_model/test_tutorial003_02.py @@ -21,7 +21,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/portal": { diff --git a/tests/test_tutorial/test_response_model/test_tutorial003_03.py b/tests/test_tutorial/test_response_model/test_tutorial003_03.py index ba4c0f2750619..970ff58450000 100644 --- a/tests/test_tutorial/test_response_model/test_tutorial003_03.py +++ b/tests/test_tutorial/test_response_model/test_tutorial003_03.py @@ -15,7 +15,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/teleport": { diff --git a/tests/test_tutorial/test_response_model/test_tutorial003_05.py b/tests/test_tutorial/test_response_model/test_tutorial003_05.py index d7c232e75118f..c7a39cc748323 100644 --- a/tests/test_tutorial/test_response_model/test_tutorial003_05.py +++ b/tests/test_tutorial/test_response_model/test_tutorial003_05.py @@ -21,7 +21,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/portal": { diff --git a/tests/test_tutorial/test_response_model/test_tutorial003_05_py310.py b/tests/test_tutorial/test_response_model/test_tutorial003_05_py310.py index a89f1dad8b518..f80d62572e29f 100644 --- a/tests/test_tutorial/test_response_model/test_tutorial003_05_py310.py +++ b/tests/test_tutorial/test_response_model/test_tutorial003_05_py310.py @@ -31,7 +31,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/portal": { diff --git a/tests/test_tutorial/test_response_model/test_tutorial003_py310.py b/tests/test_tutorial/test_response_model/test_tutorial003_py310.py index 1f4ec9057f873..3a3aee38aaffa 100644 --- a/tests/test_tutorial/test_response_model/test_tutorial003_py310.py +++ b/tests/test_tutorial/test_response_model/test_tutorial003_py310.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict, IsOneOf from fastapi.testclient import TestClient from ...utils import needs_py310 @@ -36,7 +37,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/user/": { @@ -78,7 +79,11 @@ def test_openapi_schema(client: TestClient): "schemas": { "UserOut": { "title": "UserOut", - "required": ["username", "email"], + "required": IsOneOf( + ["username", "email", "full_name"], + # TODO: remove when deprecating Pydantic v1 + ["username", "email"], + ), "type": "object", "properties": { "username": {"title": "Username", "type": "string"}, @@ -87,7 +92,16 @@ def test_openapi_schema(client: TestClient): "type": "string", "format": "email", }, - "full_name": {"title": "Full Name", "type": "string"}, + "full_name": IsDict( + { + "title": "Full Name", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Full Name", "type": "string"} + ), }, }, "UserIn": { @@ -102,7 +116,16 @@ def test_openapi_schema(client: TestClient): "type": "string", "format": "email", }, - "full_name": {"title": "Full Name", "type": "string"}, + "full_name": IsDict( + { + "title": "Full Name", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Full Name", "type": "string"} + ), }, }, "ValidationError": { diff --git a/tests/test_tutorial/test_response_model/test_tutorial004.py b/tests/test_tutorial/test_response_model/test_tutorial004.py index 8cb7dc9cf412f..e9bde18dd58c3 100644 --- a/tests/test_tutorial/test_response_model/test_tutorial004.py +++ b/tests/test_tutorial/test_response_model/test_tutorial004.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict, IsOneOf from fastapi.testclient import TestClient from docs_src.response_model.tutorial004 import app @@ -36,7 +37,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { @@ -78,12 +79,25 @@ def test_openapi_schema(): "schemas": { "Item": { "title": "Item", - "required": ["name", "price"], + "required": IsOneOf( + ["name", "description", "price", "tax", "tags"], + # TODO: remove when deprecating Pydantic v1 + ["name", "price"], + ), "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, "price": {"title": "Price", "type": "number"}, - "description": {"title": "Description", "type": "string"}, + "description": IsDict( + { + "title": "Description", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Description", "type": "string"} + ), "tax": {"title": "Tax", "type": "number", "default": 10.5}, "tags": { "title": "Tags", diff --git a/tests/test_tutorial/test_response_model/test_tutorial004_py310.py b/tests/test_tutorial/test_response_model/test_tutorial004_py310.py index 2ba8143ba68ae..6f8a3cbea8f09 100644 --- a/tests/test_tutorial/test_response_model/test_tutorial004_py310.py +++ b/tests/test_tutorial/test_response_model/test_tutorial004_py310.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict, IsOneOf from fastapi.testclient import TestClient from ...utils import needs_py310 @@ -44,7 +45,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { @@ -86,12 +87,25 @@ def test_openapi_schema(client: TestClient): "schemas": { "Item": { "title": "Item", - "required": ["name", "price"], + "required": IsOneOf( + ["name", "description", "price", "tax", "tags"], + # TODO: remove when deprecating Pydantic v1 + ["name", "price"], + ), "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, "price": {"title": "Price", "type": "number"}, - "description": {"title": "Description", "type": "string"}, + "description": IsDict( + { + "title": "Description", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Description", "type": "string"} + ), "tax": {"title": "Tax", "type": "number", "default": 10.5}, "tags": { "title": "Tags", diff --git a/tests/test_tutorial/test_response_model/test_tutorial004_py39.py b/tests/test_tutorial/test_response_model/test_tutorial004_py39.py index 97df0a238f59d..cfaa1eba2152f 100644 --- a/tests/test_tutorial/test_response_model/test_tutorial004_py39.py +++ b/tests/test_tutorial/test_response_model/test_tutorial004_py39.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict, IsOneOf from fastapi.testclient import TestClient from ...utils import needs_py39 @@ -44,7 +45,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { @@ -86,12 +87,25 @@ def test_openapi_schema(client: TestClient): "schemas": { "Item": { "title": "Item", - "required": ["name", "price"], + "required": IsOneOf( + ["name", "description", "price", "tax", "tags"], + # TODO: remove when deprecating Pydantic v1 + ["name", "price"], + ), "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, "price": {"title": "Price", "type": "number"}, - "description": {"title": "Description", "type": "string"}, + "description": IsDict( + { + "title": "Description", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Description", "type": "string"} + ), "tax": {"title": "Tax", "type": "number", "default": 10.5}, "tags": { "title": "Tags", diff --git a/tests/test_tutorial/test_response_model/test_tutorial005.py b/tests/test_tutorial/test_response_model/test_tutorial005.py index 76662f7937201..b20864c07ab44 100644 --- a/tests/test_tutorial/test_response_model/test_tutorial005.py +++ b/tests/test_tutorial/test_response_model/test_tutorial005.py @@ -1,3 +1,4 @@ +from dirty_equals import IsDict, IsOneOf from fastapi.testclient import TestClient from docs_src.response_model.tutorial005 import app @@ -25,7 +26,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}/name": { @@ -101,12 +102,25 @@ def test_openapi_schema(): "schemas": { "Item": { "title": "Item", - "required": ["name", "price"], + "required": IsOneOf( + ["name", "description", "price", "tax"], + # TODO: remove when deprecating Pydantic v1 + ["name", "price"], + ), "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, "price": {"title": "Price", "type": "number"}, - "description": {"title": "Description", "type": "string"}, + "description": IsDict( + { + "title": "Description", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Description", "type": "string"} + ), "tax": {"title": "Tax", "type": "number", "default": 10.5}, }, }, diff --git a/tests/test_tutorial/test_response_model/test_tutorial005_py310.py b/tests/test_tutorial/test_response_model/test_tutorial005_py310.py index 1b1cf4175592e..de552c8f22de5 100644 --- a/tests/test_tutorial/test_response_model/test_tutorial005_py310.py +++ b/tests/test_tutorial/test_response_model/test_tutorial005_py310.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict, IsOneOf from fastapi.testclient import TestClient from ...utils import needs_py310 @@ -35,7 +36,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}/name": { @@ -111,12 +112,25 @@ def test_openapi_schema(client: TestClient): "schemas": { "Item": { "title": "Item", - "required": ["name", "price"], + "required": IsOneOf( + ["name", "description", "price", "tax"], + # TODO: remove when deprecating Pydantic v1 + ["name", "price"], + ), "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, "price": {"title": "Price", "type": "number"}, - "description": {"title": "Description", "type": "string"}, + "description": IsDict( + { + "title": "Description", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Description", "type": "string"} + ), "tax": {"title": "Tax", "type": "number", "default": 10.5}, }, }, diff --git a/tests/test_tutorial/test_response_model/test_tutorial006.py b/tests/test_tutorial/test_response_model/test_tutorial006.py index 3a759fde41106..1e47e2eadb05e 100644 --- a/tests/test_tutorial/test_response_model/test_tutorial006.py +++ b/tests/test_tutorial/test_response_model/test_tutorial006.py @@ -1,3 +1,4 @@ +from dirty_equals import IsDict, IsOneOf from fastapi.testclient import TestClient from docs_src.response_model.tutorial006 import app @@ -25,7 +26,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}/name": { @@ -101,12 +102,25 @@ def test_openapi_schema(): "schemas": { "Item": { "title": "Item", - "required": ["name", "price"], + "required": IsOneOf( + ["name", "description", "price", "tax"], + # TODO: remove when deprecating Pydantic v1 + ["name", "price"], + ), "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, "price": {"title": "Price", "type": "number"}, - "description": {"title": "Description", "type": "string"}, + "description": IsDict( + { + "title": "Description", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Description", "type": "string"} + ), "tax": {"title": "Tax", "type": "number", "default": 10.5}, }, }, diff --git a/tests/test_tutorial/test_response_model/test_tutorial006_py310.py b/tests/test_tutorial/test_response_model/test_tutorial006_py310.py index 07e84cc82ad4b..40058b12dea45 100644 --- a/tests/test_tutorial/test_response_model/test_tutorial006_py310.py +++ b/tests/test_tutorial/test_response_model/test_tutorial006_py310.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict, IsOneOf from fastapi.testclient import TestClient from ...utils import needs_py310 @@ -35,7 +36,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}/name": { @@ -111,12 +112,25 @@ def test_openapi_schema(client: TestClient): "schemas": { "Item": { "title": "Item", - "required": ["name", "price"], + "required": IsOneOf( + ["name", "description", "price", "tax"], + # TODO: remove when deprecating Pydantic v1 + ["name", "price"], + ), "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, "price": {"title": "Price", "type": "number"}, - "description": {"title": "Description", "type": "string"}, + "description": IsDict( + { + "title": "Description", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Description", "type": "string"} + ), "tax": {"title": "Tax", "type": "number", "default": 10.5}, }, }, diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial001.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial001.py new file mode 100644 index 0000000000000..98b1873554a82 --- /dev/null +++ b/tests/test_tutorial/test_schema_extra_example/test_tutorial001.py @@ -0,0 +1,133 @@ +import pytest +from fastapi.testclient import TestClient + +from ...utils import needs_pydanticv2 + + +@pytest.fixture(name="client") +def get_client(): + from docs_src.schema_extra_example.tutorial001 import app + + client = TestClient(app) + return client + + +@needs_pydanticv2 +def test_post_body_example(client: TestClient): + response = client.put( + "/items/5", + json={ + "name": "Foo", + "description": "A very nice Item", + "price": 35.4, + "tax": 3.2, + }, + ) + assert response.status_code == 200 + + +@needs_pydanticv2 +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + # insert_assert(response.json()) + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/items/{item_id}": { + "put": { + "summary": "Update Item", + "operationId": "update_item_items__item_id__put", + "parameters": [ + { + "name": "item_id", + "in": "path", + "required": True, + "schema": {"type": "integer", "title": "Item Id"}, + } + ], + "requestBody": { + "required": True, + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Item"} + } + }, + }, + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + } + }, + "components": { + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": {"$ref": "#/components/schemas/ValidationError"}, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "Item": { + "properties": { + "name": {"type": "string", "title": "Name"}, + "description": { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Description", + }, + "price": {"type": "number", "title": "Price"}, + "tax": { + "anyOf": [{"type": "number"}, {"type": "null"}], + "title": "Tax", + }, + }, + "type": "object", + "required": ["name", "price"], + "title": "Item", + "examples": [ + { + "description": "A very nice Item", + "name": "Foo", + "price": 35.4, + "tax": 3.2, + } + ], + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + } + }, + } diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial001_pv1.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial001_pv1.py new file mode 100644 index 0000000000000..3520ef61da7f1 --- /dev/null +++ b/tests/test_tutorial/test_schema_extra_example/test_tutorial001_pv1.py @@ -0,0 +1,127 @@ +import pytest +from fastapi.testclient import TestClient + +from ...utils import needs_pydanticv1 + + +@pytest.fixture(name="client") +def get_client(): + from docs_src.schema_extra_example.tutorial001_pv1 import app + + client = TestClient(app) + return client + + +@needs_pydanticv1 +def test_post_body_example(client: TestClient): + response = client.put( + "/items/5", + json={ + "name": "Foo", + "description": "A very nice Item", + "price": 35.4, + "tax": 3.2, + }, + ) + assert response.status_code == 200 + + +@needs_pydanticv1 +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + # insert_assert(response.json()) + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/items/{item_id}": { + "put": { + "summary": "Update Item", + "operationId": "update_item_items__item_id__put", + "parameters": [ + { + "required": True, + "schema": {"type": "integer", "title": "Item Id"}, + "name": "item_id", + "in": "path", + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Item"} + } + }, + "required": True, + }, + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + } + }, + "components": { + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": {"$ref": "#/components/schemas/ValidationError"}, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "Item": { + "properties": { + "name": {"type": "string", "title": "Name"}, + "description": {"type": "string", "title": "Description"}, + "price": {"type": "number", "title": "Price"}, + "tax": {"type": "number", "title": "Tax"}, + }, + "type": "object", + "required": ["name", "price"], + "title": "Item", + "examples": [ + { + "name": "Foo", + "description": "A very nice Item", + "price": 35.4, + "tax": 3.2, + } + ], + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + } + }, + } diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial001_py310.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial001_py310.py new file mode 100644 index 0000000000000..e63e33cda5d7a --- /dev/null +++ b/tests/test_tutorial/test_schema_extra_example/test_tutorial001_py310.py @@ -0,0 +1,135 @@ +import pytest +from fastapi.testclient import TestClient + +from ...utils import needs_py310, needs_pydanticv2 + + +@pytest.fixture(name="client") +def get_client(): + from docs_src.schema_extra_example.tutorial001_py310 import app + + client = TestClient(app) + return client + + +@needs_py310 +@needs_pydanticv2 +def test_post_body_example(client: TestClient): + response = client.put( + "/items/5", + json={ + "name": "Foo", + "description": "A very nice Item", + "price": 35.4, + "tax": 3.2, + }, + ) + assert response.status_code == 200 + + +@needs_py310 +@needs_pydanticv2 +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + # insert_assert(response.json()) + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/items/{item_id}": { + "put": { + "summary": "Update Item", + "operationId": "update_item_items__item_id__put", + "parameters": [ + { + "name": "item_id", + "in": "path", + "required": True, + "schema": {"type": "integer", "title": "Item Id"}, + } + ], + "requestBody": { + "required": True, + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Item"} + } + }, + }, + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + } + }, + "components": { + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": {"$ref": "#/components/schemas/ValidationError"}, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "Item": { + "properties": { + "name": {"type": "string", "title": "Name"}, + "description": { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Description", + }, + "price": {"type": "number", "title": "Price"}, + "tax": { + "anyOf": [{"type": "number"}, {"type": "null"}], + "title": "Tax", + }, + }, + "type": "object", + "required": ["name", "price"], + "title": "Item", + "examples": [ + { + "description": "A very nice Item", + "name": "Foo", + "price": 35.4, + "tax": 3.2, + } + ], + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + } + }, + } diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial001_py310_pv1.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial001_py310_pv1.py new file mode 100644 index 0000000000000..e036d6b68b0dd --- /dev/null +++ b/tests/test_tutorial/test_schema_extra_example/test_tutorial001_py310_pv1.py @@ -0,0 +1,129 @@ +import pytest +from fastapi.testclient import TestClient + +from ...utils import needs_py310, needs_pydanticv1 + + +@pytest.fixture(name="client") +def get_client(): + from docs_src.schema_extra_example.tutorial001_py310_pv1 import app + + client = TestClient(app) + return client + + +@needs_py310 +@needs_pydanticv1 +def test_post_body_example(client: TestClient): + response = client.put( + "/items/5", + json={ + "name": "Foo", + "description": "A very nice Item", + "price": 35.4, + "tax": 3.2, + }, + ) + assert response.status_code == 200 + + +@needs_py310 +@needs_pydanticv1 +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + # insert_assert(response.json()) + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/items/{item_id}": { + "put": { + "summary": "Update Item", + "operationId": "update_item_items__item_id__put", + "parameters": [ + { + "required": True, + "schema": {"type": "integer", "title": "Item Id"}, + "name": "item_id", + "in": "path", + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Item"} + } + }, + "required": True, + }, + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + } + }, + "components": { + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": {"$ref": "#/components/schemas/ValidationError"}, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "Item": { + "properties": { + "name": {"type": "string", "title": "Name"}, + "description": {"type": "string", "title": "Description"}, + "price": {"type": "number", "title": "Price"}, + "tax": {"type": "number", "title": "Tax"}, + }, + "type": "object", + "required": ["name", "price"], + "title": "Item", + "examples": [ + { + "name": "Foo", + "description": "A very nice Item", + "price": 35.4, + "tax": 3.2, + } + ], + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + } + }, + } diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial004.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial004.py index 784517d69ed9e..eac0d1e29bbfd 100644 --- a/tests/test_tutorial/test_schema_extra_example/test_tutorial004.py +++ b/tests/test_tutorial/test_schema_extra_example/test_tutorial004.py @@ -1,3 +1,4 @@ +from dirty_equals import IsDict from fastapi.testclient import TestClient from docs_src.schema_extra_example.tutorial004 import app @@ -23,7 +24,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { @@ -41,31 +42,46 @@ def test_openapi_schema(): "requestBody": { "content": { "application/json": { - "schema": {"$ref": "#/components/schemas/Item"}, - "examples": { - "normal": { - "summary": "A normal example", - "description": "A **normal** item works correctly.", - "value": { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - }, - "converted": { - "summary": "An example with converted data", - "description": "FastAPI can convert price `strings` to actual `numbers` automatically", - "value": {"name": "Bar", "price": "35.4"}, - }, - "invalid": { - "summary": "Invalid data is rejected with an error", - "value": { - "name": "Baz", - "price": "thirty five point four", - }, - }, - }, + "schema": IsDict( + { + "$ref": "#/components/schemas/Item", + "examples": [ + { + "name": "Foo", + "description": "A very nice Item", + "price": 35.4, + "tax": 3.2, + }, + {"name": "Bar", "price": "35.4"}, + { + "name": "Baz", + "price": "thirty five point four", + }, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "allOf": [ + {"$ref": "#/components/schemas/Item"} + ], + "title": "Item", + "examples": [ + { + "name": "Foo", + "description": "A very nice Item", + "price": 35.4, + "tax": 3.2, + }, + {"name": "Bar", "price": "35.4"}, + { + "name": "Baz", + "price": "thirty five point four", + }, + ], + } + ) } }, "required": True, @@ -108,9 +124,27 @@ def test_openapi_schema(): "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, - "description": {"title": "Description", "type": "string"}, + "description": IsDict( + { + "title": "Description", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Description", "type": "string"} + ), "price": {"title": "Price", "type": "number"}, - "tax": {"title": "Tax", "type": "number"}, + "tax": IsDict( + { + "title": "Tax", + "anyOf": [{"type": "number"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Tax", "type": "number"} + ), }, }, "ValidationError": { diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial004_an.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial004_an.py index 222a4edfe8d5a..a9cecd098308d 100644 --- a/tests/test_tutorial/test_schema_extra_example/test_tutorial004_an.py +++ b/tests/test_tutorial/test_schema_extra_example/test_tutorial004_an.py @@ -1,3 +1,4 @@ +from dirty_equals import IsDict from fastapi.testclient import TestClient from docs_src.schema_extra_example.tutorial004_an import app @@ -23,7 +24,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { @@ -41,31 +42,46 @@ def test_openapi_schema(): "requestBody": { "content": { "application/json": { - "schema": {"$ref": "#/components/schemas/Item"}, - "examples": { - "normal": { - "summary": "A normal example", - "description": "A **normal** item works correctly.", - "value": { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - }, - "converted": { - "summary": "An example with converted data", - "description": "FastAPI can convert price `strings` to actual `numbers` automatically", - "value": {"name": "Bar", "price": "35.4"}, - }, - "invalid": { - "summary": "Invalid data is rejected with an error", - "value": { - "name": "Baz", - "price": "thirty five point four", - }, - }, - }, + "schema": IsDict( + { + "$ref": "#/components/schemas/Item", + "examples": [ + { + "name": "Foo", + "description": "A very nice Item", + "price": 35.4, + "tax": 3.2, + }, + {"name": "Bar", "price": "35.4"}, + { + "name": "Baz", + "price": "thirty five point four", + }, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "allOf": [ + {"$ref": "#/components/schemas/Item"} + ], + "title": "Item", + "examples": [ + { + "name": "Foo", + "description": "A very nice Item", + "price": 35.4, + "tax": 3.2, + }, + {"name": "Bar", "price": "35.4"}, + { + "name": "Baz", + "price": "thirty five point four", + }, + ], + } + ) } }, "required": True, @@ -108,9 +124,27 @@ def test_openapi_schema(): "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, - "description": {"title": "Description", "type": "string"}, + "description": IsDict( + { + "title": "Description", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Description", "type": "string"} + ), "price": {"title": "Price", "type": "number"}, - "tax": {"title": "Tax", "type": "number"}, + "tax": IsDict( + { + "title": "Tax", + "anyOf": [{"type": "number"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Tax", "type": "number"} + ), }, }, "ValidationError": { diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial004_an_py310.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial004_an_py310.py index 1eacd640af6cd..b6a7355996289 100644 --- a/tests/test_tutorial/test_schema_extra_example/test_tutorial004_an_py310.py +++ b/tests/test_tutorial/test_schema_extra_example/test_tutorial004_an_py310.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient from ...utils import needs_py310 @@ -32,7 +33,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { @@ -50,31 +51,46 @@ def test_openapi_schema(client: TestClient): "requestBody": { "content": { "application/json": { - "schema": {"$ref": "#/components/schemas/Item"}, - "examples": { - "normal": { - "summary": "A normal example", - "description": "A **normal** item works correctly.", - "value": { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - }, - "converted": { - "summary": "An example with converted data", - "description": "FastAPI can convert price `strings` to actual `numbers` automatically", - "value": {"name": "Bar", "price": "35.4"}, - }, - "invalid": { - "summary": "Invalid data is rejected with an error", - "value": { - "name": "Baz", - "price": "thirty five point four", - }, - }, - }, + "schema": IsDict( + { + "$ref": "#/components/schemas/Item", + "examples": [ + { + "name": "Foo", + "description": "A very nice Item", + "price": 35.4, + "tax": 3.2, + }, + {"name": "Bar", "price": "35.4"}, + { + "name": "Baz", + "price": "thirty five point four", + }, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "allOf": [ + {"$ref": "#/components/schemas/Item"} + ], + "title": "Item", + "examples": [ + { + "name": "Foo", + "description": "A very nice Item", + "price": 35.4, + "tax": 3.2, + }, + {"name": "Bar", "price": "35.4"}, + { + "name": "Baz", + "price": "thirty five point four", + }, + ], + } + ) } }, "required": True, @@ -117,9 +133,27 @@ def test_openapi_schema(client: TestClient): "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, - "description": {"title": "Description", "type": "string"}, + "description": IsDict( + { + "title": "Description", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Description", "type": "string"} + ), "price": {"title": "Price", "type": "number"}, - "tax": {"title": "Tax", "type": "number"}, + "tax": IsDict( + { + "title": "Tax", + "anyOf": [{"type": "number"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Tax", "type": "number"} + ), }, }, "ValidationError": { diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial004_an_py39.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial004_an_py39.py index 632f2cbe0bc8c..2493194a00116 100644 --- a/tests/test_tutorial/test_schema_extra_example/test_tutorial004_an_py39.py +++ b/tests/test_tutorial/test_schema_extra_example/test_tutorial004_an_py39.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient from ...utils import needs_py39 @@ -32,7 +33,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { @@ -50,31 +51,46 @@ def test_openapi_schema(client: TestClient): "requestBody": { "content": { "application/json": { - "schema": {"$ref": "#/components/schemas/Item"}, - "examples": { - "normal": { - "summary": "A normal example", - "description": "A **normal** item works correctly.", - "value": { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - }, - "converted": { - "summary": "An example with converted data", - "description": "FastAPI can convert price `strings` to actual `numbers` automatically", - "value": {"name": "Bar", "price": "35.4"}, - }, - "invalid": { - "summary": "Invalid data is rejected with an error", - "value": { - "name": "Baz", - "price": "thirty five point four", - }, - }, - }, + "schema": IsDict( + { + "$ref": "#/components/schemas/Item", + "examples": [ + { + "name": "Foo", + "description": "A very nice Item", + "price": 35.4, + "tax": 3.2, + }, + {"name": "Bar", "price": "35.4"}, + { + "name": "Baz", + "price": "thirty five point four", + }, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "allOf": [ + {"$ref": "#/components/schemas/Item"} + ], + "title": "Item", + "examples": [ + { + "name": "Foo", + "description": "A very nice Item", + "price": 35.4, + "tax": 3.2, + }, + {"name": "Bar", "price": "35.4"}, + { + "name": "Baz", + "price": "thirty five point four", + }, + ], + } + ) } }, "required": True, @@ -117,9 +133,27 @@ def test_openapi_schema(client: TestClient): "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, - "description": {"title": "Description", "type": "string"}, + "description": IsDict( + { + "title": "Description", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Description", "type": "string"} + ), "price": {"title": "Price", "type": "number"}, - "tax": {"title": "Tax", "type": "number"}, + "tax": IsDict( + { + "title": "Tax", + "anyOf": [{"type": "number"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Tax", "type": "number"} + ), }, }, "ValidationError": { diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial004_py310.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial004_py310.py index c99cb75c89beb..15f54bd5a61d3 100644 --- a/tests/test_tutorial/test_schema_extra_example/test_tutorial004_py310.py +++ b/tests/test_tutorial/test_schema_extra_example/test_tutorial004_py310.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient from ...utils import needs_py310 @@ -32,7 +33,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { @@ -50,31 +51,46 @@ def test_openapi_schema(client: TestClient): "requestBody": { "content": { "application/json": { - "schema": {"$ref": "#/components/schemas/Item"}, - "examples": { - "normal": { - "summary": "A normal example", - "description": "A **normal** item works correctly.", - "value": { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - }, - "converted": { - "summary": "An example with converted data", - "description": "FastAPI can convert price `strings` to actual `numbers` automatically", - "value": {"name": "Bar", "price": "35.4"}, - }, - "invalid": { - "summary": "Invalid data is rejected with an error", - "value": { - "name": "Baz", - "price": "thirty five point four", - }, - }, - }, + "schema": IsDict( + { + "$ref": "#/components/schemas/Item", + "examples": [ + { + "name": "Foo", + "description": "A very nice Item", + "price": 35.4, + "tax": 3.2, + }, + {"name": "Bar", "price": "35.4"}, + { + "name": "Baz", + "price": "thirty five point four", + }, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "allOf": [ + {"$ref": "#/components/schemas/Item"} + ], + "title": "Item", + "examples": [ + { + "name": "Foo", + "description": "A very nice Item", + "price": 35.4, + "tax": 3.2, + }, + {"name": "Bar", "price": "35.4"}, + { + "name": "Baz", + "price": "thirty five point four", + }, + ], + } + ) } }, "required": True, @@ -117,9 +133,27 @@ def test_openapi_schema(client: TestClient): "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, - "description": {"title": "Description", "type": "string"}, + "description": IsDict( + { + "title": "Description", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Description", "type": "string"} + ), "price": {"title": "Price", "type": "number"}, - "tax": {"title": "Tax", "type": "number"}, + "tax": IsDict( + { + "title": "Tax", + "anyOf": [{"type": "number"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Tax", "type": "number"} + ), }, }, "ValidationError": { diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial005.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial005.py new file mode 100644 index 0000000000000..94a40ed5a3a9a --- /dev/null +++ b/tests/test_tutorial/test_schema_extra_example/test_tutorial005.py @@ -0,0 +1,166 @@ +import pytest +from dirty_equals import IsDict +from fastapi.testclient import TestClient + + +@pytest.fixture(name="client") +def get_client(): + from docs_src.schema_extra_example.tutorial005 import app + + client = TestClient(app) + return client + + +def test_post_body_example(client: TestClient): + response = client.put( + "/items/5", + json={ + "name": "Foo", + "description": "A very nice Item", + "price": 35.4, + "tax": 3.2, + }, + ) + assert response.status_code == 200 + + +def test_openapi_schema(client: TestClient) -> None: + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/items/{item_id}": { + "put": { + "summary": "Update Item", + "operationId": "update_item_items__item_id__put", + "parameters": [ + { + "required": True, + "schema": {"title": "Item Id", "type": "integer"}, + "name": "item_id", + "in": "path", + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": IsDict({"$ref": "#/components/schemas/Item"}) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "allOf": [ + {"$ref": "#/components/schemas/Item"} + ], + "title": "Item", + } + ), + "examples": { + "normal": { + "summary": "A normal example", + "description": "A **normal** item works correctly.", + "value": { + "name": "Foo", + "description": "A very nice Item", + "price": 35.4, + "tax": 3.2, + }, + }, + "converted": { + "summary": "An example with converted data", + "description": "FastAPI can convert price `strings` to actual `numbers` automatically", + "value": {"name": "Bar", "price": "35.4"}, + }, + "invalid": { + "summary": "Invalid data is rejected with an error", + "value": { + "name": "Baz", + "price": "thirty five point four", + }, + }, + }, + } + }, + "required": True, + }, + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + } + }, + "components": { + "schemas": { + "HTTPValidationError": { + "title": "HTTPValidationError", + "type": "object", + "properties": { + "detail": { + "title": "Detail", + "type": "array", + "items": {"$ref": "#/components/schemas/ValidationError"}, + } + }, + }, + "Item": { + "title": "Item", + "required": ["name", "price"], + "type": "object", + "properties": { + "name": {"title": "Name", "type": "string"}, + "description": IsDict( + { + "title": "Description", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Description", "type": "string"} + ), + "price": {"title": "Price", "type": "number"}, + "tax": IsDict( + { + "title": "Tax", + "anyOf": [{"type": "number"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Tax", "type": "number"} + ), + }, + }, + "ValidationError": { + "title": "ValidationError", + "required": ["loc", "msg", "type"], + "type": "object", + "properties": { + "loc": { + "title": "Location", + "type": "array", + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + }, + "msg": {"title": "Message", "type": "string"}, + "type": {"title": "Error Type", "type": "string"}, + }, + }, + } + }, + } diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial005_an.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial005_an.py new file mode 100644 index 0000000000000..da92f98f6ae7f --- /dev/null +++ b/tests/test_tutorial/test_schema_extra_example/test_tutorial005_an.py @@ -0,0 +1,166 @@ +import pytest +from dirty_equals import IsDict +from fastapi.testclient import TestClient + + +@pytest.fixture(name="client") +def get_client(): + from docs_src.schema_extra_example.tutorial005_an import app + + client = TestClient(app) + return client + + +def test_post_body_example(client: TestClient): + response = client.put( + "/items/5", + json={ + "name": "Foo", + "description": "A very nice Item", + "price": 35.4, + "tax": 3.2, + }, + ) + assert response.status_code == 200 + + +def test_openapi_schema(client: TestClient) -> None: + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/items/{item_id}": { + "put": { + "summary": "Update Item", + "operationId": "update_item_items__item_id__put", + "parameters": [ + { + "required": True, + "schema": {"title": "Item Id", "type": "integer"}, + "name": "item_id", + "in": "path", + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": IsDict({"$ref": "#/components/schemas/Item"}) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "allOf": [ + {"$ref": "#/components/schemas/Item"} + ], + "title": "Item", + } + ), + "examples": { + "normal": { + "summary": "A normal example", + "description": "A **normal** item works correctly.", + "value": { + "name": "Foo", + "description": "A very nice Item", + "price": 35.4, + "tax": 3.2, + }, + }, + "converted": { + "summary": "An example with converted data", + "description": "FastAPI can convert price `strings` to actual `numbers` automatically", + "value": {"name": "Bar", "price": "35.4"}, + }, + "invalid": { + "summary": "Invalid data is rejected with an error", + "value": { + "name": "Baz", + "price": "thirty five point four", + }, + }, + }, + } + }, + "required": True, + }, + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + } + }, + "components": { + "schemas": { + "HTTPValidationError": { + "title": "HTTPValidationError", + "type": "object", + "properties": { + "detail": { + "title": "Detail", + "type": "array", + "items": {"$ref": "#/components/schemas/ValidationError"}, + } + }, + }, + "Item": { + "title": "Item", + "required": ["name", "price"], + "type": "object", + "properties": { + "name": {"title": "Name", "type": "string"}, + "description": IsDict( + { + "title": "Description", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Description", "type": "string"} + ), + "price": {"title": "Price", "type": "number"}, + "tax": IsDict( + { + "title": "Tax", + "anyOf": [{"type": "number"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Tax", "type": "number"} + ), + }, + }, + "ValidationError": { + "title": "ValidationError", + "required": ["loc", "msg", "type"], + "type": "object", + "properties": { + "loc": { + "title": "Location", + "type": "array", + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + }, + "msg": {"title": "Message", "type": "string"}, + "type": {"title": "Error Type", "type": "string"}, + }, + }, + } + }, + } diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial005_an_py310.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial005_an_py310.py new file mode 100644 index 0000000000000..9109cb14efea0 --- /dev/null +++ b/tests/test_tutorial/test_schema_extra_example/test_tutorial005_an_py310.py @@ -0,0 +1,170 @@ +import pytest +from dirty_equals import IsDict +from fastapi.testclient import TestClient + +from ...utils import needs_py310 + + +@pytest.fixture(name="client") +def get_client(): + from docs_src.schema_extra_example.tutorial005_an_py310 import app + + client = TestClient(app) + return client + + +@needs_py310 +def test_post_body_example(client: TestClient): + response = client.put( + "/items/5", + json={ + "name": "Foo", + "description": "A very nice Item", + "price": 35.4, + "tax": 3.2, + }, + ) + assert response.status_code == 200 + + +@needs_py310 +def test_openapi_schema(client: TestClient) -> None: + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/items/{item_id}": { + "put": { + "summary": "Update Item", + "operationId": "update_item_items__item_id__put", + "parameters": [ + { + "required": True, + "schema": {"title": "Item Id", "type": "integer"}, + "name": "item_id", + "in": "path", + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": IsDict({"$ref": "#/components/schemas/Item"}) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "allOf": [ + {"$ref": "#/components/schemas/Item"} + ], + "title": "Item", + } + ), + "examples": { + "normal": { + "summary": "A normal example", + "description": "A **normal** item works correctly.", + "value": { + "name": "Foo", + "description": "A very nice Item", + "price": 35.4, + "tax": 3.2, + }, + }, + "converted": { + "summary": "An example with converted data", + "description": "FastAPI can convert price `strings` to actual `numbers` automatically", + "value": {"name": "Bar", "price": "35.4"}, + }, + "invalid": { + "summary": "Invalid data is rejected with an error", + "value": { + "name": "Baz", + "price": "thirty five point four", + }, + }, + }, + } + }, + "required": True, + }, + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + } + }, + "components": { + "schemas": { + "HTTPValidationError": { + "title": "HTTPValidationError", + "type": "object", + "properties": { + "detail": { + "title": "Detail", + "type": "array", + "items": {"$ref": "#/components/schemas/ValidationError"}, + } + }, + }, + "Item": { + "title": "Item", + "required": ["name", "price"], + "type": "object", + "properties": { + "name": {"title": "Name", "type": "string"}, + "description": IsDict( + { + "title": "Description", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Description", "type": "string"} + ), + "price": {"title": "Price", "type": "number"}, + "tax": IsDict( + { + "title": "Tax", + "anyOf": [{"type": "number"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Tax", "type": "number"} + ), + }, + }, + "ValidationError": { + "title": "ValidationError", + "required": ["loc", "msg", "type"], + "type": "object", + "properties": { + "loc": { + "title": "Location", + "type": "array", + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + }, + "msg": {"title": "Message", "type": "string"}, + "type": {"title": "Error Type", "type": "string"}, + }, + }, + } + }, + } diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial005_an_py39.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial005_an_py39.py new file mode 100644 index 0000000000000..fd4ec0575e60c --- /dev/null +++ b/tests/test_tutorial/test_schema_extra_example/test_tutorial005_an_py39.py @@ -0,0 +1,170 @@ +import pytest +from dirty_equals import IsDict +from fastapi.testclient import TestClient + +from ...utils import needs_py39 + + +@pytest.fixture(name="client") +def get_client(): + from docs_src.schema_extra_example.tutorial005_an_py39 import app + + client = TestClient(app) + return client + + +@needs_py39 +def test_post_body_example(client: TestClient): + response = client.put( + "/items/5", + json={ + "name": "Foo", + "description": "A very nice Item", + "price": 35.4, + "tax": 3.2, + }, + ) + assert response.status_code == 200 + + +@needs_py39 +def test_openapi_schema(client: TestClient) -> None: + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/items/{item_id}": { + "put": { + "summary": "Update Item", + "operationId": "update_item_items__item_id__put", + "parameters": [ + { + "required": True, + "schema": {"title": "Item Id", "type": "integer"}, + "name": "item_id", + "in": "path", + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": IsDict({"$ref": "#/components/schemas/Item"}) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "allOf": [ + {"$ref": "#/components/schemas/Item"} + ], + "title": "Item", + } + ), + "examples": { + "normal": { + "summary": "A normal example", + "description": "A **normal** item works correctly.", + "value": { + "name": "Foo", + "description": "A very nice Item", + "price": 35.4, + "tax": 3.2, + }, + }, + "converted": { + "summary": "An example with converted data", + "description": "FastAPI can convert price `strings` to actual `numbers` automatically", + "value": {"name": "Bar", "price": "35.4"}, + }, + "invalid": { + "summary": "Invalid data is rejected with an error", + "value": { + "name": "Baz", + "price": "thirty five point four", + }, + }, + }, + } + }, + "required": True, + }, + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + } + }, + "components": { + "schemas": { + "HTTPValidationError": { + "title": "HTTPValidationError", + "type": "object", + "properties": { + "detail": { + "title": "Detail", + "type": "array", + "items": {"$ref": "#/components/schemas/ValidationError"}, + } + }, + }, + "Item": { + "title": "Item", + "required": ["name", "price"], + "type": "object", + "properties": { + "name": {"title": "Name", "type": "string"}, + "description": IsDict( + { + "title": "Description", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Description", "type": "string"} + ), + "price": {"title": "Price", "type": "number"}, + "tax": IsDict( + { + "title": "Tax", + "anyOf": [{"type": "number"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Tax", "type": "number"} + ), + }, + }, + "ValidationError": { + "title": "ValidationError", + "required": ["loc", "msg", "type"], + "type": "object", + "properties": { + "loc": { + "title": "Location", + "type": "array", + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + }, + "msg": {"title": "Message", "type": "string"}, + "type": {"title": "Error Type", "type": "string"}, + }, + }, + } + }, + } diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial005_py310.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial005_py310.py new file mode 100644 index 0000000000000..05df534223bf9 --- /dev/null +++ b/tests/test_tutorial/test_schema_extra_example/test_tutorial005_py310.py @@ -0,0 +1,170 @@ +import pytest +from dirty_equals import IsDict +from fastapi.testclient import TestClient + +from ...utils import needs_py310 + + +@pytest.fixture(name="client") +def get_client(): + from docs_src.schema_extra_example.tutorial005_py310 import app + + client = TestClient(app) + return client + + +@needs_py310 +def test_post_body_example(client: TestClient): + response = client.put( + "/items/5", + json={ + "name": "Foo", + "description": "A very nice Item", + "price": 35.4, + "tax": 3.2, + }, + ) + assert response.status_code == 200 + + +@needs_py310 +def test_openapi_schema(client: TestClient) -> None: + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/items/{item_id}": { + "put": { + "summary": "Update Item", + "operationId": "update_item_items__item_id__put", + "parameters": [ + { + "required": True, + "schema": {"title": "Item Id", "type": "integer"}, + "name": "item_id", + "in": "path", + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": IsDict({"$ref": "#/components/schemas/Item"}) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "allOf": [ + {"$ref": "#/components/schemas/Item"} + ], + "title": "Item", + } + ), + "examples": { + "normal": { + "summary": "A normal example", + "description": "A **normal** item works correctly.", + "value": { + "name": "Foo", + "description": "A very nice Item", + "price": 35.4, + "tax": 3.2, + }, + }, + "converted": { + "summary": "An example with converted data", + "description": "FastAPI can convert price `strings` to actual `numbers` automatically", + "value": {"name": "Bar", "price": "35.4"}, + }, + "invalid": { + "summary": "Invalid data is rejected with an error", + "value": { + "name": "Baz", + "price": "thirty five point four", + }, + }, + }, + } + }, + "required": True, + }, + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + } + }, + "components": { + "schemas": { + "HTTPValidationError": { + "title": "HTTPValidationError", + "type": "object", + "properties": { + "detail": { + "title": "Detail", + "type": "array", + "items": {"$ref": "#/components/schemas/ValidationError"}, + } + }, + }, + "Item": { + "title": "Item", + "required": ["name", "price"], + "type": "object", + "properties": { + "name": {"title": "Name", "type": "string"}, + "description": IsDict( + { + "title": "Description", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Description", "type": "string"} + ), + "price": {"title": "Price", "type": "number"}, + "tax": IsDict( + { + "title": "Tax", + "anyOf": [{"type": "number"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Tax", "type": "number"} + ), + }, + }, + "ValidationError": { + "title": "ValidationError", + "required": ["loc", "msg", "type"], + "type": "object", + "properties": { + "loc": { + "title": "Location", + "type": "array", + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + }, + "msg": {"title": "Message", "type": "string"}, + "type": {"title": "Error Type", "type": "string"}, + }, + }, + } + }, + } diff --git a/tests/test_tutorial/test_security/test_tutorial001.py b/tests/test_tutorial/test_security/test_tutorial001.py index a7f55b78b292e..417bed8f7a69a 100644 --- a/tests/test_tutorial/test_security/test_tutorial001.py +++ b/tests/test_tutorial/test_security/test_tutorial001.py @@ -29,7 +29,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { diff --git a/tests/test_tutorial/test_security/test_tutorial001_an.py b/tests/test_tutorial/test_security/test_tutorial001_an.py index fc48703aa020c..59460da7ff4f1 100644 --- a/tests/test_tutorial/test_security/test_tutorial001_an.py +++ b/tests/test_tutorial/test_security/test_tutorial001_an.py @@ -29,7 +29,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { diff --git a/tests/test_tutorial/test_security/test_tutorial001_an_py39.py b/tests/test_tutorial/test_security/test_tutorial001_an_py39.py index 345e0be0f3fb4..d8e71277367fe 100644 --- a/tests/test_tutorial/test_security/test_tutorial001_an_py39.py +++ b/tests/test_tutorial/test_security/test_tutorial001_an_py39.py @@ -40,7 +40,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { diff --git a/tests/test_tutorial/test_security/test_tutorial003.py b/tests/test_tutorial/test_security/test_tutorial003.py index c10f928eb4800..18d4680f627f6 100644 --- a/tests/test_tutorial/test_security/test_tutorial003.py +++ b/tests/test_tutorial/test_security/test_tutorial003.py @@ -1,3 +1,4 @@ +from dirty_equals import IsDict from fastapi.testclient import TestClient from docs_src.security.tutorial003 import app @@ -70,7 +71,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/token": { @@ -126,16 +127,46 @@ def test_openapi_schema(): "required": ["username", "password"], "type": "object", "properties": { - "grant_type": { - "title": "Grant Type", - "pattern": "password", - "type": "string", - }, + "grant_type": IsDict( + { + "title": "Grant Type", + "anyOf": [ + {"pattern": "password", "type": "string"}, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "Grant Type", + "pattern": "password", + "type": "string", + } + ), "username": {"title": "Username", "type": "string"}, "password": {"title": "Password", "type": "string"}, "scope": {"title": "Scope", "type": "string", "default": ""}, - "client_id": {"title": "Client Id", "type": "string"}, - "client_secret": {"title": "Client Secret", "type": "string"}, + "client_id": IsDict( + { + "title": "Client Id", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Client Id", "type": "string"} + ), + "client_secret": IsDict( + { + "title": "Client Secret", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Client Secret", "type": "string"} + ), }, }, "ValidationError": { diff --git a/tests/test_tutorial/test_security/test_tutorial003_an.py b/tests/test_tutorial/test_security/test_tutorial003_an.py index 41872fda03e1c..a8f64d0c60dbc 100644 --- a/tests/test_tutorial/test_security/test_tutorial003_an.py +++ b/tests/test_tutorial/test_security/test_tutorial003_an.py @@ -1,3 +1,4 @@ +from dirty_equals import IsDict from fastapi.testclient import TestClient from docs_src.security.tutorial003_an import app @@ -70,7 +71,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/token": { @@ -126,16 +127,46 @@ def test_openapi_schema(): "required": ["username", "password"], "type": "object", "properties": { - "grant_type": { - "title": "Grant Type", - "pattern": "password", - "type": "string", - }, + "grant_type": IsDict( + { + "title": "Grant Type", + "anyOf": [ + {"pattern": "password", "type": "string"}, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "Grant Type", + "pattern": "password", + "type": "string", + } + ), "username": {"title": "Username", "type": "string"}, "password": {"title": "Password", "type": "string"}, "scope": {"title": "Scope", "type": "string", "default": ""}, - "client_id": {"title": "Client Id", "type": "string"}, - "client_secret": {"title": "Client Secret", "type": "string"}, + "client_id": IsDict( + { + "title": "Client Id", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Client Id", "type": "string"} + ), + "client_secret": IsDict( + { + "title": "Client Secret", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Client Secret", "type": "string"} + ), }, }, "ValidationError": { diff --git a/tests/test_tutorial/test_security/test_tutorial003_an_py310.py b/tests/test_tutorial/test_security/test_tutorial003_an_py310.py index 02bd748c8cf3d..7cbbcee2f5c01 100644 --- a/tests/test_tutorial/test_security/test_tutorial003_an_py310.py +++ b/tests/test_tutorial/test_security/test_tutorial003_an_py310.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient from ...utils import needs_py310 @@ -86,7 +87,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/token": { @@ -142,16 +143,46 @@ def test_openapi_schema(client: TestClient): "required": ["username", "password"], "type": "object", "properties": { - "grant_type": { - "title": "Grant Type", - "pattern": "password", - "type": "string", - }, + "grant_type": IsDict( + { + "title": "Grant Type", + "anyOf": [ + {"pattern": "password", "type": "string"}, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "Grant Type", + "pattern": "password", + "type": "string", + } + ), "username": {"title": "Username", "type": "string"}, "password": {"title": "Password", "type": "string"}, "scope": {"title": "Scope", "type": "string", "default": ""}, - "client_id": {"title": "Client Id", "type": "string"}, - "client_secret": {"title": "Client Secret", "type": "string"}, + "client_id": IsDict( + { + "title": "Client Id", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Client Id", "type": "string"} + ), + "client_secret": IsDict( + { + "title": "Client Secret", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Client Secret", "type": "string"} + ), }, }, "ValidationError": { diff --git a/tests/test_tutorial/test_security/test_tutorial003_an_py39.py b/tests/test_tutorial/test_security/test_tutorial003_an_py39.py index 7e74afafb16fe..7b21fbcc9290e 100644 --- a/tests/test_tutorial/test_security/test_tutorial003_an_py39.py +++ b/tests/test_tutorial/test_security/test_tutorial003_an_py39.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient from ...utils import needs_py39 @@ -86,7 +87,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/token": { @@ -142,16 +143,46 @@ def test_openapi_schema(client: TestClient): "required": ["username", "password"], "type": "object", "properties": { - "grant_type": { - "title": "Grant Type", - "pattern": "password", - "type": "string", - }, + "grant_type": IsDict( + { + "title": "Grant Type", + "anyOf": [ + {"pattern": "password", "type": "string"}, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "Grant Type", + "pattern": "password", + "type": "string", + } + ), "username": {"title": "Username", "type": "string"}, "password": {"title": "Password", "type": "string"}, "scope": {"title": "Scope", "type": "string", "default": ""}, - "client_id": {"title": "Client Id", "type": "string"}, - "client_secret": {"title": "Client Secret", "type": "string"}, + "client_id": IsDict( + { + "title": "Client Id", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Client Id", "type": "string"} + ), + "client_secret": IsDict( + { + "title": "Client Secret", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Client Secret", "type": "string"} + ), }, }, "ValidationError": { diff --git a/tests/test_tutorial/test_security/test_tutorial003_py310.py b/tests/test_tutorial/test_security/test_tutorial003_py310.py index a463751f5ee3e..512504534f0b1 100644 --- a/tests/test_tutorial/test_security/test_tutorial003_py310.py +++ b/tests/test_tutorial/test_security/test_tutorial003_py310.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient from ...utils import needs_py310 @@ -86,7 +87,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/token": { @@ -142,16 +143,46 @@ def test_openapi_schema(client: TestClient): "required": ["username", "password"], "type": "object", "properties": { - "grant_type": { - "title": "Grant Type", - "pattern": "password", - "type": "string", - }, + "grant_type": IsDict( + { + "title": "Grant Type", + "anyOf": [ + {"pattern": "password", "type": "string"}, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "Grant Type", + "pattern": "password", + "type": "string", + } + ), "username": {"title": "Username", "type": "string"}, "password": {"title": "Password", "type": "string"}, "scope": {"title": "Scope", "type": "string", "default": ""}, - "client_id": {"title": "Client Id", "type": "string"}, - "client_secret": {"title": "Client Secret", "type": "string"}, + "client_id": IsDict( + { + "title": "Client Id", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Client Id", "type": "string"} + ), + "client_secret": IsDict( + { + "title": "Client Secret", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Client Secret", "type": "string"} + ), }, }, "ValidationError": { diff --git a/tests/test_tutorial/test_security/test_tutorial005.py b/tests/test_tutorial/test_security/test_tutorial005.py index ccb5b3c9f8756..2e580dbb3544f 100644 --- a/tests/test_tutorial/test_security/test_tutorial005.py +++ b/tests/test_tutorial/test_security/test_tutorial005.py @@ -1,3 +1,4 @@ +from dirty_equals import IsDict, IsOneOf from fastapi.testclient import TestClient from docs_src.security.tutorial005 import ( @@ -127,7 +128,7 @@ def test_token_no_scope(): assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' -def test_token_inexistent_user(): +def test_token_nonexistent_user(): response = client.get( "/users/me", headers={ @@ -179,7 +180,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/token": { @@ -266,13 +267,44 @@ def test_openapi_schema(): "schemas": { "User": { "title": "User", - "required": ["username"], + "required": IsOneOf( + ["username", "email", "full_name", "disabled"], + # TODO: remove when deprecating Pydantic v1 + ["username"], + ), "type": "object", "properties": { "username": {"title": "Username", "type": "string"}, - "email": {"title": "Email", "type": "string"}, - "full_name": {"title": "Full Name", "type": "string"}, - "disabled": {"title": "Disabled", "type": "boolean"}, + "email": IsDict( + { + "title": "Email", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Email", "type": "string"} + ), + "full_name": IsDict( + { + "title": "Full Name", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Full Name", "type": "string"} + ), + "disabled": IsDict( + { + "title": "Disabled", + "anyOf": [{"type": "boolean"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Disabled", "type": "boolean"} + ), }, }, "Token": { @@ -289,16 +321,46 @@ def test_openapi_schema(): "required": ["username", "password"], "type": "object", "properties": { - "grant_type": { - "title": "Grant Type", - "pattern": "password", - "type": "string", - }, + "grant_type": IsDict( + { + "title": "Grant Type", + "anyOf": [ + {"pattern": "password", "type": "string"}, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "Grant Type", + "pattern": "password", + "type": "string", + } + ), "username": {"title": "Username", "type": "string"}, "password": {"title": "Password", "type": "string"}, "scope": {"title": "Scope", "type": "string", "default": ""}, - "client_id": {"title": "Client Id", "type": "string"}, - "client_secret": {"title": "Client Secret", "type": "string"}, + "client_id": IsDict( + { + "title": "Client Id", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Client Id", "type": "string"} + ), + "client_secret": IsDict( + { + "title": "Client Secret", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Client Secret", "type": "string"} + ), }, }, "ValidationError": { diff --git a/tests/test_tutorial/test_security/test_tutorial005_an.py b/tests/test_tutorial/test_security/test_tutorial005_an.py index e851f47fecd37..04c7d60bcfc60 100644 --- a/tests/test_tutorial/test_security/test_tutorial005_an.py +++ b/tests/test_tutorial/test_security/test_tutorial005_an.py @@ -1,3 +1,4 @@ +from dirty_equals import IsDict, IsOneOf from fastapi.testclient import TestClient from docs_src.security.tutorial005_an import ( @@ -127,7 +128,7 @@ def test_token_no_scope(): assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' -def test_token_inexistent_user(): +def test_token_nonexistent_user(): response = client.get( "/users/me", headers={ @@ -179,7 +180,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/token": { @@ -266,13 +267,44 @@ def test_openapi_schema(): "schemas": { "User": { "title": "User", - "required": ["username"], + "required": IsOneOf( + ["username", "email", "full_name", "disabled"], + # TODO: remove when deprecating Pydantic v1 + ["username"], + ), "type": "object", "properties": { "username": {"title": "Username", "type": "string"}, - "email": {"title": "Email", "type": "string"}, - "full_name": {"title": "Full Name", "type": "string"}, - "disabled": {"title": "Disabled", "type": "boolean"}, + "email": IsDict( + { + "title": "Email", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Email", "type": "string"} + ), + "full_name": IsDict( + { + "title": "Full Name", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Full Name", "type": "string"} + ), + "disabled": IsDict( + { + "title": "Disabled", + "anyOf": [{"type": "boolean"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Disabled", "type": "boolean"} + ), }, }, "Token": { @@ -289,16 +321,46 @@ def test_openapi_schema(): "required": ["username", "password"], "type": "object", "properties": { - "grant_type": { - "title": "Grant Type", - "pattern": "password", - "type": "string", - }, + "grant_type": IsDict( + { + "title": "Grant Type", + "anyOf": [ + {"pattern": "password", "type": "string"}, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "Grant Type", + "pattern": "password", + "type": "string", + } + ), "username": {"title": "Username", "type": "string"}, "password": {"title": "Password", "type": "string"}, "scope": {"title": "Scope", "type": "string", "default": ""}, - "client_id": {"title": "Client Id", "type": "string"}, - "client_secret": {"title": "Client Secret", "type": "string"}, + "client_id": IsDict( + { + "title": "Client Id", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Client Id", "type": "string"} + ), + "client_secret": IsDict( + { + "title": "Client Secret", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Client Secret", "type": "string"} + ), }, }, "ValidationError": { diff --git a/tests/test_tutorial/test_security/test_tutorial005_an_py310.py b/tests/test_tutorial/test_security/test_tutorial005_an_py310.py index cca5819802ccc..9c7f83ed29a9b 100644 --- a/tests/test_tutorial/test_security/test_tutorial005_an_py310.py +++ b/tests/test_tutorial/test_security/test_tutorial005_an_py310.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict, IsOneOf from fastapi.testclient import TestClient from ...utils import needs_py310 @@ -150,7 +151,7 @@ def test_token_no_scope(client: TestClient): @needs_py310 -def test_token_inexistent_user(client: TestClient): +def test_token_nonexistent_user(client: TestClient): response = client.get( "/users/me", headers={ @@ -207,7 +208,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/token": { @@ -294,13 +295,44 @@ def test_openapi_schema(client: TestClient): "schemas": { "User": { "title": "User", - "required": ["username"], + "required": IsOneOf( + ["username", "email", "full_name", "disabled"], + # TODO: remove when deprecating Pydantic v1 + ["username"], + ), "type": "object", "properties": { "username": {"title": "Username", "type": "string"}, - "email": {"title": "Email", "type": "string"}, - "full_name": {"title": "Full Name", "type": "string"}, - "disabled": {"title": "Disabled", "type": "boolean"}, + "email": IsDict( + { + "title": "Email", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Email", "type": "string"} + ), + "full_name": IsDict( + { + "title": "Full Name", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Full Name", "type": "string"} + ), + "disabled": IsDict( + { + "title": "Disabled", + "anyOf": [{"type": "boolean"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Disabled", "type": "boolean"} + ), }, }, "Token": { @@ -317,16 +349,46 @@ def test_openapi_schema(client: TestClient): "required": ["username", "password"], "type": "object", "properties": { - "grant_type": { - "title": "Grant Type", - "pattern": "password", - "type": "string", - }, + "grant_type": IsDict( + { + "title": "Grant Type", + "anyOf": [ + {"pattern": "password", "type": "string"}, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "Grant Type", + "pattern": "password", + "type": "string", + } + ), "username": {"title": "Username", "type": "string"}, "password": {"title": "Password", "type": "string"}, "scope": {"title": "Scope", "type": "string", "default": ""}, - "client_id": {"title": "Client Id", "type": "string"}, - "client_secret": {"title": "Client Secret", "type": "string"}, + "client_id": IsDict( + { + "title": "Client Id", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Client Id", "type": "string"} + ), + "client_secret": IsDict( + { + "title": "Client Secret", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Client Secret", "type": "string"} + ), }, }, "ValidationError": { diff --git a/tests/test_tutorial/test_security/test_tutorial005_an_py39.py b/tests/test_tutorial/test_security/test_tutorial005_an_py39.py index eae8514575687..04cc1b014e1f4 100644 --- a/tests/test_tutorial/test_security/test_tutorial005_an_py39.py +++ b/tests/test_tutorial/test_security/test_tutorial005_an_py39.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict, IsOneOf from fastapi.testclient import TestClient from ...utils import needs_py39 @@ -150,7 +151,7 @@ def test_token_no_scope(client: TestClient): @needs_py39 -def test_token_inexistent_user(client: TestClient): +def test_token_nonexistent_user(client: TestClient): response = client.get( "/users/me", headers={ @@ -207,7 +208,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/token": { @@ -294,13 +295,44 @@ def test_openapi_schema(client: TestClient): "schemas": { "User": { "title": "User", - "required": ["username"], + "required": IsOneOf( + ["username", "email", "full_name", "disabled"], + # TODO: remove when deprecating Pydantic v1 + ["username"], + ), "type": "object", "properties": { "username": {"title": "Username", "type": "string"}, - "email": {"title": "Email", "type": "string"}, - "full_name": {"title": "Full Name", "type": "string"}, - "disabled": {"title": "Disabled", "type": "boolean"}, + "email": IsDict( + { + "title": "Email", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Email", "type": "string"} + ), + "full_name": IsDict( + { + "title": "Full Name", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Full Name", "type": "string"} + ), + "disabled": IsDict( + { + "title": "Disabled", + "anyOf": [{"type": "boolean"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Disabled", "type": "boolean"} + ), }, }, "Token": { @@ -317,16 +349,46 @@ def test_openapi_schema(client: TestClient): "required": ["username", "password"], "type": "object", "properties": { - "grant_type": { - "title": "Grant Type", - "pattern": "password", - "type": "string", - }, + "grant_type": IsDict( + { + "title": "Grant Type", + "anyOf": [ + {"pattern": "password", "type": "string"}, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "Grant Type", + "pattern": "password", + "type": "string", + } + ), "username": {"title": "Username", "type": "string"}, "password": {"title": "Password", "type": "string"}, "scope": {"title": "Scope", "type": "string", "default": ""}, - "client_id": {"title": "Client Id", "type": "string"}, - "client_secret": {"title": "Client Secret", "type": "string"}, + "client_id": IsDict( + { + "title": "Client Id", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Client Id", "type": "string"} + ), + "client_secret": IsDict( + { + "title": "Client Secret", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Client Secret", "type": "string"} + ), }, }, "ValidationError": { diff --git a/tests/test_tutorial/test_security/test_tutorial005_py310.py b/tests/test_tutorial/test_security/test_tutorial005_py310.py index cdbd8f75ec25c..98c60c1c202f3 100644 --- a/tests/test_tutorial/test_security/test_tutorial005_py310.py +++ b/tests/test_tutorial/test_security/test_tutorial005_py310.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict, IsOneOf from fastapi.testclient import TestClient from ...utils import needs_py310 @@ -150,7 +151,7 @@ def test_token_no_scope(client: TestClient): @needs_py310 -def test_token_inexistent_user(client: TestClient): +def test_token_nonexistent_user(client: TestClient): response = client.get( "/users/me", headers={ @@ -207,7 +208,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/token": { @@ -294,13 +295,44 @@ def test_openapi_schema(client: TestClient): "schemas": { "User": { "title": "User", - "required": ["username"], + "required": IsOneOf( + ["username", "email", "full_name", "disabled"], + # TODO: remove when deprecating Pydantic v1 + ["username"], + ), "type": "object", "properties": { "username": {"title": "Username", "type": "string"}, - "email": {"title": "Email", "type": "string"}, - "full_name": {"title": "Full Name", "type": "string"}, - "disabled": {"title": "Disabled", "type": "boolean"}, + "email": IsDict( + { + "title": "Email", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Email", "type": "string"} + ), + "full_name": IsDict( + { + "title": "Full Name", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Full Name", "type": "string"} + ), + "disabled": IsDict( + { + "title": "Disabled", + "anyOf": [{"type": "boolean"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Disabled", "type": "boolean"} + ), }, }, "Token": { @@ -317,16 +349,46 @@ def test_openapi_schema(client: TestClient): "required": ["username", "password"], "type": "object", "properties": { - "grant_type": { - "title": "Grant Type", - "pattern": "password", - "type": "string", - }, + "grant_type": IsDict( + { + "title": "Grant Type", + "anyOf": [ + {"pattern": "password", "type": "string"}, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "Grant Type", + "pattern": "password", + "type": "string", + } + ), "username": {"title": "Username", "type": "string"}, "password": {"title": "Password", "type": "string"}, "scope": {"title": "Scope", "type": "string", "default": ""}, - "client_id": {"title": "Client Id", "type": "string"}, - "client_secret": {"title": "Client Secret", "type": "string"}, + "client_id": IsDict( + { + "title": "Client Id", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Client Id", "type": "string"} + ), + "client_secret": IsDict( + { + "title": "Client Secret", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Client Secret", "type": "string"} + ), }, }, "ValidationError": { diff --git a/tests/test_tutorial/test_security/test_tutorial005_py39.py b/tests/test_tutorial/test_security/test_tutorial005_py39.py index 45b2a2341d7f0..cd2157d54dd91 100644 --- a/tests/test_tutorial/test_security/test_tutorial005_py39.py +++ b/tests/test_tutorial/test_security/test_tutorial005_py39.py @@ -1,4 +1,5 @@ import pytest +from dirty_equals import IsDict, IsOneOf from fastapi.testclient import TestClient from ...utils import needs_py39 @@ -150,7 +151,7 @@ def test_token_no_scope(client: TestClient): @needs_py39 -def test_token_inexistent_user(client: TestClient): +def test_token_nonexistent_user(client: TestClient): response = client.get( "/users/me", headers={ @@ -207,7 +208,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/token": { @@ -294,13 +295,44 @@ def test_openapi_schema(client: TestClient): "schemas": { "User": { "title": "User", - "required": ["username"], + "required": IsOneOf( + ["username", "email", "full_name", "disabled"], + # TODO: remove when deprecating Pydantic v1 + ["username"], + ), "type": "object", "properties": { "username": {"title": "Username", "type": "string"}, - "email": {"title": "Email", "type": "string"}, - "full_name": {"title": "Full Name", "type": "string"}, - "disabled": {"title": "Disabled", "type": "boolean"}, + "email": IsDict( + { + "title": "Email", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Email", "type": "string"} + ), + "full_name": IsDict( + { + "title": "Full Name", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Full Name", "type": "string"} + ), + "disabled": IsDict( + { + "title": "Disabled", + "anyOf": [{"type": "boolean"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Disabled", "type": "boolean"} + ), }, }, "Token": { @@ -317,16 +349,46 @@ def test_openapi_schema(client: TestClient): "required": ["username", "password"], "type": "object", "properties": { - "grant_type": { - "title": "Grant Type", - "pattern": "password", - "type": "string", - }, + "grant_type": IsDict( + { + "title": "Grant Type", + "anyOf": [ + {"pattern": "password", "type": "string"}, + {"type": "null"}, + ], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "title": "Grant Type", + "pattern": "password", + "type": "string", + } + ), "username": {"title": "Username", "type": "string"}, "password": {"title": "Password", "type": "string"}, "scope": {"title": "Scope", "type": "string", "default": ""}, - "client_id": {"title": "Client Id", "type": "string"}, - "client_secret": {"title": "Client Secret", "type": "string"}, + "client_id": IsDict( + { + "title": "Client Id", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Client Id", "type": "string"} + ), + "client_secret": IsDict( + { + "title": "Client Secret", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Client Secret", "type": "string"} + ), }, }, "ValidationError": { diff --git a/tests/test_tutorial/test_security/test_tutorial006.py b/tests/test_tutorial/test_security/test_tutorial006.py index 73cbdc538d21b..dc459b6fd0313 100644 --- a/tests/test_tutorial/test_security/test_tutorial006.py +++ b/tests/test_tutorial/test_security/test_tutorial006.py @@ -42,7 +42,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/me": { diff --git a/tests/test_tutorial/test_security/test_tutorial006_an.py b/tests/test_tutorial/test_security/test_tutorial006_an.py index 5f970ed013fb7..52ddd938f992d 100644 --- a/tests/test_tutorial/test_security/test_tutorial006_an.py +++ b/tests/test_tutorial/test_security/test_tutorial006_an.py @@ -42,7 +42,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/me": { diff --git a/tests/test_tutorial/test_security/test_tutorial006_an_py39.py b/tests/test_tutorial/test_security/test_tutorial006_an_py39.py index 7d7a851acf65b..52b22e5739a27 100644 --- a/tests/test_tutorial/test_security/test_tutorial006_an_py39.py +++ b/tests/test_tutorial/test_security/test_tutorial006_an_py39.py @@ -54,7 +54,7 @@ def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/me": { diff --git a/tests/test_tutorial/test_separate_openapi_schemas/__init__.py b/tests/test_tutorial/test_separate_openapi_schemas/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001.py b/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001.py new file mode 100644 index 0000000000000..cdfae9f8c1b67 --- /dev/null +++ b/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001.py @@ -0,0 +1,133 @@ +import pytest +from fastapi.testclient import TestClient + +from ...utils import needs_pydanticv2 + + +@pytest.fixture(name="client") +def get_client() -> TestClient: + from docs_src.separate_openapi_schemas.tutorial001 import app + + client = TestClient(app) + return client + + +def test_create_item(client: TestClient) -> None: + response = client.post("/items/", json={"name": "Foo"}) + assert response.status_code == 200, response.text + assert response.json() == {"name": "Foo", "description": None} + + +def test_read_items(client: TestClient) -> None: + response = client.get("/items/") + assert response.status_code == 200, response.text + assert response.json() == [ + { + "name": "Portal Gun", + "description": "Device to travel through the multi-rick-verse", + }, + {"name": "Plumbus", "description": None}, + ] + + +@needs_pydanticv2 +def test_openapi_schema(client: TestClient) -> None: + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/items/": { + "get": { + "summary": "Read Items", + "operationId": "read_items_items__get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "items": {"$ref": "#/components/schemas/Item"}, + "type": "array", + "title": "Response Read Items Items Get", + } + } + }, + } + }, + }, + "post": { + "summary": "Create Item", + "operationId": "create_item_items__post", + "requestBody": { + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Item"} + } + }, + "required": True, + }, + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + }, + } + }, + "components": { + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": {"$ref": "#/components/schemas/ValidationError"}, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "Item": { + "properties": { + "name": {"type": "string", "title": "Name"}, + "description": { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Description", + }, + }, + "type": "object", + "required": ["name"], + "title": "Item", + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + } + }, + } diff --git a/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001_py310.py b/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001_py310.py new file mode 100644 index 0000000000000..3b22146f634da --- /dev/null +++ b/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001_py310.py @@ -0,0 +1,136 @@ +import pytest +from fastapi.testclient import TestClient + +from ...utils import needs_py310, needs_pydanticv2 + + +@pytest.fixture(name="client") +def get_client() -> TestClient: + from docs_src.separate_openapi_schemas.tutorial001_py310 import app + + client = TestClient(app) + return client + + +@needs_py310 +def test_create_item(client: TestClient) -> None: + response = client.post("/items/", json={"name": "Foo"}) + assert response.status_code == 200, response.text + assert response.json() == {"name": "Foo", "description": None} + + +@needs_py310 +def test_read_items(client: TestClient) -> None: + response = client.get("/items/") + assert response.status_code == 200, response.text + assert response.json() == [ + { + "name": "Portal Gun", + "description": "Device to travel through the multi-rick-verse", + }, + {"name": "Plumbus", "description": None}, + ] + + +@needs_py310 +@needs_pydanticv2 +def test_openapi_schema(client: TestClient) -> None: + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/items/": { + "get": { + "summary": "Read Items", + "operationId": "read_items_items__get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "items": {"$ref": "#/components/schemas/Item"}, + "type": "array", + "title": "Response Read Items Items Get", + } + } + }, + } + }, + }, + "post": { + "summary": "Create Item", + "operationId": "create_item_items__post", + "requestBody": { + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Item"} + } + }, + "required": True, + }, + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + }, + } + }, + "components": { + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": {"$ref": "#/components/schemas/ValidationError"}, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "Item": { + "properties": { + "name": {"type": "string", "title": "Name"}, + "description": { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Description", + }, + }, + "type": "object", + "required": ["name"], + "title": "Item", + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + } + }, + } diff --git a/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001_py39.py b/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001_py39.py new file mode 100644 index 0000000000000..991abe8113e96 --- /dev/null +++ b/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001_py39.py @@ -0,0 +1,136 @@ +import pytest +from fastapi.testclient import TestClient + +from ...utils import needs_py39, needs_pydanticv2 + + +@pytest.fixture(name="client") +def get_client() -> TestClient: + from docs_src.separate_openapi_schemas.tutorial001_py39 import app + + client = TestClient(app) + return client + + +@needs_py39 +def test_create_item(client: TestClient) -> None: + response = client.post("/items/", json={"name": "Foo"}) + assert response.status_code == 200, response.text + assert response.json() == {"name": "Foo", "description": None} + + +@needs_py39 +def test_read_items(client: TestClient) -> None: + response = client.get("/items/") + assert response.status_code == 200, response.text + assert response.json() == [ + { + "name": "Portal Gun", + "description": "Device to travel through the multi-rick-verse", + }, + {"name": "Plumbus", "description": None}, + ] + + +@needs_py39 +@needs_pydanticv2 +def test_openapi_schema(client: TestClient) -> None: + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/items/": { + "get": { + "summary": "Read Items", + "operationId": "read_items_items__get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "items": {"$ref": "#/components/schemas/Item"}, + "type": "array", + "title": "Response Read Items Items Get", + } + } + }, + } + }, + }, + "post": { + "summary": "Create Item", + "operationId": "create_item_items__post", + "requestBody": { + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Item"} + } + }, + "required": True, + }, + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + }, + } + }, + "components": { + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": {"$ref": "#/components/schemas/ValidationError"}, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "Item": { + "properties": { + "name": {"type": "string", "title": "Name"}, + "description": { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Description", + }, + }, + "type": "object", + "required": ["name"], + "title": "Item", + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + } + }, + } diff --git a/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002.py b/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002.py new file mode 100644 index 0000000000000..d2cf7945b71d7 --- /dev/null +++ b/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002.py @@ -0,0 +1,133 @@ +import pytest +from fastapi.testclient import TestClient + +from ...utils import needs_pydanticv2 + + +@pytest.fixture(name="client") +def get_client() -> TestClient: + from docs_src.separate_openapi_schemas.tutorial002 import app + + client = TestClient(app) + return client + + +def test_create_item(client: TestClient) -> None: + response = client.post("/items/", json={"name": "Foo"}) + assert response.status_code == 200, response.text + assert response.json() == {"name": "Foo", "description": None} + + +def test_read_items(client: TestClient) -> None: + response = client.get("/items/") + assert response.status_code == 200, response.text + assert response.json() == [ + { + "name": "Portal Gun", + "description": "Device to travel through the multi-rick-verse", + }, + {"name": "Plumbus", "description": None}, + ] + + +@needs_pydanticv2 +def test_openapi_schema(client: TestClient) -> None: + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/items/": { + "get": { + "summary": "Read Items", + "operationId": "read_items_items__get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "items": {"$ref": "#/components/schemas/Item"}, + "type": "array", + "title": "Response Read Items Items Get", + } + } + }, + } + }, + }, + "post": { + "summary": "Create Item", + "operationId": "create_item_items__post", + "requestBody": { + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Item"} + } + }, + "required": True, + }, + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + }, + } + }, + "components": { + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": {"$ref": "#/components/schemas/ValidationError"}, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "Item": { + "properties": { + "name": {"type": "string", "title": "Name"}, + "description": { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Description", + }, + }, + "type": "object", + "required": ["name"], + "title": "Item", + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + } + }, + } diff --git a/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002_py310.py b/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002_py310.py new file mode 100644 index 0000000000000..89c9ce977043e --- /dev/null +++ b/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002_py310.py @@ -0,0 +1,136 @@ +import pytest +from fastapi.testclient import TestClient + +from ...utils import needs_py310, needs_pydanticv2 + + +@pytest.fixture(name="client") +def get_client() -> TestClient: + from docs_src.separate_openapi_schemas.tutorial002_py310 import app + + client = TestClient(app) + return client + + +@needs_py310 +def test_create_item(client: TestClient) -> None: + response = client.post("/items/", json={"name": "Foo"}) + assert response.status_code == 200, response.text + assert response.json() == {"name": "Foo", "description": None} + + +@needs_py310 +def test_read_items(client: TestClient) -> None: + response = client.get("/items/") + assert response.status_code == 200, response.text + assert response.json() == [ + { + "name": "Portal Gun", + "description": "Device to travel through the multi-rick-verse", + }, + {"name": "Plumbus", "description": None}, + ] + + +@needs_py310 +@needs_pydanticv2 +def test_openapi_schema(client: TestClient) -> None: + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/items/": { + "get": { + "summary": "Read Items", + "operationId": "read_items_items__get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "items": {"$ref": "#/components/schemas/Item"}, + "type": "array", + "title": "Response Read Items Items Get", + } + } + }, + } + }, + }, + "post": { + "summary": "Create Item", + "operationId": "create_item_items__post", + "requestBody": { + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Item"} + } + }, + "required": True, + }, + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + }, + } + }, + "components": { + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": {"$ref": "#/components/schemas/ValidationError"}, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "Item": { + "properties": { + "name": {"type": "string", "title": "Name"}, + "description": { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Description", + }, + }, + "type": "object", + "required": ["name"], + "title": "Item", + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + } + }, + } diff --git a/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002_py39.py b/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002_py39.py new file mode 100644 index 0000000000000..6ac3d8f7912da --- /dev/null +++ b/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002_py39.py @@ -0,0 +1,136 @@ +import pytest +from fastapi.testclient import TestClient + +from ...utils import needs_py39, needs_pydanticv2 + + +@pytest.fixture(name="client") +def get_client() -> TestClient: + from docs_src.separate_openapi_schemas.tutorial002_py39 import app + + client = TestClient(app) + return client + + +@needs_py39 +def test_create_item(client: TestClient) -> None: + response = client.post("/items/", json={"name": "Foo"}) + assert response.status_code == 200, response.text + assert response.json() == {"name": "Foo", "description": None} + + +@needs_py39 +def test_read_items(client: TestClient) -> None: + response = client.get("/items/") + assert response.status_code == 200, response.text + assert response.json() == [ + { + "name": "Portal Gun", + "description": "Device to travel through the multi-rick-verse", + }, + {"name": "Plumbus", "description": None}, + ] + + +@needs_py39 +@needs_pydanticv2 +def test_openapi_schema(client: TestClient) -> None: + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/items/": { + "get": { + "summary": "Read Items", + "operationId": "read_items_items__get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "items": {"$ref": "#/components/schemas/Item"}, + "type": "array", + "title": "Response Read Items Items Get", + } + } + }, + } + }, + }, + "post": { + "summary": "Create Item", + "operationId": "create_item_items__post", + "requestBody": { + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Item"} + } + }, + "required": True, + }, + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + }, + } + }, + "components": { + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": {"$ref": "#/components/schemas/ValidationError"}, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "Item": { + "properties": { + "name": {"type": "string", "title": "Name"}, + "description": { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Description", + }, + }, + "type": "object", + "required": ["name"], + "title": "Item", + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + } + }, + } diff --git a/tests/test_tutorial/test_settings/test_app02.py b/tests/test_tutorial/test_settings/test_app02.py index fd32b8766f649..eced88c044ba4 100644 --- a/tests/test_tutorial/test_settings/test_app02.py +++ b/tests/test_tutorial/test_settings/test_app02.py @@ -1,17 +1,20 @@ -from fastapi.testclient import TestClient from pytest import MonkeyPatch -from docs_src.settings.app02 import main, test_main - -client = TestClient(main.app) +from ...utils import needs_pydanticv2 +@needs_pydanticv2 def test_settings(monkeypatch: MonkeyPatch): + from docs_src.settings.app02 import main + monkeypatch.setenv("ADMIN_EMAIL", "admin@example.com") settings = main.get_settings() assert settings.app_name == "Awesome API" assert settings.items_per_user == 50 +@needs_pydanticv2 def test_override_settings(): + from docs_src.settings.app02 import test_main + test_main.test_app() diff --git a/tests/test_tutorial/test_settings/test_tutorial001.py b/tests/test_tutorial/test_settings/test_tutorial001.py new file mode 100644 index 0000000000000..eb30dbcee44bc --- /dev/null +++ b/tests/test_tutorial/test_settings/test_tutorial001.py @@ -0,0 +1,19 @@ +from fastapi.testclient import TestClient +from pytest import MonkeyPatch + +from ...utils import needs_pydanticv2 + + +@needs_pydanticv2 +def test_settings(monkeypatch: MonkeyPatch): + monkeypatch.setenv("ADMIN_EMAIL", "admin@example.com") + from docs_src.settings.tutorial001 import app + + client = TestClient(app) + response = client.get("/info") + assert response.status_code == 200, response.text + assert response.json() == { + "app_name": "Awesome API", + "admin_email": "admin@example.com", + "items_per_user": 50, + } diff --git a/tests/test_tutorial/test_settings/test_tutorial001_pv1.py b/tests/test_tutorial/test_settings/test_tutorial001_pv1.py new file mode 100644 index 0000000000000..e4659de6653c9 --- /dev/null +++ b/tests/test_tutorial/test_settings/test_tutorial001_pv1.py @@ -0,0 +1,19 @@ +from fastapi.testclient import TestClient +from pytest import MonkeyPatch + +from ...utils import needs_pydanticv1 + + +@needs_pydanticv1 +def test_settings(monkeypatch: MonkeyPatch): + monkeypatch.setenv("ADMIN_EMAIL", "admin@example.com") + from docs_src.settings.tutorial001_pv1 import app + + client = TestClient(app) + response = client.get("/info") + assert response.status_code == 200, response.text + assert response.json() == { + "app_name": "Awesome API", + "admin_email": "admin@example.com", + "items_per_user": 50, + } diff --git a/tests/test_tutorial/test_sql_databases/test_sql_databases.py b/tests/test_tutorial/test_sql_databases/test_sql_databases.py index a2628f3c3bc08..e3e2b36a801ab 100644 --- a/tests/test_tutorial/test_sql_databases/test_sql_databases.py +++ b/tests/test_tutorial/test_sql_databases/test_sql_databases.py @@ -3,8 +3,11 @@ from pathlib import Path import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient +from ...utils import needs_pydanticv1 + @pytest.fixture(scope="module") def client(tmp_path_factory: pytest.TempPathFactory): @@ -26,6 +29,8 @@ def client(tmp_path_factory: pytest.TempPathFactory): os.chdir(cwd) +# TODO: pv2 add version with Pydantic v2 +@needs_pydanticv1 def test_create_user(client): test_user = {"email": "johndoe@example.com", "password": "secret"} response = client.post("/users/", json=test_user) @@ -37,6 +42,8 @@ def test_create_user(client): assert response.status_code == 400, response.text +# TODO: pv2 add version with Pydantic v2 +@needs_pydanticv1 def test_get_user(client): response = client.get("/users/1") assert response.status_code == 200, response.text @@ -45,11 +52,15 @@ def test_get_user(client): assert "id" in data -def test_inexistent_user(client): +# TODO: pv2 add version with Pydantic v2 +@needs_pydanticv1 +def test_nonexistent_user(client): response = client.get("/users/999") assert response.status_code == 404, response.text +# TODO: pv2 add version with Pydantic v2 +@needs_pydanticv1 def test_get_users(client): response = client.get("/users/") assert response.status_code == 200, response.text @@ -58,6 +69,8 @@ def test_get_users(client): assert "id" in data[0] +# TODO: pv2 add Pydantic v2 version +@needs_pydanticv1 def test_create_item(client): item = {"title": "Foo", "description": "Something that fights"} response = client.post("/users/1/items/", json=item) @@ -75,6 +88,8 @@ def test_create_item(client): assert item_to_check["description"] == item["description"] +# TODO: pv2 add Pydantic v2 version +@needs_pydanticv1 def test_read_items(client): response = client.get("/items/") assert response.status_code == 200, response.text @@ -85,11 +100,13 @@ def test_read_items(client): assert "description" in first_item -def test_openapi_schema(client): +# TODO: pv2 add version with Pydantic v2 +@needs_pydanticv1 +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/": { @@ -313,7 +330,16 @@ def test_openapi_schema(client): "type": "object", "properties": { "title": {"title": "Title", "type": "string"}, - "description": {"title": "Description", "type": "string"}, + "description": IsDict( + { + "title": "Description", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Description", "type": "string"} + ), }, }, "Item": { @@ -322,7 +348,16 @@ def test_openapi_schema(client): "type": "object", "properties": { "title": {"title": "Title", "type": "string"}, - "description": {"title": "Description", "type": "string"}, + "description": IsDict( + { + "title": "Description", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Description", "type": "string"}, + ), "id": {"title": "Id", "type": "integer"}, "owner_id": {"title": "Owner Id", "type": "integer"}, }, diff --git a/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware.py b/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware.py index 02501b1a248f9..73b97e09d9f8a 100644 --- a/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware.py +++ b/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware.py @@ -2,8 +2,11 @@ from pathlib import Path import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient +from ...utils import needs_pydanticv1 + @pytest.fixture(scope="module") def client(): @@ -22,6 +25,8 @@ def client(): test_db.unlink() +# TODO: pv2 add version with Pydantic v2 +@needs_pydanticv1 def test_create_user(client): test_user = {"email": "johndoe@example.com", "password": "secret"} response = client.post("/users/", json=test_user) @@ -33,6 +38,8 @@ def test_create_user(client): assert response.status_code == 400, response.text +# TODO: pv2 add version with Pydantic v2 +@needs_pydanticv1 def test_get_user(client): response = client.get("/users/1") assert response.status_code == 200, response.text @@ -41,11 +48,15 @@ def test_get_user(client): assert "id" in data -def test_inexistent_user(client): +# TODO: pv2 add version with Pydantic v2 +@needs_pydanticv1 +def test_nonexistent_user(client): response = client.get("/users/999") assert response.status_code == 404, response.text +# TODO: pv2 add version with Pydantic v2 +@needs_pydanticv1 def test_get_users(client): response = client.get("/users/") assert response.status_code == 200, response.text @@ -54,6 +65,8 @@ def test_get_users(client): assert "id" in data[0] +# TODO: pv2 add Pydantic v2 version +@needs_pydanticv1 def test_create_item(client): item = {"title": "Foo", "description": "Something that fights"} response = client.post("/users/1/items/", json=item) @@ -77,6 +90,8 @@ def test_create_item(client): assert item_to_check["description"] == item["description"] +# TODO: pv2 add Pydantic v2 version +@needs_pydanticv1 def test_read_items(client): response = client.get("/items/") assert response.status_code == 200, response.text @@ -87,11 +102,13 @@ def test_read_items(client): assert "description" in first_item -def test_openapi_schema(client): +# TODO: pv2 add version with Pydantic v2 +@needs_pydanticv1 +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/": { @@ -315,7 +332,16 @@ def test_openapi_schema(client): "type": "object", "properties": { "title": {"title": "Title", "type": "string"}, - "description": {"title": "Description", "type": "string"}, + "description": IsDict( + { + "title": "Description", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Description", "type": "string"} + ), }, }, "Item": { @@ -324,7 +350,16 @@ def test_openapi_schema(client): "type": "object", "properties": { "title": {"title": "Title", "type": "string"}, - "description": {"title": "Description", "type": "string"}, + "description": IsDict( + { + "title": "Description", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Description", "type": "string"}, + ), "id": {"title": "Id", "type": "integer"}, "owner_id": {"title": "Owner Id", "type": "integer"}, }, diff --git a/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware_py310.py b/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware_py310.py index 67b92ea4a4012..a078f012a96d1 100644 --- a/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware_py310.py +++ b/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware_py310.py @@ -3,9 +3,10 @@ from pathlib import Path import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient -from ...utils import needs_py310 +from ...utils import needs_py310, needs_pydanticv1 @pytest.fixture(scope="module") @@ -30,6 +31,8 @@ def client(tmp_path_factory: pytest.TempPathFactory): @needs_py310 +# TODO: pv2 add version with Pydantic v2 +@needs_pydanticv1 def test_create_user(client): test_user = {"email": "johndoe@example.com", "password": "secret"} response = client.post("/users/", json=test_user) @@ -42,6 +45,8 @@ def test_create_user(client): @needs_py310 +# TODO: pv2 add version with Pydantic v2 +@needs_pydanticv1 def test_get_user(client): response = client.get("/users/1") assert response.status_code == 200, response.text @@ -51,12 +56,16 @@ def test_get_user(client): @needs_py310 -def test_inexistent_user(client): +# TODO: pv2 add version with Pydantic v2 +@needs_pydanticv1 +def test_nonexistent_user(client): response = client.get("/users/999") assert response.status_code == 404, response.text @needs_py310 +# TODO: pv2 add version with Pydantic v2 +@needs_pydanticv1 def test_get_users(client): response = client.get("/users/") assert response.status_code == 200, response.text @@ -66,6 +75,8 @@ def test_get_users(client): @needs_py310 +# TODO: pv2 add Pydantic v2 version +@needs_pydanticv1 def test_create_item(client): item = {"title": "Foo", "description": "Something that fights"} response = client.post("/users/1/items/", json=item) @@ -90,6 +101,8 @@ def test_create_item(client): @needs_py310 +# TODO: pv2 add Pydantic v2 version +@needs_pydanticv1 def test_read_items(client): response = client.get("/items/") assert response.status_code == 200, response.text @@ -101,11 +114,13 @@ def test_read_items(client): @needs_py310 -def test_openapi_schema(client): +# TODO: pv2 add version with Pydantic v2 +@needs_pydanticv1 +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/": { @@ -329,7 +344,16 @@ def test_openapi_schema(client): "type": "object", "properties": { "title": {"title": "Title", "type": "string"}, - "description": {"title": "Description", "type": "string"}, + "description": IsDict( + { + "title": "Description", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Description", "type": "string"} + ), }, }, "Item": { @@ -338,7 +362,16 @@ def test_openapi_schema(client): "type": "object", "properties": { "title": {"title": "Title", "type": "string"}, - "description": {"title": "Description", "type": "string"}, + "description": IsDict( + { + "title": "Description", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Description", "type": "string"}, + ), "id": {"title": "Id", "type": "integer"}, "owner_id": {"title": "Owner Id", "type": "integer"}, }, diff --git a/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware_py39.py b/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware_py39.py index a2af20ea23194..a5da07ac6feaf 100644 --- a/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware_py39.py +++ b/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware_py39.py @@ -3,9 +3,10 @@ from pathlib import Path import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient -from ...utils import needs_py39 +from ...utils import needs_py39, needs_pydanticv1 @pytest.fixture(scope="module") @@ -30,6 +31,8 @@ def client(tmp_path_factory: pytest.TempPathFactory): @needs_py39 +# TODO: pv2 add version with Pydantic v2 +@needs_pydanticv1 def test_create_user(client): test_user = {"email": "johndoe@example.com", "password": "secret"} response = client.post("/users/", json=test_user) @@ -42,6 +45,8 @@ def test_create_user(client): @needs_py39 +# TODO: pv2 add version with Pydantic v2 +@needs_pydanticv1 def test_get_user(client): response = client.get("/users/1") assert response.status_code == 200, response.text @@ -51,12 +56,16 @@ def test_get_user(client): @needs_py39 -def test_inexistent_user(client): +# TODO: pv2 add version with Pydantic v2 +@needs_pydanticv1 +def test_nonexistent_user(client): response = client.get("/users/999") assert response.status_code == 404, response.text @needs_py39 +# TODO: pv2 add version with Pydantic v2 +@needs_pydanticv1 def test_get_users(client): response = client.get("/users/") assert response.status_code == 200, response.text @@ -66,6 +75,8 @@ def test_get_users(client): @needs_py39 +# TODO: pv2 add version with Pydantic v2 +@needs_pydanticv1 def test_create_item(client): item = {"title": "Foo", "description": "Something that fights"} response = client.post("/users/1/items/", json=item) @@ -90,6 +101,8 @@ def test_create_item(client): @needs_py39 +# TODO: pv2 add version with Pydantic v2 +@needs_pydanticv1 def test_read_items(client): response = client.get("/items/") assert response.status_code == 200, response.text @@ -101,11 +114,13 @@ def test_read_items(client): @needs_py39 -def test_openapi_schema(client): +# TODO: pv2 add version with Pydantic v2 +@needs_pydanticv1 +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/": { @@ -329,7 +344,16 @@ def test_openapi_schema(client): "type": "object", "properties": { "title": {"title": "Title", "type": "string"}, - "description": {"title": "Description", "type": "string"}, + "description": IsDict( + { + "title": "Description", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Description", "type": "string"} + ), }, }, "Item": { @@ -338,7 +362,16 @@ def test_openapi_schema(client): "type": "object", "properties": { "title": {"title": "Title", "type": "string"}, - "description": {"title": "Description", "type": "string"}, + "description": IsDict( + { + "title": "Description", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Description", "type": "string"}, + ), "id": {"title": "Id", "type": "integer"}, "owner_id": {"title": "Owner Id", "type": "integer"}, }, diff --git a/tests/test_tutorial/test_sql_databases/test_sql_databases_py310.py b/tests/test_tutorial/test_sql_databases/test_sql_databases_py310.py index 2f918cfd8bb49..5a9106598884c 100644 --- a/tests/test_tutorial/test_sql_databases/test_sql_databases_py310.py +++ b/tests/test_tutorial/test_sql_databases/test_sql_databases_py310.py @@ -3,9 +3,10 @@ from pathlib import Path import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient -from ...utils import needs_py310 +from ...utils import needs_py310, needs_pydanticv1 @pytest.fixture(scope="module", name="client") @@ -29,6 +30,8 @@ def get_client(tmp_path_factory: pytest.TempPathFactory): @needs_py310 +# TODO: pv2 add version with Pydantic v2 +@needs_pydanticv1 def test_create_user(client): test_user = {"email": "johndoe@example.com", "password": "secret"} response = client.post("/users/", json=test_user) @@ -41,6 +44,8 @@ def test_create_user(client): @needs_py310 +# TODO: pv2 add version with Pydantic v2 +@needs_pydanticv1 def test_get_user(client): response = client.get("/users/1") assert response.status_code == 200, response.text @@ -50,12 +55,16 @@ def test_get_user(client): @needs_py310 -def test_inexistent_user(client): +# TODO: pv2 add version with Pydantic v2 +@needs_pydanticv1 +def test_nonexistent_user(client): response = client.get("/users/999") assert response.status_code == 404, response.text @needs_py310 +# TODO: pv2 add version with Pydantic v2 +@needs_pydanticv1 def test_get_users(client): response = client.get("/users/") assert response.status_code == 200, response.text @@ -65,6 +74,8 @@ def test_get_users(client): @needs_py310 +# TODO: pv2 add Pydantic v2 version +@needs_pydanticv1 def test_create_item(client): item = {"title": "Foo", "description": "Something that fights"} response = client.post("/users/1/items/", json=item) @@ -89,6 +100,8 @@ def test_create_item(client): @needs_py310 +# TODO: pv2 add Pydantic v2 version +@needs_pydanticv1 def test_read_items(client): response = client.get("/items/") assert response.status_code == 200, response.text @@ -100,11 +113,13 @@ def test_read_items(client): @needs_py310 -def test_openapi_schema(client): +# TODO: pv2 add version with Pydantic v2 +@needs_pydanticv1 +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/": { @@ -328,7 +343,16 @@ def test_openapi_schema(client): "type": "object", "properties": { "title": {"title": "Title", "type": "string"}, - "description": {"title": "Description", "type": "string"}, + "description": IsDict( + { + "title": "Description", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Description", "type": "string"} + ), }, }, "Item": { @@ -337,7 +361,16 @@ def test_openapi_schema(client): "type": "object", "properties": { "title": {"title": "Title", "type": "string"}, - "description": {"title": "Description", "type": "string"}, + "description": IsDict( + { + "title": "Description", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Description", "type": "string"}, + ), "id": {"title": "Id", "type": "integer"}, "owner_id": {"title": "Owner Id", "type": "integer"}, }, diff --git a/tests/test_tutorial/test_sql_databases/test_sql_databases_py39.py b/tests/test_tutorial/test_sql_databases/test_sql_databases_py39.py index f2eefe41d03a4..a354ba9053020 100644 --- a/tests/test_tutorial/test_sql_databases/test_sql_databases_py39.py +++ b/tests/test_tutorial/test_sql_databases/test_sql_databases_py39.py @@ -3,9 +3,10 @@ from pathlib import Path import pytest +from dirty_equals import IsDict from fastapi.testclient import TestClient -from ...utils import needs_py39 +from ...utils import needs_py39, needs_pydanticv1 @pytest.fixture(scope="module", name="client") @@ -29,6 +30,8 @@ def get_client(tmp_path_factory: pytest.TempPathFactory): @needs_py39 +# TODO: pv2 add version with Pydantic v2 +@needs_pydanticv1 def test_create_user(client): test_user = {"email": "johndoe@example.com", "password": "secret"} response = client.post("/users/", json=test_user) @@ -41,6 +44,8 @@ def test_create_user(client): @needs_py39 +# TODO: pv2 add version with Pydantic v2 +@needs_pydanticv1 def test_get_user(client): response = client.get("/users/1") assert response.status_code == 200, response.text @@ -50,12 +55,16 @@ def test_get_user(client): @needs_py39 -def test_inexistent_user(client): +# TODO: pv2 add version with Pydantic v2 +@needs_pydanticv1 +def test_nonexistent_user(client): response = client.get("/users/999") assert response.status_code == 404, response.text @needs_py39 +# TODO: pv2 add version with Pydantic v2 +@needs_pydanticv1 def test_get_users(client): response = client.get("/users/") assert response.status_code == 200, response.text @@ -65,6 +74,8 @@ def test_get_users(client): @needs_py39 +# TODO: pv2 add Pydantic v2 version +@needs_pydanticv1 def test_create_item(client): item = {"title": "Foo", "description": "Something that fights"} response = client.post("/users/1/items/", json=item) @@ -89,6 +100,8 @@ def test_create_item(client): @needs_py39 +# TODO: pv2 add Pydantic v2 version +@needs_pydanticv1 def test_read_items(client): response = client.get("/items/") assert response.status_code == 200, response.text @@ -100,11 +113,13 @@ def test_read_items(client): @needs_py39 -def test_openapi_schema(client): +# TODO: pv2 add version with Pydantic v2 +@needs_pydanticv1 +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/": { @@ -328,7 +343,16 @@ def test_openapi_schema(client): "type": "object", "properties": { "title": {"title": "Title", "type": "string"}, - "description": {"title": "Description", "type": "string"}, + "description": IsDict( + { + "title": "Description", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Description", "type": "string"} + ), }, }, "Item": { @@ -337,7 +361,16 @@ def test_openapi_schema(client): "type": "object", "properties": { "title": {"title": "Title", "type": "string"}, - "description": {"title": "Description", "type": "string"}, + "description": IsDict( + { + "title": "Description", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Description", "type": "string"}, + ), "id": {"title": "Id", "type": "integer"}, "owner_id": {"title": "Owner Id", "type": "integer"}, }, diff --git a/tests/test_tutorial/test_sql_databases/test_testing_databases.py b/tests/test_tutorial/test_sql_databases/test_testing_databases.py index 6f667dea03ce1..ce6ce230c84f4 100644 --- a/tests/test_tutorial/test_sql_databases/test_testing_databases.py +++ b/tests/test_tutorial/test_sql_databases/test_testing_databases.py @@ -4,7 +4,11 @@ import pytest +from ...utils import needs_pydanticv1 + +# TODO: pv2 add version with Pydantic v2 +@needs_pydanticv1 def test_testing_dbs(tmp_path_factory: pytest.TempPathFactory): tmp_path = tmp_path_factory.mktemp("data") cwd = os.getcwd() diff --git a/tests/test_tutorial/test_sql_databases/test_testing_databases_py310.py b/tests/test_tutorial/test_sql_databases/test_testing_databases_py310.py index 9e6b3f3e2ccb0..545d63c2a8155 100644 --- a/tests/test_tutorial/test_sql_databases/test_testing_databases_py310.py +++ b/tests/test_tutorial/test_sql_databases/test_testing_databases_py310.py @@ -4,10 +4,12 @@ import pytest -from ...utils import needs_py310 +from ...utils import needs_py310, needs_pydanticv1 @needs_py310 +# TODO: pv2 add version with Pydantic v2 +@needs_pydanticv1 def test_testing_dbs_py39(tmp_path_factory: pytest.TempPathFactory): tmp_path = tmp_path_factory.mktemp("data") cwd = os.getcwd() diff --git a/tests/test_tutorial/test_sql_databases/test_testing_databases_py39.py b/tests/test_tutorial/test_sql_databases/test_testing_databases_py39.py index 0b27adf44a9c5..99bfd3fa8a9da 100644 --- a/tests/test_tutorial/test_sql_databases/test_testing_databases_py39.py +++ b/tests/test_tutorial/test_sql_databases/test_testing_databases_py39.py @@ -4,10 +4,12 @@ import pytest -from ...utils import needs_py39 +from ...utils import needs_py39, needs_pydanticv1 @needs_py39 +# TODO: pv2 add version with Pydantic v2 +@needs_pydanticv1 def test_testing_dbs_py39(tmp_path_factory: pytest.TempPathFactory): tmp_path = tmp_path_factory.mktemp("data") cwd = os.getcwd() diff --git a/tests/test_tutorial/test_sql_databases_peewee/test_sql_databases_peewee.py b/tests/test_tutorial/test_sql_databases_peewee/test_sql_databases_peewee.py deleted file mode 100644 index d2470a2db9248..0000000000000 --- a/tests/test_tutorial/test_sql_databases_peewee/test_sql_databases_peewee.py +++ /dev/null @@ -1,444 +0,0 @@ -import time -from pathlib import Path -from unittest.mock import MagicMock - -import pytest -from fastapi.testclient import TestClient - - -@pytest.fixture(scope="module") -def client(): - # Import while creating the client to create the DB after starting the test session - from docs_src.sql_databases_peewee.sql_app.main import app - - test_db = Path("./test.db") - with TestClient(app) as c: - yield c - test_db.unlink() - - -def test_create_user(client): - test_user = {"email": "johndoe@example.com", "password": "secret"} - response = client.post("/users/", json=test_user) - assert response.status_code == 200, response.text - data = response.json() - assert test_user["email"] == data["email"] - assert "id" in data - response = client.post("/users/", json=test_user) - assert response.status_code == 400, response.text - - -def test_get_user(client): - response = client.get("/users/1") - assert response.status_code == 200, response.text - data = response.json() - assert "email" in data - assert "id" in data - - -def test_inexistent_user(client): - response = client.get("/users/999") - assert response.status_code == 404, response.text - - -def test_get_users(client): - response = client.get("/users/") - assert response.status_code == 200, response.text - data = response.json() - assert "email" in data[0] - assert "id" in data[0] - - -time.sleep = MagicMock() - - -def test_get_slowusers(client): - response = client.get("/slowusers/") - assert response.status_code == 200, response.text - data = response.json() - assert "email" in data[0] - assert "id" in data[0] - - -def test_create_item(client): - item = {"title": "Foo", "description": "Something that fights"} - response = client.post("/users/1/items/", json=item) - assert response.status_code == 200, response.text - item_data = response.json() - assert item["title"] == item_data["title"] - assert item["description"] == item_data["description"] - assert "id" in item_data - assert "owner_id" in item_data - response = client.get("/users/1") - assert response.status_code == 200, response.text - user_data = response.json() - item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0] - assert item_to_check["title"] == item["title"] - assert item_to_check["description"] == item["description"] - response = client.get("/users/1") - assert response.status_code == 200, response.text - user_data = response.json() - item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0] - assert item_to_check["title"] == item["title"] - assert item_to_check["description"] == item["description"] - - -def test_read_items(client): - response = client.get("/items/") - assert response.status_code == 200, response.text - data = response.json() - assert data - first_item = data[0] - assert "title" in first_item - assert "description" in first_item - - -def test_openapi_schema(client): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.0.2", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/users/": { - "get": { - "summary": "Read Users", - "operationId": "read_users_users__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Users Users Get", - "type": "array", - "items": {"$ref": "#/components/schemas/User"}, - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - }, - "post": { - "summary": "Create User", - "operationId": "create_user_users__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/UserCreate"} - } - }, - "required": True, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - }, - }, - "/users/{user_id}": { - "get": { - "summary": "Read User", - "operationId": "read_user_users__user_id__get", - "parameters": [ - { - "required": True, - "schema": {"title": "User Id", "type": "integer"}, - "name": "user_id", - "in": "path", - } - ], - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - "/users/{user_id}/items/": { - "post": { - "summary": "Create Item For User", - "operationId": "create_item_for_user_users__user_id__items__post", - "parameters": [ - { - "required": True, - "schema": {"title": "User Id", "type": "integer"}, - "name": "user_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/ItemCreate"} - } - }, - "required": True, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - "/items/": { - "get": { - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Items Items Get", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - "/slowusers/": { - "get": { - "summary": "Read Slow Users", - "operationId": "read_slow_users_slowusers__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Slow Users Slowusers Get", - "type": "array", - "items": {"$ref": "#/components/schemas/User"}, - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "Item": { - "title": "Item", - "required": ["title", "id", "owner_id"], - "type": "object", - "properties": { - "title": {"title": "Title", "type": "string"}, - "description": {"title": "Description", "type": "string"}, - "id": {"title": "Id", "type": "integer"}, - "owner_id": {"title": "Owner Id", "type": "integer"}, - }, - }, - "ItemCreate": { - "title": "ItemCreate", - "required": ["title"], - "type": "object", - "properties": { - "title": {"title": "Title", "type": "string"}, - "description": {"title": "Description", "type": "string"}, - }, - }, - "User": { - "title": "User", - "required": ["email", "id", "is_active"], - "type": "object", - "properties": { - "email": {"title": "Email", "type": "string"}, - "id": {"title": "Id", "type": "integer"}, - "is_active": {"title": "Is Active", "type": "boolean"}, - "items": { - "title": "Items", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - "default": [], - }, - }, - }, - "UserCreate": { - "title": "UserCreate", - "required": ["email", "password"], - "type": "object", - "properties": { - "email": {"title": "Email", "type": "string"}, - "password": {"title": "Password", "type": "string"}, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_sub_applications/test_tutorial001.py b/tests/test_tutorial/test_sub_applications/test_tutorial001.py index 00e9aec577900..0790d207be10b 100644 --- a/tests/test_tutorial/test_sub_applications/test_tutorial001.py +++ b/tests/test_tutorial/test_sub_applications/test_tutorial001.py @@ -5,7 +5,7 @@ client = TestClient(app) openapi_schema_main = { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/app": { @@ -23,7 +23,7 @@ }, } openapi_schema_sub = { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/sub": { diff --git a/tests/test_tutorial/test_templates/test_tutorial001.py b/tests/test_tutorial/test_templates/test_tutorial001.py index bfee5c0902dbc..4d4729425e845 100644 --- a/tests/test_tutorial/test_templates/test_tutorial001.py +++ b/tests/test_tutorial/test_templates/test_tutorial001.py @@ -16,7 +16,10 @@ def test_main(): client = TestClient(app) response = client.get("/items/foo") assert response.status_code == 200, response.text - assert b"<h1>Item ID: foo</h1>" in response.content + assert ( + b'<h1><a href="http://testserver/items/foo">Item ID: foo</a></h1>' + in response.content + ) response = client.get("/static/styles.css") assert response.status_code == 200, response.text assert b"color: green;" in response.content diff --git a/tests/test_tutorial/test_testing/test_main.py b/tests/test_tutorial/test_testing/test_main.py index 937ce75e42815..fe349808136cf 100644 --- a/tests/test_tutorial/test_testing/test_main.py +++ b/tests/test_tutorial/test_testing/test_main.py @@ -9,7 +9,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/": { diff --git a/tests/test_tutorial/test_testing/test_main_b.py b/tests/test_tutorial/test_testing/test_main_b.py index fc1a832f99620..1e1836f5b362e 100644 --- a/tests/test_tutorial/test_testing/test_main_b.py +++ b/tests/test_tutorial/test_testing/test_main_b.py @@ -5,6 +5,6 @@ def test_app(): test_main.test_create_existing_item() test_main.test_create_item() test_main.test_create_item_bad_token() - test_main.test_read_inexistent_item() + test_main.test_read_nonexistent_item() test_main.test_read_item() test_main.test_read_item_bad_token() diff --git a/tests/test_tutorial/test_testing/test_main_b_an.py b/tests/test_tutorial/test_testing/test_main_b_an.py index b64c5f7107785..e53fc32246cae 100644 --- a/tests/test_tutorial/test_testing/test_main_b_an.py +++ b/tests/test_tutorial/test_testing/test_main_b_an.py @@ -5,6 +5,6 @@ def test_app(): test_main.test_create_existing_item() test_main.test_create_item() test_main.test_create_item_bad_token() - test_main.test_read_inexistent_item() + test_main.test_read_nonexistent_item() test_main.test_read_item() test_main.test_read_item_bad_token() diff --git a/tests/test_tutorial/test_testing/test_main_b_an_py310.py b/tests/test_tutorial/test_testing/test_main_b_an_py310.py index 194700b6dd0e6..c974e5dc1e520 100644 --- a/tests/test_tutorial/test_testing/test_main_b_an_py310.py +++ b/tests/test_tutorial/test_testing/test_main_b_an_py310.py @@ -8,6 +8,6 @@ def test_app(): test_main.test_create_existing_item() test_main.test_create_item() test_main.test_create_item_bad_token() - test_main.test_read_inexistent_item() + test_main.test_read_nonexistent_item() test_main.test_read_item() test_main.test_read_item_bad_token() diff --git a/tests/test_tutorial/test_testing/test_main_b_an_py39.py b/tests/test_tutorial/test_testing/test_main_b_an_py39.py index 2f8a13623fceb..71f99726c90f4 100644 --- a/tests/test_tutorial/test_testing/test_main_b_an_py39.py +++ b/tests/test_tutorial/test_testing/test_main_b_an_py39.py @@ -8,6 +8,6 @@ def test_app(): test_main.test_create_existing_item() test_main.test_create_item() test_main.test_create_item_bad_token() - test_main.test_read_inexistent_item() + test_main.test_read_nonexistent_item() test_main.test_read_item() test_main.test_read_item_bad_token() diff --git a/tests/test_tutorial/test_testing/test_main_b_py310.py b/tests/test_tutorial/test_testing/test_main_b_py310.py index a504ed2346edf..e30cdc073ea36 100644 --- a/tests/test_tutorial/test_testing/test_main_b_py310.py +++ b/tests/test_tutorial/test_testing/test_main_b_py310.py @@ -8,6 +8,6 @@ def test_app(): test_main.test_create_existing_item() test_main.test_create_item() test_main.test_create_item_bad_token() - test_main.test_read_inexistent_item() + test_main.test_read_nonexistent_item() test_main.test_read_item() test_main.test_read_item_bad_token() diff --git a/tests/test_tutorial/test_testing/test_tutorial001.py b/tests/test_tutorial/test_testing/test_tutorial001.py index f3db70af2baca..471e896c93cac 100644 --- a/tests/test_tutorial/test_testing/test_tutorial001.py +++ b/tests/test_tutorial/test_testing/test_tutorial001.py @@ -9,7 +9,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/": { diff --git a/tests/test_tutorial/test_testing/test_tutorial003.py b/tests/test_tutorial/test_testing/test_tutorial003.py index d9e16390ed4ec..2a5d67071260f 100644 --- a/tests/test_tutorial/test_testing/test_tutorial003.py +++ b/tests/test_tutorial/test_testing/test_tutorial003.py @@ -1,5 +1,7 @@ -from docs_src.app_testing.tutorial003 import test_read_items +import pytest def test_main(): + with pytest.warns(DeprecationWarning): + from docs_src.app_testing.tutorial003 import test_read_items test_read_items() diff --git a/tests/test_union_body.py b/tests/test_union_body.py index bc1e744328aef..c15acacd18d3d 100644 --- a/tests/test_union_body.py +++ b/tests/test_union_body.py @@ -1,5 +1,6 @@ from typing import Optional, Union +from dirty_equals import IsDict from fastapi import FastAPI from fastapi.testclient import TestClient from pydantic import BaseModel @@ -39,7 +40,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { @@ -90,7 +91,18 @@ def test_openapi_schema(): "Item": { "title": "Item", "type": "object", - "properties": {"name": {"title": "Name", "type": "string"}}, + "properties": IsDict( + { + "name": { + "title": "Name", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"name": {"title": "Name", "type": "string"}} + ), }, "ValidationError": { "title": "ValidationError", diff --git a/tests/test_union_inherited_body.py b/tests/test_union_inherited_body.py index 988b920aa77ad..ef75d459ead1f 100644 --- a/tests/test_union_inherited_body.py +++ b/tests/test_union_inherited_body.py @@ -1,5 +1,6 @@ from typing import Optional, Union +from dirty_equals import IsDict from fastapi import FastAPI from fastapi.testclient import TestClient from pydantic import BaseModel @@ -39,7 +40,7 @@ def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { @@ -84,14 +85,34 @@ def test_openapi_schema(): "Item": { "title": "Item", "type": "object", - "properties": {"name": {"title": "Name", "type": "string"}}, + "properties": { + "name": IsDict( + { + "title": "Name", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Name", "type": "string"} + ) + }, }, "ExtendedItem": { "title": "ExtendedItem", "required": ["age"], "type": "object", "properties": { - "name": {"title": "Name", "type": "string"}, + "name": IsDict( + { + "title": "Name", + "anyOf": [{"type": "string"}, {"type": "null"}], + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + {"title": "Name", "type": "string"} + ), "age": {"title": "Age", "type": "integer"}, }, }, diff --git a/tests/test_validate_response.py b/tests/test_validate_response.py index 62f51c960ded3..cd97007a44814 100644 --- a/tests/test_validate_response.py +++ b/tests/test_validate_response.py @@ -2,8 +2,9 @@ import pytest from fastapi import FastAPI +from fastapi.exceptions import ResponseValidationError from fastapi.testclient import TestClient -from pydantic import BaseModel, ValidationError +from pydantic import BaseModel app = FastAPI() @@ -50,12 +51,12 @@ def get_invalidlist(): def test_invalid(): - with pytest.raises(ValidationError): + with pytest.raises(ResponseValidationError): client.get("/items/invalid") def test_invalid_none(): - with pytest.raises(ValidationError): + with pytest.raises(ResponseValidationError): client.get("/items/invalidnone") @@ -74,10 +75,10 @@ def test_valid_none_none(): def test_double_invalid(): - with pytest.raises(ValidationError): + with pytest.raises(ResponseValidationError): client.get("/items/innerinvalid") def test_invalid_list(): - with pytest.raises(ValidationError): + with pytest.raises(ResponseValidationError): client.get("/items/invalidlist") diff --git a/tests/test_validate_response_dataclass.py b/tests/test_validate_response_dataclass.py index f2cfa7a11b46d..0415988a0b8b5 100644 --- a/tests/test_validate_response_dataclass.py +++ b/tests/test_validate_response_dataclass.py @@ -2,8 +2,8 @@ import pytest from fastapi import FastAPI +from fastapi.exceptions import ResponseValidationError from fastapi.testclient import TestClient -from pydantic import ValidationError from pydantic.dataclasses import dataclass app = FastAPI() @@ -39,15 +39,15 @@ def get_invalidlist(): def test_invalid(): - with pytest.raises(ValidationError): + with pytest.raises(ResponseValidationError): client.get("/items/invalid") def test_double_invalid(): - with pytest.raises(ValidationError): + with pytest.raises(ResponseValidationError): client.get("/items/innerinvalid") def test_invalid_list(): - with pytest.raises(ValidationError): + with pytest.raises(ResponseValidationError): client.get("/items/invalidlist") diff --git a/tests/test_validate_response_recursive/__init__.py b/tests/test_validate_response_recursive/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/tests/test_validate_response_recursive.py b/tests/test_validate_response_recursive/app_pv1.py similarity index 58% rename from tests/test_validate_response_recursive.py rename to tests/test_validate_response_recursive/app_pv1.py index 3a4b10e0ca9f4..4cfc4b3eef1fc 100644 --- a/tests/test_validate_response_recursive.py +++ b/tests/test_validate_response_recursive/app_pv1.py @@ -1,7 +1,6 @@ from typing import List from fastapi import FastAPI -from fastapi.testclient import TestClient from pydantic import BaseModel app = FastAPI() @@ -49,32 +48,3 @@ def get_recursive_submodel(): } ], } - - -client = TestClient(app) - - -def test_recursive(): - response = client.get("/items/recursive") - assert response.status_code == 200, response.text - assert response.json() == { - "sub_items": [{"name": "subitem", "sub_items": []}], - "name": "item", - } - - response = client.get("/items/recursive-submodel") - assert response.status_code == 200, response.text - assert response.json() == { - "name": "item", - "sub_items1": [ - { - "name": "subitem", - "sub_items2": [ - { - "name": "subsubitem", - "sub_items1": [{"name": "subsubsubitem", "sub_items2": []}], - } - ], - } - ], - } diff --git a/tests/test_validate_response_recursive/app_pv2.py b/tests/test_validate_response_recursive/app_pv2.py new file mode 100644 index 0000000000000..8c93a834901e9 --- /dev/null +++ b/tests/test_validate_response_recursive/app_pv2.py @@ -0,0 +1,51 @@ +from typing import List + +from fastapi import FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class RecursiveItem(BaseModel): + sub_items: List["RecursiveItem"] = [] + name: str + + +RecursiveItem.model_rebuild() + + +class RecursiveSubitemInSubmodel(BaseModel): + sub_items2: List["RecursiveItemViaSubmodel"] = [] + name: str + + +class RecursiveItemViaSubmodel(BaseModel): + sub_items1: List[RecursiveSubitemInSubmodel] = [] + name: str + + +RecursiveSubitemInSubmodel.model_rebuild() +RecursiveItemViaSubmodel.model_rebuild() + + +@app.get("/items/recursive", response_model=RecursiveItem) +def get_recursive(): + return {"name": "item", "sub_items": [{"name": "subitem", "sub_items": []}]} + + +@app.get("/items/recursive-submodel", response_model=RecursiveItemViaSubmodel) +def get_recursive_submodel(): + return { + "name": "item", + "sub_items1": [ + { + "name": "subitem", + "sub_items2": [ + { + "name": "subsubitem", + "sub_items1": [{"name": "subsubsubitem", "sub_items2": []}], + } + ], + } + ], + } diff --git a/tests/test_validate_response_recursive/test_validate_response_recursive_pv1.py b/tests/test_validate_response_recursive/test_validate_response_recursive_pv1.py new file mode 100644 index 0000000000000..de578ae03120c --- /dev/null +++ b/tests/test_validate_response_recursive/test_validate_response_recursive_pv1.py @@ -0,0 +1,33 @@ +from fastapi.testclient import TestClient + +from ..utils import needs_pydanticv1 + + +@needs_pydanticv1 +def test_recursive(): + from .app_pv1 import app + + client = TestClient(app) + response = client.get("/items/recursive") + assert response.status_code == 200, response.text + assert response.json() == { + "sub_items": [{"name": "subitem", "sub_items": []}], + "name": "item", + } + + response = client.get("/items/recursive-submodel") + assert response.status_code == 200, response.text + assert response.json() == { + "name": "item", + "sub_items1": [ + { + "name": "subitem", + "sub_items2": [ + { + "name": "subsubitem", + "sub_items1": [{"name": "subsubsubitem", "sub_items2": []}], + } + ], + } + ], + } diff --git a/tests/test_validate_response_recursive/test_validate_response_recursive_pv2.py b/tests/test_validate_response_recursive/test_validate_response_recursive_pv2.py new file mode 100644 index 0000000000000..7d45e7fe402f8 --- /dev/null +++ b/tests/test_validate_response_recursive/test_validate_response_recursive_pv2.py @@ -0,0 +1,33 @@ +from fastapi.testclient import TestClient + +from ..utils import needs_pydanticv2 + + +@needs_pydanticv2 +def test_recursive(): + from .app_pv2 import app + + client = TestClient(app) + response = client.get("/items/recursive") + assert response.status_code == 200, response.text + assert response.json() == { + "sub_items": [{"name": "subitem", "sub_items": []}], + "name": "item", + } + + response = client.get("/items/recursive-submodel") + assert response.status_code == 200, response.text + assert response.json() == { + "name": "item", + "sub_items1": [ + { + "name": "subitem", + "sub_items2": [ + { + "name": "subsubitem", + "sub_items1": [{"name": "subsubsubitem", "sub_items2": []}], + } + ], + } + ], + } diff --git a/tests/test_webhooks_security.py b/tests/test_webhooks_security.py new file mode 100644 index 0000000000000..21a694cb5420f --- /dev/null +++ b/tests/test_webhooks_security.py @@ -0,0 +1,126 @@ +from datetime import datetime + +from fastapi import FastAPI, Security +from fastapi.security import HTTPBearer +from fastapi.testclient import TestClient +from pydantic import BaseModel +from typing_extensions import Annotated + +app = FastAPI() + +bearer_scheme = HTTPBearer() + + +class Subscription(BaseModel): + username: str + monthly_fee: float + start_date: datetime + + +@app.webhooks.post("new-subscription") +def new_subscription( + body: Subscription, token: Annotated[str, Security(bearer_scheme)] +): + """ + When a new user subscribes to your service we'll send you a POST request with this + data to the URL that you register for the event `new-subscription` in the dashboard. + """ + + +client = TestClient(app) + + +def test_dummy_webhook(): + # Just for coverage + new_subscription(body={}, token="Bearer 123") + + +def test_openapi_schema(): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + # insert_assert(response.json()) + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": {}, + "webhooks": { + "new-subscription": { + "post": { + "summary": "New Subscription", + "description": "When a new user subscribes to your service we'll send you a POST request with this\ndata to the URL that you register for the event `new-subscription` in the dashboard.", + "operationId": "new_subscriptionnew_subscription_post", + "requestBody": { + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Subscription"} + } + }, + "required": True, + }, + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + "security": [{"HTTPBearer": []}], + } + } + }, + "components": { + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": {"$ref": "#/components/schemas/ValidationError"}, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "Subscription": { + "properties": { + "username": {"type": "string", "title": "Username"}, + "monthly_fee": {"type": "number", "title": "Monthly Fee"}, + "start_date": { + "type": "string", + "format": "date-time", + "title": "Start Date", + }, + }, + "type": "object", + "required": ["username", "monthly_fee", "start_date"], + "title": "Subscription", + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + }, + "securitySchemes": {"HTTPBearer": {"type": "http", "scheme": "bearer"}}, + }, + } diff --git a/tests/utils.py b/tests/utils.py index 5305424c4563b..460c028f7f2a9 100644 --- a/tests/utils.py +++ b/tests/utils.py @@ -1,8 +1,11 @@ import sys import pytest +from fastapi._compat import PYDANTIC_V2 needs_py39 = pytest.mark.skipif(sys.version_info < (3, 9), reason="requires python3.9+") needs_py310 = pytest.mark.skipif( sys.version_info < (3, 10), reason="requires python3.10+" ) +needs_pydanticv2 = pytest.mark.skipif(not PYDANTIC_V2, reason="requires Pydantic v2") +needs_pydanticv1 = pytest.mark.skipif(PYDANTIC_V2, reason="requires Pydantic v1")