diff --git a/.github/DISCUSSION_TEMPLATE/questions.yml b/.github/DISCUSSION_TEMPLATE/questions.yml
index 3726b7d18..98424a341 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/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml
index a8f4c4de2..fd9f3b11c 100644
--- a/.github/ISSUE_TEMPLATE/config.yml
+++ b/.github/ISSUE_TEMPLATE/config.yml
@@ -4,13 +4,13 @@ contact_links:
about: Please report security vulnerabilities to security@tiangolo.com
- name: Question or Problem
about: Ask a question or ask about a problem in GitHub Discussions.
- url: https://github.com/tiangolo/fastapi/discussions/categories/questions
+ url: https://github.com/fastapi/fastapi/discussions/categories/questions
- name: Feature Request
about: To suggest an idea or ask about a feature, please start with a question saying what you would like to achieve. There might be a way to do it already.
- url: https://github.com/tiangolo/fastapi/discussions/categories/questions
+ url: https://github.com/fastapi/fastapi/discussions/categories/questions
- name: Show and tell
about: Show what you built with FastAPI or to be used with FastAPI.
- url: https://github.com/tiangolo/fastapi/discussions/categories/show-and-tell
+ url: https://github.com/fastapi/fastapi/discussions/categories/show-and-tell
- name: Translations
about: Coordinate translations in GitHub Discussions.
- url: https://github.com/tiangolo/fastapi/discussions/categories/translations
+ url: https://github.com/fastapi/fastapi/discussions/categories/translations
diff --git a/.github/ISSUE_TEMPLATE/privileged.yml b/.github/ISSUE_TEMPLATE/privileged.yml
index c01e34b6d..2b85eb310 100644
--- a/.github/ISSUE_TEMPLATE/privileged.yml
+++ b/.github/ISSUE_TEMPLATE/privileged.yml
@@ -6,7 +6,7 @@ body:
value: |
Thanks for your interest in FastAPI! 🚀
- If you are not @tiangolo or he didn't ask you directly to create an issue here, please start the conversation in a [Question in GitHub Discussions](https://github.com/tiangolo/fastapi/discussions/categories/questions) instead.
+ If you are not @tiangolo or he didn't ask you directly to create an issue here, please start the conversation in a [Question in GitHub Discussions](https://github.com/fastapi/fastapi/discussions/categories/questions) instead.
- type: checkboxes
id: privileged
attributes:
diff --git a/.github/actions/comment-docs-preview-in-pr/Dockerfile b/.github/actions/comment-docs-preview-in-pr/Dockerfile
deleted file mode 100644
index 4f20c5f10..000000000
--- a/.github/actions/comment-docs-preview-in-pr/Dockerfile
+++ /dev/null
@@ -1,7 +0,0 @@
-FROM python:3.7
-
-RUN pip install httpx "pydantic==1.5.1" pygithub
-
-COPY ./app /app
-
-CMD ["python", "/app/main.py"]
diff --git a/.github/actions/comment-docs-preview-in-pr/action.yml b/.github/actions/comment-docs-preview-in-pr/action.yml
deleted file mode 100644
index 0eb64402d..000000000
--- a/.github/actions/comment-docs-preview-in-pr/action.yml
+++ /dev/null
@@ -1,13 +0,0 @@
-name: Comment Docs Preview in PR
-description: Comment with the docs URL preview in the PR
-author: Sebastián Ramírez
-
-
+
+
-
-
+
+
@@ -23,11 +23,11 @@
**Documentation**: https://fastapi.tiangolo.com
-**Source Code**: https://github.com/tiangolo/fastapi
+**Source Code**: https://github.com/fastapi/fastapi
---
-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 based on standard Python type hints.
The key features are:
@@ -46,15 +46,22 @@ The key features are:
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
@@ -64,7 +71,7 @@ The key features are:
"_[...] 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._"
-
uvicorn main:app --reload
...fastapi dev main.py
...ujson
- for faster JSON "parsing".
-* email_validator
- for email validation.
+* email-validator
- for email validation.
Used by Starlette:
* httpx
- Required if you want to use the `TestClient`.
* jinja2
- Required if you want to use the default template configuration.
-* python-multipart
- Required if you want to support form "parsing", with `request.form()`.
-* itsdangerous
- Required for `SessionMiddleware` support.
-* pyyaml
- Required for Starlette's `SchemaGenerator` support (you probably don't need it with FastAPI).
-* ujson
- Required if you want to use `UJSONResponse`.
+* python-multipart
- Required if you want to support form "parsing", with `request.form()`.
Used by FastAPI / Starlette:
-* uvicorn
- for the server that loads and serves your application.
-* orjson
- Required if you want to use `ORJSONResponse`.
+* uvicorn
- for the server that loads and serves your application. This includes `uvicorn[standard]`, which includes some dependencies (e.g. `uvloop`) needed for high performance serving.
+* `fastapi-cli` - to provide the `fastapi` command.
+
+### Without `standard` Dependencies
+
+If you don't want to include the `standard` optional dependencies, you can install with `pip install fastapi` instead of `pip install "fastapi[standard]"`.
-You can install all of these with `pip install "fastapi[all]"`.
+### Additional Optional Dependencies
+
+There are some additional dependencies you might want to install.
+
+Additional optional Pydantic dependencies:
+
+* pydantic-settings
- for settings management.
+* pydantic-extra-types
- for extra types to be used with Pydantic.
+
+Additional optional FastAPI dependencies:
+
+* orjson
- Required if you want to use `ORJSONResponse`.
+* ujson
- Required if you want to use `UJSONResponse`.
## License
diff --git a/docs/az/docs/index.md b/docs/az/docs/index.md
index 282c15032..fbbbce130 100644
--- a/docs/az/docs/index.md
+++ b/docs/az/docs/index.md
@@ -1,57 +1,55 @@
-
-{!../../../docs/missing-translation.md!}
-
-
- FastAPI framework, high performance, easy to learn, fast to code, ready for production + FastAPI framework, yüksək məshuldarlı, öyrənməsi asan, çevik kodlama, istifadəyə hazırdır
--- -**Documentation**: https://fastapi.tiangolo.com +**Sənədlər**: https://fastapi.tiangolo.com -**Source Code**: https://github.com/tiangolo/fastapi +**Qaynaq Kodu**: https://github.com/fastapi/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: +FastAPI Python 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. -* **Fast**: Very high performance, on par with **NodeJS** and **Go** (thanks to Starlette and Pydantic). [One of the fastest Python frameworks available](#performance). +Əsas xüsusiyyətləri bunlardır: -* **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. +* **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. -* estimation based on tests on an internal development team, building production applications. +* Bu fikirlər daxili development komandasının hazırladıqları məhsulların sınaqlarına əsaslanır. -## Sponsors +## Sponsorlar {% if sponsors %} {% for sponsor in sponsors.gold -%}async def
...async def
...uvicorn main:app --reload
...uvicorn main:app --reload
əmri haqqında...ujson
- for faster JSON "parsing".
-* email_validator
- for email validation.
+* 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.
-Used by Starlette:
+Starlette tərəfindən istifadə olunanlar:
-* 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`.
+* 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.
-Used by FastAPI / Starlette:
+Həm FastAPI, həm də Starlette tərəfindən istifadə olunur:
-* uvicorn
- for the server that loads and serves your application.
-* orjson
- Required if you want to use `ORJSONResponse`.
+* 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.
-You can install all of these with `pip install fastapi[all]`.
+Bütün bunları `pip install fastapi[all]` ilə quraşdıra bilərsiniz.
-## License
+## Lisenziya
-This project is licensed under the terms of the MIT license.
+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 000000000..cc32108bf
--- /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
index 22a77c6e2..de18856f4 100644
--- a/docs/az/mkdocs.yml
+++ b/docs/az/mkdocs.yml
@@ -1,157 +1 @@
-site_name: FastAPI
-site_description: FastAPI framework, high performance, easy to learn, fast to code, ready for production
-site_url: https://fastapi.tiangolo.com/az/
-theme:
- name: material
- custom_dir: overrides
- palette:
- - media: '(prefers-color-scheme: light)'
- scheme: default
- primary: teal
- accent: amber
- toggle:
- icon: material/lightbulb
- name: Switch to light mode
- - media: '(prefers-color-scheme: dark)'
- scheme: slate
- primary: teal
- accent: amber
- toggle:
- icon: material/lightbulb-outline
- name: Switch to dark mode
- features:
- - search.suggest
- - search.highlight
- - content.tabs.link
- icon:
- repo: fontawesome/brands/github-alt
- logo: https://fastapi.tiangolo.com/img/icon-white.svg
- favicon: https://fastapi.tiangolo.com/img/favicon.png
- language: en
-repo_name: tiangolo/fastapi
-repo_url: https://github.com/tiangolo/fastapi
-edit_uri: ''
-plugins:
-- search
-- markdownextradata:
- data: data
-nav:
-- FastAPI: index.md
-- Languages:
- - en: /
- - az: /az/
- - cs: /cs/
- - de: /de/
- - em: /em/
- - es: /es/
- - fa: /fa/
- - fr: /fr/
- - he: /he/
- - hy: /hy/
- - id: /id/
- - it: /it/
- - ja: /ja/
- - ko: /ko/
- - nl: /nl/
- - pl: /pl/
- - pt: /pt/
- - ru: /ru/
- - sq: /sq/
- - sv: /sv/
- - ta: /ta/
- - tr: /tr/
- - uk: /uk/
- - zh: /zh/
-markdown_extensions:
-- toc:
- permalink: true
-- markdown.extensions.codehilite:
- guess_lang: false
-- mdx_include:
- base_path: docs
-- admonition
-- codehilite
-- extra
-- pymdownx.superfences:
- custom_fences:
- - name: mermaid
- class: mermaid
- format: !!python/name:pymdownx.superfences.fence_code_format ''
-- pymdownx.tabbed:
- alternate_style: true
-- attr_list
-- md_in_html
-extra:
- analytics:
- provider: google
- property: G-YNEVN69SC3
- social:
- - icon: fontawesome/brands/github-alt
- link: https://github.com/tiangolo/fastapi
- - icon: fontawesome/brands/discord
- link: https://discord.gg/VQjSZaeJmf
- - icon: fontawesome/brands/twitter
- link: https://twitter.com/fastapi
- - icon: fontawesome/brands/linkedin
- link: https://www.linkedin.com/in/tiangolo
- - icon: fontawesome/brands/dev
- link: https://dev.to/tiangolo
- - icon: fontawesome/brands/medium
- link: https://medium.com/@tiangolo
- - icon: fontawesome/solid/globe
- link: https://tiangolo.com
- alternate:
- - link: /
- name: en - English
- - link: /az/
- name: az
- - link: /cs/
- name: cs
- - link: /de/
- name: de
- - link: /em/
- name: 😉
- - link: /es/
- name: es - español
- - link: /fa/
- name: fa
- - link: /fr/
- name: fr - français
- - link: /he/
- name: he
- - link: /hy/
- name: hy
- - link: /id/
- name: id
- - link: /it/
- name: it - italiano
- - link: /ja/
- name: ja - 日本語
- - link: /ko/
- name: ko - 한국어
- - link: /nl/
- name: nl
- - link: /pl/
- name: pl
- - link: /pt/
- name: pt - português
- - link: /ru/
- name: ru - русский язык
- - link: /sq/
- name: sq - shqip
- - link: /sv/
- name: sv - svenska
- - link: /ta/
- name: ta - தமிழ்
- - link: /tr/
- name: tr - Türkçe
- - link: /uk/
- name: uk - українська мова
- - link: /zh/
- name: zh - 汉语
-extra_css:
-- https://fastapi.tiangolo.com/css/termynal.css
-- https://fastapi.tiangolo.com/css/custom.css
-extra_javascript:
-- https://fastapi.tiangolo.com/js/termynal.js
-- https://fastapi.tiangolo.com/js/custom.js
+INHERIT: ../en/mkdocs.yml
diff --git a/docs/bn/docs/environment-variables.md b/docs/bn/docs/environment-variables.md
new file mode 100644
index 000000000..9122ca5bf
--- /dev/null
+++ b/docs/bn/docs/environment-variables.md
@@ -0,0 +1,298 @@
+# এনভায়রনমেন্ট ভেরিয়েবলস
+
+/// tip
+
+আপনি যদি "এনভায়রনমেন্ট ভেরিয়েবলস" কী এবং সেগুলো কীভাবে ব্যবহার করতে হয় সেটা জানেন, তাহলে এই অংশটি স্কিপ করে যেতে পারেন।
+
+///
+
+এনভায়রনমেন্ট ভেরিয়েবল (সংক্ষেপে "**env var**" নামেও পরিচিত) হলো এমন একটি ভেরিয়েবল যা পাইথন কোডের **বাইরে**, **অপারেটিং সিস্টেমে** থাকে এবং আপনার পাইথন কোড (বা অন্যান্য প্রোগ্রাম) দ্বারা যাকে রিড করা যায়।
+
+এনভায়রনমেন্ট ভেরিয়েবলস অ্যাপ্লিকেশনের **সেটিংস** পরিচালনা করতে, পাইথনের **ইনস্টলেশন** প্রক্রিয়ার অংশ হিসেবে, ইত্যাদি কাজে উপযোগী হতে পারে।
+
+## Env Vars তৈরী এবং ব্যবহার
+
+আপনি **শেল (টার্মিনাল)**-এ, পাইথনের প্রয়োজন ছাড়াই, এনভায়রনমেন্ট ভেরিয়েবলস **তৈরি** এবং ব্যবহার করতে পারবেনঃ
+
+//// tab | লিনাক্স, ম্যাকওএস, উইন্ডোজ Bash
+
++ FastAPI উচ্চক্ষমতা সম্পন্ন, সহজে শেখার এবং দ্রুত কোড করে প্রোডাকশনের জন্য ফ্রামওয়ার্ক। +
+ + +--- + +**নির্দেশিকা নথি**: https://fastapi.tiangolo.com + +**সোর্স কোড**: https://github.com/fastapi/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 -%} +async def
...uvicorn main:app --reload
...email-validator
- ইমেল যাচাইকরণের জন্য।
+
+স্টারলেট দ্বারা ব্যবহৃত:
+
+- httpx
- আপনি যদি `TestClient` ব্যবহার করতে চান তাহলে আবশ্যক।
+- jinja2
- আপনি যদি প্রদত্ত টেমপ্লেট রূপরেখা ব্যবহার করতে চান তাহলে প্রয়োজন।
+- python-multipart
- আপনি যদি ফর্ম সহায়তা করতে চান তাহলে প্রয়োজন "parsing", `request.form()` সহ।
+- itsdangerous
- `SessionMiddleware` সহায়তার জন্য প্রয়োজন।
+- pyyaml
- স্টারলেটের SchemaGenerator সাপোর্ট এর জন্য প্রয়োজন (আপনার সম্ভাবত FastAPI প্রয়োজন নেই)।
+- graphene
- `GraphQLApp` সহায়তার জন্য প্রয়োজন।
+
+FastAPI / Starlette দ্বারা ব্যবহৃত:
+
+- uvicorn
- সার্ভারের জন্য যা আপনার অ্যাপ্লিকেশন লোড করে এবং পরিবেশন করে।
+- orjson
- আপনি `ORJSONResponse` ব্যবহার করতে চাইলে প্রয়োজন।
+- ujson
- আপনি `UJSONResponse` ব্যবহার করতে চাইলে প্রয়োজন।
+
+আপনি এই সব ইনস্টল করতে পারেন `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 000000000..4e4c62038
--- /dev/null
+++ b/docs/bn/docs/learn/index.md
@@ -0,0 +1,5 @@
+# শিখুন
+
+এখানে **FastAPI** শিখার জন্য প্রাথমিক বিভাগগুলি এবং টিউটোরিয়ালগুলি রয়েছে।
+
+আপনি এটিকে একটি **বই**, একটি **কোর্স**, এবং FastAPI শিখার **অফিসিয়াল** এবং প্রস্তাবিত উপায় বিবেচনা করতে পারেন। 😎
diff --git a/docs/bn/docs/python-types.md b/docs/bn/docs/python-types.md
new file mode 100644
index 000000000..d98c2ec87
--- /dev/null
+++ b/docs/bn/docs/python-types.md
@@ -0,0 +1,586 @@
+# পাইথন এর টাইপ্স পরিচিতি
+
+Python-এ ঐচ্ছিক "টাইপ হিন্ট" (যা "টাইপ অ্যানোটেশন" নামেও পরিচিত) এর জন্য সাপোর্ট রয়েছে।
+
+এই **"টাইপ হিন্ট"** বা অ্যানোটেশনগুলি এক ধরণের বিশেষ সিনট্যাক্স যা একটি ভেরিয়েবলের টাইপ ঘোষণা করতে দেয়।
+
+ভেরিয়েবলগুলির জন্য টাইপ ঘোষণা করলে, এডিটর এবং টুলগুলি আপনাকে আরও ভালো সাপোর্ট দিতে পারে।
+
+এটি পাইথন টাইপ হিন্ট সম্পর্কে একটি দ্রুত **টিউটোরিয়াল / রিফ্রেশার** মাত্র। এটি **FastAPI** এর সাথে ব্যবহার করার জন্য শুধুমাত্র ন্যূনতম প্রয়োজনীয়তা কভার করে... যা আসলে খুব একটা বেশি না।
+
+**FastAPI** এই টাইপ হিন্টগুলির উপর ভিত্তি করে নির্মিত, যা এটিকে অনেক সুবিধা এবং লাভ প্রদান করে।
+
+তবে, আপনি যদি কখনো **FastAPI** ব্যবহার নাও করেন, তবুও এগুলি সম্পর্কে একটু শেখা আপনার উপকারে আসবে।
+
+/// note
+
+যদি আপনি একজন Python বিশেষজ্ঞ হন, এবং টাইপ হিন্ট সম্পর্কে সবকিছু জানেন, তাহলে পরবর্তী অধ্যায়ে চলে যান।
+
+///
+
+## প্রেরণা
+
+চলুন একটি সাধারণ উদাহরণ দিয়ে শুরু করি:
+
+{* ../../docs_src/python_types/tutorial001.py *}
+
+
+এই প্রোগ্রামটি কল করলে আউটপুট হয়:
+
+```
+John Doe
+```
+
+ফাংশনটি নিম্নলিখিত কাজ করে:
+
+* `first_name` এবং `last_name` নেয়।
+* প্রতিটির প্রথম অক্ষরকে `title()` ব্যবহার করে বড় হাতের অক্ষরে রূপান্তর করে।
+* তাদেরকে মাঝখানে একটি স্পেস দিয়ে concatenate করে।
+
+{* ../../docs_src/python_types/tutorial001.py hl[2] *}
+
+
+### এটি সম্পাদনা করুন
+
+এটি একটি খুব সাধারণ প্রোগ্রাম।
+
+কিন্তু এখন কল্পনা করুন যে আপনি এটি শুরু থেকে লিখছিলেন।
+
+এক পর্যায়ে আপনি ফাংশনের সংজ্ঞা শুরু করেছিলেন, আপনার প্যারামিটারগুলি প্রস্তুত ছিল...
+
+কিন্তু তারপর আপনাকে "সেই method কল করতে হবে যা প্রথম অক্ষরকে বড় হাতের অক্ষরে রূপান্তর করে"।
+
+এটা কি `upper` ছিল? নাকি `uppercase`? `first_uppercase`? `capitalize`?
+
+তারপর, আপনি পুরোনো প্রোগ্রামারের বন্ধু, এডিটর অটোকমপ্লিশনের সাহায্যে নেওয়ার চেষ্টা করেন।
+
+আপনি ফাংশনের প্রথম প্যারামিটার `first_name` টাইপ করেন, তারপর একটি ডট (`.`) টাইপ করেন এবং `Ctrl+Space` চাপেন অটোকমপ্লিশন ট্রিগার করার জন্য।
+
+কিন্তু, দুর্ভাগ্যবশত, আপনি কিছুই উপযোগী পান না:
+
+- FastAPI framework, high performance, easy to learn, fast to code, ready for production -
- - ---- - -**Documentation**: https://fastapi.tiangolo.com - -**Source Code**: https://github.com/tiangolo/fastapi - ---- - -FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints. - -The key features are: - -* **Fast**: Very high performance, on par with **NodeJS** and **Go** (thanks to Starlette and Pydantic). [One of the fastest Python frameworks available](#performance). -* **Fast to code**: Increase the speed to develop features by about 200% to 300%. * -* **Fewer bugs**: Reduce about 40% of human (developer) induced errors. * -* **Intuitive**: Great editor support. Completion everywhere. Less time debugging. -* **Easy**: Designed to be easy to use and learn. Less time reading docs. -* **Short**: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs. -* **Robust**: Get production-ready code. With automatic interactive documentation. -* **Standards-based**: Based on (and fully compatible with) the open standards for APIs: OpenAPI (previously known as Swagger) and JSON Schema. - -* estimation based on tests on an internal development team, building production applications. - -## Sponsors - - - -{% if sponsors %} -{% for sponsor in sponsors.gold -%} -async def
...uvicorn main:app --reload
...ujson
- for faster JSON "parsing".
-* email_validator
- for email validation.
-
-Used by Starlette:
-
-* httpx
- Required if you want to use the `TestClient`.
-* jinja2
- Required if you want to use the default template configuration.
-* python-multipart
- Required if you want to support form "parsing", with `request.form()`.
-* itsdangerous
- Required for `SessionMiddleware` support.
-* pyyaml
- Required for Starlette's `SchemaGenerator` support (you probably don't need it with FastAPI).
-* ujson
- Required if you want to use `UJSONResponse`.
-
-Used by FastAPI / Starlette:
-
-* uvicorn
- for the server that loads and serves your application.
-* orjson
- Required if you want to use `ORJSONResponse`.
-
-You can install all of these with `pip install "fastapi[all]"`.
-
-## License
-
-This project is licensed under the terms of the MIT license.
diff --git a/docs/cs/mkdocs.yml b/docs/cs/mkdocs.yml
deleted file mode 100644
index 539d7d65d..000000000
--- a/docs/cs/mkdocs.yml
+++ /dev/null
@@ -1,154 +0,0 @@
-site_name: FastAPI
-site_description: FastAPI framework, high performance, easy to learn, fast to code, ready for production
-site_url: https://fastapi.tiangolo.com/cs/
-theme:
- name: material
- custom_dir: overrides
- palette:
- - media: '(prefers-color-scheme: light)'
- scheme: default
- primary: teal
- accent: amber
- toggle:
- icon: material/lightbulb
- name: Switch to light mode
- - media: '(prefers-color-scheme: dark)'
- scheme: slate
- primary: teal
- accent: amber
- toggle:
- icon: material/lightbulb-outline
- name: Switch to dark mode
- features:
- - search.suggest
- - search.highlight
- - content.tabs.link
- icon:
- repo: fontawesome/brands/github-alt
- logo: https://fastapi.tiangolo.com/img/icon-white.svg
- favicon: https://fastapi.tiangolo.com/img/favicon.png
- language: cs
-repo_name: tiangolo/fastapi
-repo_url: https://github.com/tiangolo/fastapi
-edit_uri: ''
-plugins:
-- search
-- markdownextradata:
- data: data
-nav:
-- FastAPI: index.md
-- Languages:
- - en: /
- - az: /az/
- - cs: /cs/
- - de: /de/
- - es: /es/
- - fa: /fa/
- - fr: /fr/
- - he: /he/
- - hy: /hy/
- - id: /id/
- - it: /it/
- - ja: /ja/
- - ko: /ko/
- - nl: /nl/
- - pl: /pl/
- - pt: /pt/
- - ru: /ru/
- - sq: /sq/
- - sv: /sv/
- - ta: /ta/
- - tr: /tr/
- - uk: /uk/
- - zh: /zh/
-markdown_extensions:
-- toc:
- permalink: true
-- markdown.extensions.codehilite:
- guess_lang: false
-- mdx_include:
- base_path: docs
-- admonition
-- codehilite
-- extra
-- pymdownx.superfences:
- custom_fences:
- - name: mermaid
- class: mermaid
- format: !!python/name:pymdownx.superfences.fence_code_format ''
-- pymdownx.tabbed:
- alternate_style: true
-- attr_list
-- md_in_html
-extra:
- analytics:
- provider: google
- property: G-YNEVN69SC3
- social:
- - icon: fontawesome/brands/github-alt
- link: https://github.com/tiangolo/fastapi
- - icon: fontawesome/brands/discord
- link: https://discord.gg/VQjSZaeJmf
- - icon: fontawesome/brands/twitter
- link: https://twitter.com/fastapi
- - icon: fontawesome/brands/linkedin
- link: https://www.linkedin.com/in/tiangolo
- - icon: fontawesome/brands/dev
- link: https://dev.to/tiangolo
- - icon: fontawesome/brands/medium
- link: https://medium.com/@tiangolo
- - icon: fontawesome/solid/globe
- link: https://tiangolo.com
- alternate:
- - link: /
- name: en - English
- - link: /az/
- name: az
- - link: /cs/
- name: cs
- - link: /de/
- name: de
- - link: /es/
- name: es - español
- - link: /fa/
- name: fa
- - link: /fr/
- name: fr - français
- - link: /he/
- name: he
- - link: /hy/
- name: hy
- - link: /id/
- name: id
- - link: /it/
- name: it - italiano
- - link: /ja/
- name: ja - 日本語
- - link: /ko/
- name: ko - 한국어
- - link: /nl/
- name: nl
- - link: /pl/
- name: pl
- - link: /pt/
- name: pt - português
- - link: /ru/
- name: ru - русский язык
- - link: /sq/
- name: sq - shqip
- - link: /sv/
- name: sv - svenska
- - link: /ta/
- name: ta - தமிழ்
- - link: /tr/
- name: tr - Türkçe
- - link: /uk/
- name: uk - українська мова
- - link: /zh/
- name: zh - 汉语
-extra_css:
-- https://fastapi.tiangolo.com/css/termynal.css
-- https://fastapi.tiangolo.com/css/custom.css
-extra_javascript:
-- https://fastapi.tiangolo.com/js/termynal.js
-- https://fastapi.tiangolo.com/js/custom.js
diff --git a/docs/cs/overrides/.gitignore b/docs/cs/overrides/.gitignore
deleted file mode 100644
index e69de29bb..000000000
diff --git a/docs/de/docs/about/index.md b/docs/de/docs/about/index.md
new file mode 100644
index 000000000..4c309e02a
--- /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 000000000..bf38d9795
--- /dev/null
+++ b/docs/de/docs/advanced/additional-responses.md
@@ -0,0 +1,247 @@
+# 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:
+
+{* ../../docs_src/additional_responses/tutorial001.py hl[18,22] *}
+
+/// 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:
+
+{* ../../docs_src/additional_responses/tutorial002.py hl[19:24,28] *}
+
+/// 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:
+
+{* ../../docs_src/additional_responses/tutorial003.py hl[20:31] *}
+
+Es wird alles kombiniert und in Ihre OpenAPI eingebunden und in der API-Dokumentation angezeigt:
+
++ +**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 000000000..50ae11f90 --- /dev/null +++ b/docs/de/docs/how-to/conditional-openapi.md @@ -0,0 +1,56 @@ +# 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: + +{* ../../docs_src/conditional_openapi/tutorial001.py hl[6,11] *} + +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: + +
- FastAPI framework, high performance, easy to learn, fast to code, ready for production + FastAPI Framework, hochperformant, leicht zu erlernen, schnell zu programmieren, einsatzbereit
--- -**Documentation**: https://fastapi.tiangolo.com +**Dokumentation**: https://fastapi.tiangolo.com -**Source Code**: https://github.com/tiangolo/fastapi +**Quellcode**: https://github.com/fastapi/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 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 +64,68 @@ 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._“ -async def
...async def
...uvicorn main:app --reload
...uvicorn main:app --reload
...ujson
- for faster JSON "parsing".
-* 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 000000000..b5582f55b
--- /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/project-generation.md b/docs/de/docs/project-generation.md
new file mode 100644
index 000000000..c47bcb6d3
--- /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 000000000..81d43bc5b
--- /dev/null
+++ b/docs/de/docs/python-types.md
@@ -0,0 +1,574 @@
+# 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:
+
+{* ../../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.
+
+{* ../../docs_src/python_types/tutorial001.py hl[2] *}
+
+### 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:
+
+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("/")`).
+
+{* ../../docs_src/first_steps/tutorial001.py hl[7] *}
+
+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:
+
+{* ../../docs_src/first_steps/tutorial003.py hl[7] *}
+
+/// 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
+
+{* ../../docs_src/first_steps/tutorial001.py hl[8] *}
+
+Sie können ein `dict`, eine `list`, einzelne Werte wie `str`, `int`, usw. zurückgeben.
+
+Sie können auch Pydantic-Modelle zurückgeben (dazu später mehr).
+
+Es gibt viele andere Objekte und Modelle, die automatisch zu JSON konvertiert werden (einschließlich ORMs usw.). Versuchen Sie, Ihre Lieblingsobjekte zu verwenden. Es ist sehr wahrscheinlich, dass sie bereits unterstützt werden.
+
+## 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 000000000..31bc6d328
--- /dev/null
+++ b/docs/de/docs/tutorial/handling-errors.md
@@ -0,0 +1,255 @@
+# 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
+
+{* ../../docs_src/handling_errors/tutorial001.py hl[1] *}
+
+### 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.
+
+{* ../../docs_src/handling_errors/tutorial001.py hl[11] *}
+
+### 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:
+
+{* ../../docs_src/handling_errors/tutorial002.py hl[14] *}
+
+## 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:
+
+{* ../../docs_src/handling_errors/tutorial003.py hl[5:7,13:18,24] *}
+
+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.
+
+{* ../../docs_src/handling_errors/tutorial004.py hl[2,14:16] *}
+
+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:
+
+{* ../../docs_src/handling_errors/tutorial004.py hl[3:4,9:11,22] *}
+
+/// 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.
+
+{* ../../docs_src/handling_errors/tutorial005.py hl[14] *}
+
+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:
+
+{* ../../docs_src/handling_errors/tutorial006.py hl[2:5,15,21] *}
+
+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 000000000..8283cc929
--- /dev/null
+++ b/docs/de/docs/tutorial/header-params.md
@@ -0,0 +1,91 @@
+# Header-Parameter
+
+So wie `Query`-, `Path`-, und `Cookie`-Parameter können Sie auch Header-Parameter definieren.
+
+## `Header` importieren
+
+Importieren Sie zuerst `Header`:
+
+{* ../../docs_src/header_params/tutorial001_an_py310.py hl[3] *}
+
+## `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:
+
+{* ../../docs_src/header_params/tutorial001_an_py310.py hl[9] *}
+
+/// 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`.
+
+{* ../../docs_src/header_params/tutorial002_an_py310.py hl[10] *}
+
+/// 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:
+
+{* ../../docs_src/header_params/tutorial003_an_py310.py hl[9] *}
+
+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 000000000..3cbfe37f4
--- /dev/null
+++ b/docs/de/docs/tutorial/index.md
@@ -0,0 +1,83 @@
+# 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:
+
+contact
-FelderParameter | Typ | Beschreibung |
---|---|---|
name | str | Der identifizierende Name der Kontaktperson/Organisation. |
url | str | Die URL, die auf die Kontaktinformationen verweist. MUSS im Format einer URL vorliegen. |
email | str | Die E-Mail-Adresse der Kontaktperson/Organisation. MUSS im Format einer E-Mail-Adresse vorliegen. |
license_info
-FelderParameter | Typ | Beschreibung |
---|---|---|
name | str | ERFORDERLICH (wenn eine license_info festgelegt ist). Der für die API verwendete Lizenzname. |
identifier | str | Ein 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. |
url | str | Eine URL zur Lizenz, die für die API verwendet wird. MUSS im Format einer URL vorliegen. |
kwargs
, verwendet werden. Selbst wenn diese keinen Defaultwert haben.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *}
+
+### 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.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py hl[10] *}
+
+## 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).
+{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py hl[10] *}
+
+## 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
+
+{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py hl[10] *}
+
+## 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
.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py hl[13] *}
+
+## 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 000000000..123990940
--- /dev/null
+++ b/docs/de/docs/tutorial/path-params.md
@@ -0,0 +1,258 @@
+# Pfad-Parameter
+
+Sie können Pfad-„Parameter“ oder -„Variablen“ mit der gleichen Syntax deklarieren, welche in Python-Format-Strings verwendet wird:
+
+{* ../../docs_src/path_params/tutorial001.py hl[6:7] *}
+
+Der Wert des Pfad-Parameters `item_id` wird Ihrer Funktion als das Argument `item_id` übergeben.
+
+Wenn Sie dieses Beispiel ausführen und auf http://127.0.0.1:8000/items/foo 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:
+
+{* ../../docs_src/path_params/tutorial002.py hl[7] *}
+
+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:
+
+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:
+
+{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *}
+
+## `UploadFile` mit zusätzlichen Metadaten
+
+Sie können auch `File()` zusammen mit `UploadFile` verwenden, um zum Beispiel zusätzliche Metadaten zu setzen:
+
+{* ../../docs_src/request_files/tutorial001_03_an_py39.py hl[9,15] *}
+
+## 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:
+
+{* ../../docs_src/request_files/tutorial002_an_py39.py hl[10,15] *}
+
+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`:
+
+{* ../../docs_src/request_files/tutorial003_an_py39.py hl[11,18:20] *}
+
+## 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 000000000..3c5e11adf
--- /dev/null
+++ b/docs/de/docs/tutorial/request-forms-and-files.md
@@ -0,0 +1,37 @@
+# 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
+
+{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[3] *}
+
+## `File` und `Form`-Parameter definieren
+
+Erstellen Sie Datei- und Formularparameter, so wie Sie es auch mit `Body` und `Query` machen würden:
+
+{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[10:12] *}
+
+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 000000000..2f88caaba
--- /dev/null
+++ b/docs/de/docs/tutorial/request-forms.md
@@ -0,0 +1,69 @@
+# 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`:
+
+{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[3] *}
+
+## `Form`-Parameter definieren
+
+Erstellen Sie Formular-Parameter, so wie Sie es auch mit `Body` und `Query` machen würden:
+
+{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[9] *}
+
+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 000000000..faf9be516
--- /dev/null
+++ b/docs/de/docs/tutorial/response-model.md
@@ -0,0 +1,348 @@
+# 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.
+
+{* ../../docs_src/response_model/tutorial001_01_py310.py hl[16,21] *}
+
+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.
+
+{* ../../docs_src/response_model/tutorial001_py310.py hl[17,22,24:27] *}
+
+/// 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:
+
+{* ../../docs_src/response_model/tutorial002_py310.py hl[7,9] *}
+
+/// 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:
+
+{* ../../docs_src/response_model/tutorial002_py310.py hl[16] *}
+
+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:
+
+{* ../../docs_src/response_model/tutorial003_py310.py hl[9,11,16] *}
+
+Obwohl unsere *Pfadoperation-Funktion* hier denselben `user` von der Eingabe zurückgibt, der das Passwort enthält:
+
+{* ../../docs_src/response_model/tutorial003_py310.py hl[24] *}
+
+... haben wir deklariert, dass `response_model` das Modell `UserOut` ist, welches das Passwort nicht enthält:
+
+{* ../../docs_src/response_model/tutorial003_py310.py hl[22] *}
+
+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.
+
+{* ../../docs_src/response_model/tutorial003_01_py310.py hl[7:10,13:14,18] *}
+
+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:
+
+await
🐕🦺, 👥 🔜 📣 👆 🔢 ⏮️ 😐 `def` ↩️ `async def`.
-
-, 🗄 👍 🚫 ⚙️ 👁 `Bucket` 🎚 💗 "🧵Ⓜ",, 👥 💪 🤚 🥡 🔗 & 🚶♀️ ⚫️ 👆 🚙 🔢:
-
-```Python hl_lines="49-53"
-{!../../../docs_src/nosql_databases/tutorial001.py!}
-```
-
-## 🌃
-
-👆 💪 🛠️ 🙆 🥉 🥳 ☁ 💽, ⚙️ 👫 🐩 📦.
-
-🎏 ✔ 🙆 🎏 🔢 🧰, ⚙️ ⚖️ 🛠️.
diff --git a/docs/em/docs/advanced/openapi-callbacks.md b/docs/em/docs/advanced/openapi-callbacks.md
index 630b75ed2..b0a821668 100644
--- a/docs/em/docs/advanced/openapi-callbacks.md
+++ b/docs/em/docs/advanced/openapi-callbacks.md
@@ -31,12 +31,13 @@
👉 🍕 📶 😐, 🌅 📟 🎲 ⏪ 😰 👆:
-```Python hl_lines="9-13 36-53"
-{!../../../docs_src/openapi_callbacks/tutorial001.py!}
-```
+{* ../../docs_src/openapi_callbacks/tutorial001.py hl[9:13,36:53] *}
+
+/// tip
-!!! tip
- `callback_url` 🔢 🔢 ⚙️ Pydantic 📛 🆎.
+`callback_url` 🔢 🔢 ⚙️ Pydantic 📛 🆎.
+
+///
🕴 🆕 👜 `callbacks=messages_callback_router.routes` ❌ *➡ 🛠️ 👨🎨*. 👥 🔜 👀 ⚫️❔ 👈 ⏭.
@@ -61,10 +62,13 @@ httpx.post(callback_url, json={"description": "Invoice paid", "paid": True})
👉 🖼 🚫 🛠️ ⏲ ⚫️ (👈 💪 ⏸ 📟), 🕴 🧾 🍕.
-!!! tip
- ☑ ⏲ 🇺🇸🔍 📨.
+/// tip
+
+☑ ⏲ 🇺🇸🔍 📨.
- 🕐❔ 🛠️ ⏲ 👆, 👆 💪 ⚙️ 🕳 💖 🇸🇲 ⚖️ 📨.
+🕐❔ 🛠️ ⏲ 👆, 👆 💪 ⚙️ 🕳 💖 🇸🇲 ⚖️ 📨.
+
+///
## ✍ ⏲ 🧾 📟
@@ -74,18 +78,19 @@ httpx.post(callback_url, json={"description": "Invoice paid", "paid": True})
👥 🔜 ⚙️ 👈 🎏 💡 📄 ❔ *🔢 🛠️* 🔜 👀 💖... 🏗 *➡ 🛠️(Ⓜ)* 👈 🔢 🛠️ 🔜 🛠️ (🕐 👆 🛠️ 🔜 🤙).
-!!! tip
- 🕐❔ ✍ 📟 📄 ⏲, ⚫️ 💪 ⚠ 🌈 👈 👆 👈 *🔢 👩💻*. & 👈 👆 ⏳ 🛠️ *🔢 🛠️*, 🚫 *👆 🛠️*.
+/// tip
+
+🕐❔ ✍ 📟 📄 ⏲, ⚫️ 💪 ⚠ 🌈 👈 👆 👈 *🔢 👩💻*. & 👈 👆 ⏳ 🛠️ *🔢 🛠️*, 🚫 *👆 🛠️*.
+
+🍕 🛠️ 👉 ☝ 🎑 ( *🔢 👩💻*) 💪 ℹ 👆 💭 💖 ⚫️ 🌅 ⭐ 🌐❔ 🚮 🔢, Pydantic 🏷 💪, 📨, ♒️. 👈 *🔢 🛠️*.
- 🍕 🛠️ 👉 ☝ 🎑 ( *🔢 👩💻*) 💪 ℹ 👆 💭 💖 ⚫️ 🌅 ⭐ 🌐❔ 🚮 🔢, Pydantic 🏷 💪, 📨, ♒️. 👈 *🔢 🛠️*.
+///
### ✍ ⏲ `APIRouter`
🥇 ✍ 🆕 `APIRouter` 👈 🔜 🔌 1️⃣ ⚖️ 🌅 ⏲.
-```Python hl_lines="3 25"
-{!../../../docs_src/openapi_callbacks/tutorial001.py!}
-```
+{* ../../docs_src/openapi_callbacks/tutorial001.py hl[3,25] *}
### ✍ ⏲ *➡ 🛠️*
@@ -96,9 +101,7 @@ httpx.post(callback_url, json={"description": "Invoice paid", "paid": True})
* ⚫️ 🔜 🎲 ✔️ 📄 💪 ⚫️ 🔜 📨, ✅ `body: InvoiceEvent`.
* & ⚫️ 💪 ✔️ 📄 📨 ⚫️ 🔜 📨, ✅ `response_model=InvoiceEventReceived`.
-```Python hl_lines="16-18 21-22 28-32"
-{!../../../docs_src/openapi_callbacks/tutorial001.py!}
-```
+{* ../../docs_src/openapi_callbacks/tutorial001.py hl[16:18,21:22,28:32] *}
📤 2️⃣ 👑 🔺 ⚪️➡️ 😐 *➡ 🛠️*:
@@ -154,8 +157,11 @@ https://www.external.org/events/invoices/2expen51ve
}
```
-!!! tip
- 👀 ❔ ⏲ 📛 ⚙️ 🔌 📛 📨 🔢 🔢 `callback_url` (`https://www.external.org/events`) & 🧾 `id` ⚪️➡️ 🔘 🎻 💪 (`2expen51ve`).
+/// tip
+
+👀 ❔ ⏲ 📛 ⚙️ 🔌 📛 📨 🔢 🔢 `callback_url` (`https://www.external.org/events`) & 🧾 `id` ⚪️➡️ 🔘 🎻 💪 (`2expen51ve`).
+
+///
### 🚮 ⏲ 📻
@@ -163,12 +169,13 @@ https://www.external.org/events/invoices/2expen51ve
🔜 ⚙️ 🔢 `callbacks` *👆 🛠️ ➡ 🛠️ 👨🎨* 🚶♀️ 🔢 `.routes` (👈 🤙 `list` 🛣/*➡ 🛠️*) ⚪️➡️ 👈 ⏲ 📻:
-```Python hl_lines="35"
-{!../../../docs_src/openapi_callbacks/tutorial001.py!}
-```
+{* ../../docs_src/openapi_callbacks/tutorial001.py hl[35] *}
+
+/// tip
+
+👀 👈 👆 🚫 🚶♀️ 📻 ⚫️ (`invoices_callback_router`) `callback=`, ✋️ 🔢 `.routes`, `invoices_callback_router.routes`.
-!!! tip
- 👀 👈 👆 🚫 🚶♀️ 📻 ⚫️ (`invoices_callback_router`) `callback=`, ✋️ 🔢 `.routes`, `invoices_callback_router.routes`.
+///
### ✅ 🩺
diff --git a/docs/em/docs/advanced/path-operation-advanced-configuration.md b/docs/em/docs/advanced/path-operation-advanced-configuration.md
index ec7231870..9d9d5fa8d 100644
--- a/docs/em/docs/advanced/path-operation-advanced-configuration.md
+++ b/docs/em/docs/advanced/path-operation-advanced-configuration.md
@@ -2,16 +2,17 @@
## 🗄 {
-!!! warning
- 🚥 👆 🚫 "🕴" 🗄, 👆 🎲 🚫 💪 👉.
+/// warning
+
+🚥 👆 🚫 "🕴" 🗄, 👆 🎲 🚫 💪 👉.
+
+///
👆 💪 ⚒ 🗄 `operationId` ⚙️ 👆 *➡ 🛠️* ⏮️ 🔢 `operation_id`.
👆 🔜 ✔️ ⚒ 💭 👈 ⚫️ 😍 🔠 🛠️.
-```Python hl_lines="6"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial001.py!}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial001.py hl[6] *}
### ⚙️ *➡ 🛠️ 🔢* 📛 {
@@ -19,25 +20,27 @@
👆 🔜 ⚫️ ⏮️ ❎ 🌐 👆 *➡ 🛠️*.
-```Python hl_lines="2 12-21 24"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial002.py hl[2,12:21,24] *}
+
+/// tip
-!!! tip
- 🚥 👆 ❎ 🤙 `app.openapi()`, 👆 🔜 ℹ `operationId`Ⓜ ⏭ 👈.
+🚥 👆 ❎ 🤙 `app.openapi()`, 👆 🔜 ℹ `operationId`Ⓜ ⏭ 👈.
-!!! warning
- 🚥 👆 👉, 👆 ✔️ ⚒ 💭 🔠 1️⃣ 👆 *➡ 🛠️ 🔢* ✔️ 😍 📛.
+///
- 🚥 👫 🎏 🕹 (🐍 📁).
+/// warning
+
+🚥 👆 👉, 👆 ✔️ ⚒ 💭 🔠 1️⃣ 👆 *➡ 🛠️ 🔢* ✔️ 😍 📛.
+
+🚥 👫 🎏 🕹 (🐍 📁).
+
+///
## 🚫 ⚪️➡️ 🗄
🚫 *➡ 🛠️* ⚪️➡️ 🏗 🗄 🔗 (& ➡️, ⚪️➡️ 🏧 🧾 ⚙️), ⚙️ 🔢 `include_in_schema` & ⚒ ⚫️ `False`:
-```Python hl_lines="6"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial003.py!}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial003.py hl[6] *}
## 🏧 📛 ⚪️➡️ #️⃣
@@ -47,9 +50,7 @@
⚫️ 🏆 🚫 🎦 🆙 🧾, ✋️ 🎏 🧰 (✅ 🐉) 🔜 💪 ⚙️ 🎂.
-```Python hl_lines="19-29"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial004.py!}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial004.py hl[19:29] *}
## 🌖 📨
@@ -59,14 +60,17 @@
👆 💪 📣 🌖 📨 ⏮️ 👫 🏷, 👔 📟, ♒️.
-📤 🎂 📃 📥 🧾 🔃 ⚫️, 👆 💪 ✍ ⚫️ [🌖 📨 🗄](./additional-responses.md){.internal-link target=_blank}.
+📤 🎂 📃 📥 🧾 🔃 ⚫️, 👆 💪 ✍ ⚫️ [🌖 📨 🗄](additional-responses.md){.internal-link target=_blank}.
## 🗄 ➕
🕐❔ 👆 📣 *➡ 🛠️* 👆 🈸, **FastAPI** 🔁 🏗 🔗 🗃 🔃 👈 *➡ 🛠️* 🔌 🗄 🔗.
-!!! note "📡 ℹ"
- 🗄 🔧 ⚫️ 🤙 🛠️ 🎚.
+/// note | 📡 ℹ
+
+🗄 🔧 ⚫️ 🤙 🛠️ 🎚.
+
+///
⚫️ ✔️ 🌐 ℹ 🔃 *➡ 🛠️* & ⚙️ 🏗 🏧 🧾.
@@ -74,10 +78,13 @@
👉 *➡ 🛠️*-🎯 🗄 🔗 🛎 🏗 🔁 **FastAPI**, ✋️ 👆 💪 ↔ ⚫️.
-!!! tip
- 👉 🔅 🎚 ↔ ☝.
+/// tip
+
+👉 🔅 🎚 ↔ ☝.
- 🚥 👆 🕴 💪 📣 🌖 📨, 🌅 🏪 🌌 ⚫️ ⏮️ [🌖 📨 🗄](./additional-responses.md){.internal-link target=_blank}.
+🚥 👆 🕴 💪 📣 🌖 📨, 🌅 🏪 🌌 ⚫️ ⏮️ [🌖 📨 🗄](additional-responses.md){.internal-link target=_blank}.
+
+///
👆 💪 ↔ 🗄 🔗 *➡ 🛠️* ⚙️ 🔢 `openapi_extra`.
@@ -85,9 +92,7 @@
👉 `openapi_extra` 💪 👍, 🖼, 📣 [🗄 ↔](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions):
-```Python hl_lines="6"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial005.py!}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial005.py hl[6] *}
🚥 👆 📂 🏧 🛠️ 🩺, 👆 ↔ 🔜 🎦 🆙 🔝 🎯 *➡ 🛠️*.
@@ -134,9 +139,7 @@
👆 💪 👈 ⏮️ `openapi_extra`:
-```Python hl_lines="20-37 39-40"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial006.py!}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial006.py hl[20:37,39:40] *}
👉 🖼, 👥 🚫 📣 🙆 Pydantic 🏷. 👐, 📨 💪 🚫 🎻 🎻, ⚫️ ✍ 🔗 `bytes`, & 🔢 `magic_data_reader()` 🔜 🈚 🎻 ⚫️ 🌌.
@@ -150,9 +153,7 @@
🖼, 👉 🈸 👥 🚫 ⚙️ FastAPI 🛠️ 🛠️ ⚗ 🎻 🔗 ⚪️➡️ Pydantic 🏷 🚫 🏧 🔬 🎻. 👐, 👥 📣 📨 🎚 🆎 📁, 🚫 🎻:
-```Python hl_lines="17-22 24"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial007.py!}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[17:22,24] *}
👐, 👐 👥 🚫 ⚙️ 🔢 🛠️ 🛠️, 👥 ⚙️ Pydantic 🏷 ❎ 🏗 🎻 🔗 💽 👈 👥 💚 📨 📁.
@@ -160,11 +161,12 @@
& ⤴️ 👆 📟, 👥 🎻 👈 📁 🎚 🔗, & ⤴️ 👥 🔄 ⚙️ 🎏 Pydantic 🏷 ✔ 📁 🎚:
-```Python hl_lines="26-33"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial007.py!}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[26:33] *}
+
+/// tip
+
+📥 👥 🏤-⚙️ 🎏 Pydantic 🏷.
-!!! tip
- 📥 👥 🏤-⚙️ 🎏 Pydantic 🏷.
+✋️ 🎏 🌌, 👥 💪 ✔️ ✔ ⚫️ 🎏 🌌.
- ✋️ 🎏 🌌, 👥 💪 ✔️ ✔ ⚫️ 🎏 🌌.
+///
diff --git a/docs/em/docs/advanced/response-change-status-code.md b/docs/em/docs/advanced/response-change-status-code.md
index 156efcc16..4933484dd 100644
--- a/docs/em/docs/advanced/response-change-status-code.md
+++ b/docs/em/docs/advanced/response-change-status-code.md
@@ -20,9 +20,7 @@
& ⤴️ 👆 💪 ⚒ `status_code` 👈 *🔀* 📨 🎚.
-```Python hl_lines="1 9 12"
-{!../../../docs_src/response_change_status_code/tutorial001.py!}
-```
+{* ../../docs_src/response_change_status_code/tutorial001.py hl[1,9,12] *}
& ⤴️ 👆 💪 📨 🙆 🎚 👆 💪, 👆 🛎 🔜 ( `dict`, 💽 🏷, ♒️).
diff --git a/docs/em/docs/advanced/response-cookies.md b/docs/em/docs/advanced/response-cookies.md
index 23fffe1dd..d9fdbaa87 100644
--- a/docs/em/docs/advanced/response-cookies.md
+++ b/docs/em/docs/advanced/response-cookies.md
@@ -6,9 +6,7 @@
& ⤴️ 👆 💪 ⚒ 🍪 👈 *🔀* 📨 🎚.
-```Python hl_lines="1 8-9"
-{!../../../docs_src/response_cookies/tutorial002.py!}
-```
+{* ../../docs_src/response_cookies/tutorial002.py hl[1,8:9] *}
& ⤴️ 👆 💪 📨 🙆 🎚 👆 💪, 👆 🛎 🔜 ( `dict`, 💽 🏷, ♒️).
@@ -26,24 +24,28 @@
⤴️ ⚒ 🍪 ⚫️, & ⤴️ 📨 ⚫️:
-```Python hl_lines="10-12"
-{!../../../docs_src/response_cookies/tutorial001.py!}
-```
+{* ../../docs_src/response_cookies/tutorial001.py hl[10:12] *}
-!!! tip
- ✔️ 🤯 👈 🚥 👆 📨 📨 🔗 ↩️ ⚙️ `Response` 🔢, FastAPI 🔜 📨 ⚫️ 🔗.
+/// tip
- , 👆 🔜 ✔️ ⚒ 💭 👆 💽 ☑ 🆎. 🤶 Ⓜ. ⚫️ 🔗 ⏮️ 🎻, 🚥 👆 🛬 `JSONResponse`.
+✔️ 🤯 👈 🚥 👆 📨 📨 🔗 ↩️ ⚙️ `Response` 🔢, FastAPI 🔜 📨 ⚫️ 🔗.
- & 👈 👆 🚫 📨 🙆 📊 👈 🔜 ✔️ ⛽ `response_model`.
+, 👆 🔜 ✔️ ⚒ 💭 👆 💽 ☑ 🆎. 🤶 Ⓜ. ⚫️ 🔗 ⏮️ 🎻, 🚥 👆 🛬 `JSONResponse`.
+
+ & 👈 👆 🚫 📨 🙆 📊 👈 🔜 ✔️ ⛽ `response_model`.
+
+///
### 🌅 ℹ
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette.responses import Response` ⚖️ `from starlette.responses import JSONResponse`.
+/// note | 📡 ℹ
+
+👆 💪 ⚙️ `from starlette.responses import Response` ⚖️ `from starlette.responses import JSONResponse`.
+
+**FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃.
- **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃.
+ & `Response` 💪 ⚙️ 🛎 ⚒ 🎚 & 🍪, **FastAPI** 🚚 ⚫️ `fastapi.Response`.
- & `Response` 💪 ⚙️ 🛎 ⚒ 🎚 & 🍪, **FastAPI** 🚚 ⚫️ `fastapi.Response`.
+///
👀 🌐 💪 🔢 & 🎛, ✅ 🧾 💃.
diff --git a/docs/em/docs/advanced/response-directly.md b/docs/em/docs/advanced/response-directly.md
index ba09734fb..29819a205 100644
--- a/docs/em/docs/advanced/response-directly.md
+++ b/docs/em/docs/advanced/response-directly.md
@@ -14,8 +14,11 @@
👐, 👆 💪 📨 🙆 `Response` ⚖️ 🙆 🎧-🎓 ⚫️.
-!!! tip
- `JSONResponse` ⚫️ 🎧-🎓 `Response`.
+/// tip
+
+`JSONResponse` ⚫️ 🎧-🎓 `Response`.
+
+///
& 🕐❔ 👆 📨 `Response`, **FastAPI** 🔜 🚶♀️ ⚫️ 🔗.
@@ -31,14 +34,15 @@
📚 💼, 👆 💪 ⚙️ `jsonable_encoder` 🗜 👆 📊 ⏭ 🚶♀️ ⚫️ 📨:
-```Python hl_lines="6-7 21-22"
-{!../../../docs_src/response_directly/tutorial001.py!}
-```
+{* ../../docs_src/response_directly/tutorial001.py hl[6:7,21:22] *}
+
+/// note | 📡 ℹ
+
+👆 💪 ⚙️ `from starlette.responses import JSONResponse`.
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette.responses import JSONResponse`.
+**FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃.
- **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃.
+///
## 🛬 🛃 `Response`
@@ -50,9 +54,7 @@
👆 💪 🚮 👆 📂 🎚 🎻, 🚮 ⚫️ `Response`, & 📨 ⚫️:
-```Python hl_lines="1 18"
-{!../../../docs_src/response_directly/tutorial002.py!}
-```
+{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *}
## 🗒
diff --git a/docs/em/docs/advanced/response-headers.md b/docs/em/docs/advanced/response-headers.md
index de798982a..e9e1b62d2 100644
--- a/docs/em/docs/advanced/response-headers.md
+++ b/docs/em/docs/advanced/response-headers.md
@@ -6,9 +6,7 @@
& ⤴️ 👆 💪 ⚒ 🎚 👈 *🔀* 📨 🎚.
-```Python hl_lines="1 7-8"
-{!../../../docs_src/response_headers/tutorial002.py!}
-```
+{* ../../docs_src/response_headers/tutorial002.py hl[1,7:8] *}
& ⤴️ 👆 💪 📨 🙆 🎚 👆 💪, 👆 🛎 🔜 ( `dict`, 💽 🏷, ♒️).
@@ -24,16 +22,17 @@
✍ 📨 🔬 [📨 📨 🔗](response-directly.md){.internal-link target=_blank} & 🚶♀️ 🎚 🌖 🔢:
-```Python hl_lines="10-12"
-{!../../../docs_src/response_headers/tutorial001.py!}
-```
+{* ../../docs_src/response_headers/tutorial001.py hl[10:12] *}
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette.responses import Response` ⚖️ `from starlette.responses import JSONResponse`.
+/// note | 📡 ℹ
- **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃.
+👆 💪 ⚙️ `from starlette.responses import Response` ⚖️ `from starlette.responses import JSONResponse`.
- & `Response` 💪 ⚙️ 🛎 ⚒ 🎚 & 🍪, **FastAPI** 🚚 ⚫️ `fastapi.Response`.
+**FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃.
+
+ & `Response` 💪 ⚙️ 🛎 ⚒ 🎚 & 🍪, **FastAPI** 🚚 ⚫️ `fastapi.Response`.
+
+///
## 🛃 🎚
diff --git a/docs/em/docs/advanced/security/http-basic-auth.md b/docs/em/docs/advanced/security/http-basic-auth.md
index 33470a726..73736f3b3 100644
--- a/docs/em/docs/advanced/security/http-basic-auth.md
+++ b/docs/em/docs/advanced/security/http-basic-auth.md
@@ -20,9 +20,7 @@
* ⚫️ 📨 🎚 🆎 `HTTPBasicCredentials`:
* ⚫️ 🔌 `username` & `password` 📨.
-```Python hl_lines="2 6 10"
-{!../../../docs_src/security/tutorial006.py!}
-```
+{* ../../docs_src/security/tutorial006.py hl[2,6,10] *}
🕐❔ 👆 🔄 📂 📛 🥇 🕰 (⚖️ 🖊 "🛠️" 🔼 🩺) 🖥 🔜 💭 👆 👆 🆔 & 🔐:
@@ -42,9 +40,7 @@
⤴️ 👥 💪 ⚙️ `secrets.compare_digest()` 🚚 👈 `credentials.username` `"stanleyjobson"`, & 👈 `credentials.password` `"swordfish"`.
-```Python hl_lines="1 11-21"
-{!../../../docs_src/security/tutorial007.py!}
-```
+{* ../../docs_src/security/tutorial007.py hl[1,11:21] *}
👉 🔜 🎏:
@@ -108,6 +104,4 @@ if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish":
⏮️ 🔍 👈 🎓 ❌, 📨 `HTTPException` ⏮️ 👔 📟 4️⃣0️⃣1️⃣ (🎏 📨 🕐❔ 🙅♂ 🎓 🚚) & 🚮 🎚 `WWW-Authenticate` ⚒ 🖥 🎦 💳 📋 🔄:
-```Python hl_lines="23-27"
-{!../../../docs_src/security/tutorial007.py!}
-```
+{* ../../docs_src/security/tutorial007.py hl[23:27] *}
diff --git a/docs/em/docs/advanced/security/index.md b/docs/em/docs/advanced/security/index.md
index 20ee85553..5cdc47505 100644
--- a/docs/em/docs/advanced/security/index.md
+++ b/docs/em/docs/advanced/security/index.md
@@ -1,16 +1,19 @@
-# 🏧 💂♂ - 🎶
+# 🏧 💂♂
## 🌖 ⚒
-📤 ➕ ⚒ 🍵 💂♂ ↖️ ⚪️➡️ 🕐 📔 [🔰 - 👩💻 🦮: 💂♂](../../tutorial/security/){.internal-link target=_blank}.
+📤 ➕ ⚒ 🍵 💂♂ ↖️ ⚪️➡️ 🕐 📔 [🔰 - 👩💻 🦮: 💂♂](../../tutorial/security/index.md){.internal-link target=_blank}.
-!!! tip
- ⏭ 📄 **🚫 🎯 "🏧"**.
+/// tip
- & ⚫️ 💪 👈 👆 ⚙️ 💼, ⚗ 1️⃣ 👫.
+⏭ 📄 **🚫 🎯 "🏧"**.
+
+ & ⚫️ 💪 👈 👆 ⚙️ 💼, ⚗ 1️⃣ 👫.
+
+///
## ✍ 🔰 🥇
-⏭ 📄 🤔 👆 ⏪ ✍ 👑 [🔰 - 👩💻 🦮: 💂♂](../../tutorial/security/){.internal-link target=_blank}.
+⏭ 📄 🤔 👆 ⏪ ✍ 👑 [🔰 - 👩💻 🦮: 💂♂](../../tutorial/security/index.md){.internal-link target=_blank}.
👫 🌐 ⚓️ 🔛 🎏 🔧, ✋️ ✔ ➕ 🛠️.
diff --git a/docs/em/docs/advanced/security/oauth2-scopes.md b/docs/em/docs/advanced/security/oauth2-scopes.md
index a4684352c..b8c49bd11 100644
--- a/docs/em/docs/advanced/security/oauth2-scopes.md
+++ b/docs/em/docs/advanced/security/oauth2-scopes.md
@@ -10,18 +10,21 @@ Oauth2️⃣ ⏮️ ↔ 🛠️ ⚙️ 📚 🦏 🤝 🐕🦺, 💖 👱📔
👉 📄 👆 🔜 👀 ❔ 🛠️ 🤝 & ✔ ⏮️ 🎏 Oauth2️⃣ ⏮️ ↔ 👆 **FastAPI** 🈸.
-!!! warning
- 👉 🌅 ⚖️ 🌘 🏧 📄. 🚥 👆 ▶️, 👆 💪 🚶 ⚫️.
+/// warning
- 👆 🚫 🎯 💪 Oauth2️⃣ ↔, & 👆 💪 🍵 🤝 & ✔ 👐 👆 💚.
+👉 🌅 ⚖️ 🌘 🏧 📄. 🚥 👆 ▶️, 👆 💪 🚶 ⚫️.
- ✋️ Oauth2️⃣ ⏮️ ↔ 💪 🎆 🛠️ 🔘 👆 🛠️ (⏮️ 🗄) & 👆 🛠️ 🩺.
+👆 🚫 🎯 💪 Oauth2️⃣ ↔, & 👆 💪 🍵 🤝 & ✔ 👐 👆 💚.
- 👐, 👆 🛠️ 📚 ↔, ⚖️ 🙆 🎏 💂♂/✔ 📄, 👐 👆 💪, 👆 📟.
+✋️ Oauth2️⃣ ⏮️ ↔ 💪 🎆 🛠️ 🔘 👆 🛠️ (⏮️ 🗄) & 👆 🛠️ 🩺.
- 📚 💼, Oauth2️⃣ ⏮️ ↔ 💪 👹.
+👐, 👆 🛠️ 📚 ↔, ⚖️ 🙆 🎏 💂♂/✔ 📄, 👐 👆 💪, 👆 📟.
- ✋️ 🚥 👆 💭 👆 💪 ⚫️, ⚖️ 👆 😟, 🚧 👂.
+📚 💼, Oauth2️⃣ ⏮️ ↔ 💪 👹.
+
+✋️ 🚥 👆 💭 👆 💪 ⚫️, ⚖️ 👆 😟, 🚧 👂.
+
+///
## Oauth2️⃣ ↔ & 🗄
@@ -43,22 +46,23 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀.
* `instagram_basic` ⚙️ 👱📔 / 👱📔.
* `https://www.googleapis.com/auth/drive` ⚙️ 🇺🇸🔍.
-!!! info
- Oauth2️⃣ "↔" 🎻 👈 📣 🎯 ✔ ✔.
+/// info
+
+Oauth2️⃣ "↔" 🎻 👈 📣 🎯 ✔ ✔.
+
+⚫️ 🚫 🤔 🚥 ⚫️ ✔️ 🎏 🦹 💖 `:` ⚖️ 🚥 ⚫️ 📛.
- ⚫️ 🚫 🤔 🚥 ⚫️ ✔️ 🎏 🦹 💖 `:` ⚖️ 🚥 ⚫️ 📛.
+👈 ℹ 🛠️ 🎯.
- 👈 ℹ 🛠️ 🎯.
+Oauth2️⃣ 👫 🎻.
- Oauth2️⃣ 👫 🎻.
+///
## 🌐 🎑
🥇, ➡️ 🔜 👀 🍕 👈 🔀 ⚪️➡️ 🖼 👑 **🔰 - 👩💻 🦮** [Oauth2️⃣ ⏮️ 🔐 (& 🔁), 📨 ⏮️ 🥙 🤝](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. 🔜 ⚙️ Oauth2️⃣ ↔:
-```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 153"
-{!../../../docs_src/security/tutorial005.py!}
-```
+{* ../../docs_src/security/tutorial005.py hl[2,4,8,12,46,64,105,107:115,121:124,128:134,139,155] *}
🔜 ➡️ 📄 👈 🔀 🔁 🔁.
@@ -68,9 +72,7 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀.
`scopes` 🔢 📨 `dict` ⏮️ 🔠 ↔ 🔑 & 📛 💲:
-```Python hl_lines="62-65"
-{!../../../docs_src/security/tutorial005.py!}
-```
+{* ../../docs_src/security/tutorial005.py hl[62:65] *}
↩️ 👥 🔜 📣 📚 ↔, 👫 🔜 🎦 🆙 🛠️ 🩺 🕐❔ 👆 🕹-/✔.
@@ -88,14 +90,15 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀.
& 👥 📨 ↔ 🍕 🥙 🤝.
-!!! danger
- 🦁, 📥 👥 ❎ ↔ 📨 🔗 🤝.
+/// danger
- ✋️ 👆 🈸, 💂♂, 👆 🔜 ⚒ 💭 👆 🕴 🚮 ↔ 👈 👩💻 🤙 💪 ✔️, ⚖️ 🕐 👆 ✔️ 🔁.
+🦁, 📥 👥 ❎ ↔ 📨 🔗 🤝.
-```Python hl_lines="153"
-{!../../../docs_src/security/tutorial005.py!}
-```
+✋️ 👆 🈸, 💂♂, 👆 🔜 ⚒ 💭 👆 🕴 🚮 ↔ 👈 👩💻 🤙 💪 ✔️, ⚖️ 🕐 👆 ✔️ 🔁.
+
+///
+
+{* ../../docs_src/security/tutorial005.py hl[155] *}
## 📣 ↔ *➡ 🛠️* & 🔗
@@ -113,21 +116,25 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀.
👉 💼, ⚫️ 🚚 ↔ `me` (⚫️ 💪 🚚 🌅 🌘 1️⃣ ↔).
-!!! note
- 👆 🚫 🎯 💪 🚮 🎏 ↔ 🎏 🥉.
+/// note
+
+👆 🚫 🎯 💪 🚮 🎏 ↔ 🎏 🥉.
- 👥 🔨 ⚫️ 📥 🎦 ❔ **FastAPI** 🍵 ↔ 📣 🎏 🎚.
+👥 🔨 ⚫️ 📥 🎦 ❔ **FastAPI** 🍵 ↔ 📣 🎏 🎚.
-```Python hl_lines="4 139 166"
-{!../../../docs_src/security/tutorial005.py!}
-```
+///
-!!! info "📡 ℹ"
- `Security` 🤙 🏿 `Depends`, & ⚫️ ✔️ 1️⃣ ➕ 🔢 👈 👥 🔜 👀 ⏪.
+{* ../../docs_src/security/tutorial005.py hl[4,139,168] *}
- ✋️ ⚙️ `Security` ↩️ `Depends`, **FastAPI** 🔜 💭 👈 ⚫️ 💪 📣 💂♂ ↔, ⚙️ 👫 🔘, & 📄 🛠️ ⏮️ 🗄.
+/// info | 📡 ℹ
- ✋️ 🕐❔ 👆 🗄 `Query`, `Path`, `Depends`, `Security` & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓.
+`Security` 🤙 🏿 `Depends`, & ⚫️ ✔️ 1️⃣ ➕ 🔢 👈 👥 🔜 👀 ⏪.
+
+✋️ ⚙️ `Security` ↩️ `Depends`, **FastAPI** 🔜 💭 👈 ⚫️ 💪 📣 💂♂ ↔, ⚙️ 👫 🔘, & 📄 🛠️ ⏮️ 🗄.
+
+✋️ 🕐❔ 👆 🗄 `Query`, `Path`, `Depends`, `Security` & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓.
+
+///
## ⚙️ `SecurityScopes`
@@ -143,9 +150,7 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀.
👉 `SecurityScopes` 🎓 🎏 `Request` (`Request` ⚙️ 🤚 📨 🎚 🔗).
-```Python hl_lines="8 105"
-{!../../../docs_src/security/tutorial005.py!}
-```
+{* ../../docs_src/security/tutorial005.py hl[8,105] *}
## ⚙️ `scopes`
@@ -159,9 +164,7 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀.
👉 ⚠, 👥 🔌 ↔ 🚚 (🚥 🙆) 🎻 👽 🚀 (⚙️ `scope_str`). 👥 🚮 👈 🎻 ⚗ ↔ `WWW-Authenticate` 🎚 (👉 🍕 🔌).
-```Python hl_lines="105 107-115"
-{!../../../docs_src/security/tutorial005.py!}
-```
+{* ../../docs_src/security/tutorial005.py hl[105,107:115] *}
## ✔ `username` & 💽 💠
@@ -177,9 +180,7 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀.
👥 ✔ 👈 👥 ✔️ 👩💻 ⏮️ 👈 🆔, & 🚥 🚫, 👥 🤚 👈 🎏 ⚠ 👥 ✍ ⏭.
-```Python hl_lines="46 116-127"
-{!../../../docs_src/security/tutorial005.py!}
-```
+{* ../../docs_src/security/tutorial005.py hl[46,116:127] *}
## ✔ `scopes`
@@ -187,9 +188,7 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀.
👉, 👥 ⚙️ `security_scopes.scopes`, 👈 🔌 `list` ⏮️ 🌐 👫 ↔ `str`.
-```Python hl_lines="128-134"
-{!../../../docs_src/security/tutorial005.py!}
-```
+{* ../../docs_src/security/tutorial005.py hl[128:134] *}
## 🔗 🌲 & ↔
@@ -216,10 +215,13 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀.
* `security_scopes.scopes` 🔜 🔌 `["me"]` *➡ 🛠️* `read_users_me`, ↩️ ⚫️ 📣 🔗 `get_current_active_user`.
* `security_scopes.scopes` 🔜 🔌 `[]` (🕳) *➡ 🛠️* `read_system_status`, ↩️ ⚫️ 🚫 📣 🙆 `Security` ⏮️ `scopes`, & 🚮 🔗, `get_current_user`, 🚫 📣 🙆 `scope` 👯♂️.
-!!! tip
- ⚠ & "🎱" 👜 📥 👈 `get_current_user` 🔜 ✔️ 🎏 📇 `scopes` ✅ 🔠 *➡ 🛠️*.
+/// tip
+
+⚠ & "🎱" 👜 📥 👈 `get_current_user` 🔜 ✔️ 🎏 📇 `scopes` ✅ 🔠 *➡ 🛠️*.
- 🌐 ⚓️ 🔛 `scopes` 📣 🔠 *➡ 🛠️* & 🔠 🔗 🔗 🌲 👈 🎯 *➡ 🛠️*.
+🌐 ⚓️ 🔛 `scopes` 📣 🔠 *➡ 🛠️* & 🔠 🔗 🔗 🌲 👈 🎯 *➡ 🛠️*.
+
+///
## 🌖 ℹ 🔃 `SecurityScopes`
@@ -257,10 +259,13 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀.
🏆 🔐 📟 💧, ✋️ 🌖 🏗 🛠️ ⚫️ 🚚 🌅 📶. ⚫️ 🌅 🏗, 📚 🐕🦺 🔚 🆙 ✔ 🔑 💧.
-!!! note
- ⚫️ ⚠ 👈 🔠 🤝 🐕🦺 📛 👫 💧 🎏 🌌, ⚒ ⚫️ 🍕 👫 🏷.
+/// note
+
+⚫️ ⚠ 👈 🔠 🤝 🐕🦺 📛 👫 💧 🎏 🌌, ⚒ ⚫️ 🍕 👫 🏷.
+
+✋️ 🔚, 👫 🛠️ 🎏 Oauth2️⃣ 🐩.
- ✋️ 🔚, 👫 🛠️ 🎏 Oauth2️⃣ 🐩.
+///
**FastAPI** 🔌 🚙 🌐 👫 Oauth2️⃣ 🤝 💧 `fastapi.security.oauth2`.
diff --git a/docs/em/docs/advanced/settings.md b/docs/em/docs/advanced/settings.md
index bc50bf755..7fdd0d68a 100644
--- a/docs/em/docs/advanced/settings.md
+++ b/docs/em/docs/advanced/settings.md
@@ -8,44 +8,51 @@
## 🌐 🔢
-!!! tip
- 🚥 👆 ⏪ 💭 ⚫️❔ "🌐 🔢" & ❔ ⚙️ 👫, 💭 🆓 🚶 ⏭ 📄 🔛.
+/// tip
+
+🚥 👆 ⏪ 💭 ⚫️❔ "🌐 🔢" & ❔ ⚙️ 👫, 💭 🆓 🚶 ⏭ 📄 🔛.
+
+///
🌐 🔢 (💭 "🇨🇻 {") 🔢 👈 🖖 🏞 🐍 📟, 🏃♂ ⚙️, & 💪 ✍ 👆 🐍 📟 (⚖️ 🎏 📋 👍).
👆 💪 ✍ & ⚙️ 🌐 🔢 🐚, 🍵 💆♂ 🐍:
-=== "💾, 🇸🇻, 🚪 🎉"
+//// tab | 💾, 🇸🇻, 🚪 🎉
-
-
-
+
+
-
-
+
+
@@ -23,15 +29,15 @@
**🧾**: https://fastapi.tiangolo.com
-**ℹ 📟**: https://github.com/tiangolo/fastapi
+**ℹ 📟**: https://github.com/fastapi/fastapi
---
-FastAPI 🏛, ⏩ (↕-🎭), 🕸 🛠️ 🏗 🛠️ ⏮️ 🐍 3️⃣.7️⃣ ➕ ⚓️ 🔛 🐩 🐍 🆎 🔑.
+FastAPI 🏛, ⏩ (↕-🎭), 🕸 🛠️ 🏗 🛠️ ⏮️ 🐍 3️⃣.8️⃣ ➕ ⚓️ 🔛 🐩 🐍 🆎 🔑.
🔑 ⚒:
-* **⏩**: 📶 ↕ 🎭, 🔛 🇷🇪 ⏮️ **✳** & **🚶** (👏 💃 & Pydantic). [1️⃣ ⏩ 🐍 🛠️ 💪](#performance).
+* **⏩**: 📶 ↕ 🎭, 🔛 🇷🇪 ⏮️ **✳** & **🚶** (👏 💃 & Pydantic). [1️⃣ ⏩ 🐍 🛠️ 💪](#_15).
* **⏩ 📟**: 📈 🚅 🛠️ ⚒ 🔃 2️⃣0️⃣0️⃣ 💯 3️⃣0️⃣0️⃣ 💯. *
* **👩❤👨 🐛**: 📉 🔃 4️⃣0️⃣ 💯 🗿 (👩💻) 📉 ❌. *
* **🏋️**: 👑 👨🎨 🐕🦺. 🛠️ 🌐. 🌘 🕰 🛠️.
@@ -63,7 +69,7 @@ FastAPI 🏛, ⏩ (↕-🎭), 🕸 🛠️ 🏗 🛠️ ⏮️ 🐍 3️⃣.7️
"_[...] 👤 ⚙️ **FastAPI** 📚 👫 📆. [...] 👤 🤙 📆 ⚙️ ⚫️ 🌐 👇 🏉 **⚗ 🐕🦺 🤸♂**. 👫 💆♂ 🛠️ 🔘 🐚 **🖥** 🏬 & **📠** 🏬._"
-
ujson
- ⏩ 🎻 "🎻".
-* email_validator
- 📧 🔬.
+* email-validator
- 📧 🔬.
⚙️ 💃:
* httpx
- ✔ 🚥 👆 💚 ⚙️ `TestClient`.
* jinja2
- ✔ 🚥 👆 💚 ⚙️ 🔢 📄 📳.
-* python-multipart
- ✔ 🚥 👆 💚 🐕🦺 📨 "✍", ⏮️ `request.form()`.
+* python-multipart
- ✔ 🚥 👆 💚 🐕🦺 📨 "✍", ⏮️ `request.form()`.
* itsdangerous
- ✔ `SessionMiddleware` 🐕🦺.
* pyyaml
- ✔ 💃 `SchemaGenerator` 🐕🦺 (👆 🎲 🚫 💪 ⚫️ ⏮️ FastAPI).
-* ujson
- ✔ 🚥 👆 💚 ⚙️ `UJSONResponse`.
⚙️ FastAPI / 💃:
* uvicorn
- 💽 👈 📐 & 🍦 👆 🈸.
* orjson
- ✔ 🚥 👆 💚 ⚙️ `ORJSONResponse`.
+* ujson
- ✔ 🚥 👆 💚 ⚙️ `UJSONResponse`.
👆 💪 ❎ 🌐 👫 ⏮️ `pip install "fastapi[all]"`.
diff --git a/docs/em/docs/project-generation.md b/docs/em/docs/project-generation.md
index 5fd667ad1..ef6a21821 100644
--- a/docs/em/docs/project-generation.md
+++ b/docs/em/docs/project-generation.md
@@ -14,7 +14,7 @@
* ☁ 🐝 📳 🛠️.
* **☁ ✍** 🛠️ & 🛠️ 🇧🇿 🛠️.
* **🏭 🔜** 🐍 🕸 💽 ⚙️ Uvicorn & 🐁.
-* 🐍 **FastAPI** 👩💻:
+* 🐍 **FastAPI** 👩💻:
* **⏩**: 📶 ↕ 🎭, 🔛 🇷🇪 ⏮️ **✳** & **🚶** (👏 💃 & Pydantic).
* **🏋️**: 👑 👨🎨 🐕🦺. 🛠️ 🌐. 🌘 🕰 🛠️.
* **⏩**: 🔧 ⏩ ⚙️ & 💡. 🌘 🕰 👂 🩺.
@@ -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 e079d9039..d2af23bb9 100644
--- a/docs/em/docs/python-types.md
+++ b/docs/em/docs/python-types.md
@@ -12,15 +12,18 @@
✋️ 🚥 👆 🙅 ⚙️ **FastAPI**, 👆 🔜 💰 ⚪️➡️ 🏫 🍖 🔃 👫.
-!!! note
- 🚥 👆 🐍 🕴, & 👆 ⏪ 💭 🌐 🔃 🆎 🔑, 🚶 ⏭ 📃.
+/// note
+
+🚥 👆 🐍 🕴, & 👆 ⏪ 💭 🌐 🔃 🆎 🔑, 🚶 ⏭ 📃.
+
+///
## 🎯
➡️ ▶️ ⏮️ 🙅 🖼:
```Python
-{!../../../docs_src/python_types/tutorial001.py!}
+{!../../docs_src/python_types/tutorial001.py!}
```
🤙 👉 📋 🔢:
@@ -36,7 +39,7 @@ John Doe
* 🔢 👫 ⏮️ 🚀 🖕.
```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial001.py!}
+{!../../docs_src/python_types/tutorial001.py!}
```
### ✍ ⚫️
@@ -80,7 +83,7 @@ John Doe
👈 "🆎 🔑":
```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial002.py!}
+{!../../docs_src/python_types/tutorial002.py!}
```
👈 🚫 🎏 📣 🔢 💲 💖 🔜 ⏮️:
@@ -110,7 +113,7 @@ John Doe
✅ 👉 🔢, ⚫️ ⏪ ✔️ 🆎 🔑:
```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial003.py!}
+{!../../docs_src/python_types/tutorial003.py!}
```
↩️ 👨🎨 💭 🆎 🔢, 👆 🚫 🕴 🤚 🛠️, 👆 🤚 ❌ ✅:
@@ -120,7 +123,7 @@ John Doe
🔜 👆 💭 👈 👆 ✔️ 🔧 ⚫️, 🗜 `age` 🎻 ⏮️ `str(age)`:
```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial004.py!}
+{!../../docs_src/python_types/tutorial004.py!}
```
## 📣 🆎
@@ -141,7 +144,7 @@ John Doe
* `bytes`
```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial005.py!}
+{!../../docs_src/python_types/tutorial005.py!}
```
### 💊 🆎 ⏮️ 🆎 🔢
@@ -164,45 +167,55 @@ John Doe
🖼, ➡️ 🔬 🔢 `list` `str`.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ⚪️➡️ `typing`, 🗄 `List` (⏮️ 🔠 `L`):
+⚪️➡️ `typing`, 🗄 `List` (⏮️ 🔠 `L`):
+
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial006.py!}
+```
- ``` Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial006.py!}
- ```
+📣 🔢, ⏮️ 🎏 ❤ (`:`) ❕.
- 📣 🔢, ⏮️ 🎏 ❤ (`:`) ❕.
+🆎, 🚮 `List` 👈 👆 🗄 ⚪️➡️ `typing`.
- 🆎, 🚮 `List` 👈 👆 🗄 ⚪️➡️ `typing`.
+📇 🆎 👈 🔌 🔗 🆎, 👆 🚮 👫 ⬜ 🗜:
- 📇 🆎 👈 🔌 🔗 🆎, 👆 🚮 👫 ⬜ 🗜:
+```Python hl_lines="4"
+{!> ../../docs_src/python_types/tutorial006.py!}
+```
- ```Python hl_lines="4"
- {!> ../../../docs_src/python_types/tutorial006.py!}
- ```
+////
-=== "🐍 3️⃣.9️⃣ & 🔛"
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
- 📣 🔢, ⏮️ 🎏 ❤ (`:`) ❕.
+📣 🔢, ⏮️ 🎏 ❤ (`:`) ❕.
- 🆎, 🚮 `list`.
+🆎, 🚮 `list`.
- 📇 🆎 👈 🔌 🔗 🆎, 👆 🚮 👫 ⬜ 🗜:
+📇 🆎 👈 🔌 🔗 🆎, 👆 🚮 👫 ⬜ 🗜:
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial006_py39.py!}
- ```
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial006_py39.py!}
+```
-!!! info
- 👈 🔗 🆎 ⬜ 🗜 🤙 "🆎 🔢".
+////
- 👉 💼, `str` 🆎 🔢 🚶♀️ `List` (⚖️ `list` 🐍 3️⃣.9️⃣ & 🔛).
+/// info
+
+👈 🔗 🆎 ⬜ 🗜 🤙 "🆎 🔢".
+
+👉 💼, `str` 🆎 🔢 🚶♀️ `List` (⚖️ `list` 🐍 3️⃣.9️⃣ & 🔛).
+
+///
👈 ⛓: "🔢 `items` `list`, & 🔠 🏬 👉 📇 `str`".
-!!! tip
- 🚥 👆 ⚙️ 🐍 3️⃣.9️⃣ ⚖️ 🔛, 👆 🚫 ✔️ 🗄 `List` ⚪️➡️ `typing`, 👆 💪 ⚙️ 🎏 🥔 `list` 🆎 ↩️.
+/// tip
+
+🚥 👆 ⚙️ 🐍 3️⃣.9️⃣ ⚖️ 🔛, 👆 🚫 ✔️ 🗄 `List` ⚪️➡️ `typing`, 👆 💪 ⚙️ 🎏 🥔 `list` 🆎 ↩️.
+
+///
🔨 👈, 👆 👨🎨 💪 🚚 🐕🦺 ⏪ 🏭 🏬 ⚪️➡️ 📇:
@@ -218,17 +231,21 @@ John Doe
👆 🔜 🎏 📣 `tuple`Ⓜ & `set`Ⓜ:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial007.py!}
- ```
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial007.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial007_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
+
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial007_py39.py!}
+```
+
+////
👉 ⛓:
@@ -243,17 +260,21 @@ John Doe
🥈 🆎 🔢 💲 `dict`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial008.py!}
+```
+
+////
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial008.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.9️⃣ & 🔛"
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial008_py39.py!}
+```
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial008_py39.py!}
- ```
+////
👉 ⛓:
@@ -269,17 +290,21 @@ John Doe
🐍 3️⃣.1️⃣0️⃣ 📤 **🎛 ❕** 🌐❔ 👆 💪 🚮 💪 🆎 👽 ⏸ ⏸ (`|`).
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial008b.py!}
+```
+
+////
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial008b.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial008b_py310.py!}
+```
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial008b_py310.py!}
- ```
+////
👯♂️ 💼 👉 ⛓ 👈 `item` 💪 `int` ⚖️ `str`.
@@ -290,7 +315,7 @@ John Doe
🐍 3️⃣.6️⃣ & 🔛 (✅ 🐍 3️⃣.1️⃣0️⃣) 👆 💪 📣 ⚫️ 🏭 & ⚙️ `Optional` ⚪️➡️ `typing` 🕹.
```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009.py!}
+{!../../docs_src/python_types/tutorial009.py!}
```
⚙️ `Optional[str]` ↩️ `str` 🔜 ➡️ 👨🎨 ℹ 👆 🔍 ❌ 🌐❔ 👆 💪 🤔 👈 💲 🕧 `str`, 🕐❔ ⚫️ 💪 🤙 `None` 💁♂️.
@@ -299,23 +324,29 @@ John Doe
👉 ⛓ 👈 🐍 3️⃣.1️⃣0️⃣, 👆 💪 ⚙️ `Something | None`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial009.py!}
+```
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial009.py!}
- ```
+////
-=== "🐍 3️⃣.6️⃣ & 🔛 - 🎛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛 - 🎛
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial009b.py!}
- ```
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial009b.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial009_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial009_py310.py!}
+```
+
+////
#### ⚙️ `Union` ⚖️ `Optional`
@@ -333,7 +364,7 @@ John Doe
🖼, ➡️ ✊ 👉 🔢:
```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009c.py!}
+{!../../docs_src/python_types/tutorial009c.py!}
```
🔢 `name` 🔬 `Optional[str]`, ✋️ ⚫️ **🚫 📦**, 👆 🚫🔜 🤙 🔢 🍵 🔢:
@@ -351,7 +382,7 @@ say_hi(name=None) # This works, None is valid 🎉
👍 📰, 🕐 👆 🔛 🐍 3️⃣.1️⃣0️⃣ 👆 🏆 🚫 ✔️ 😟 🔃 👈, 👆 🔜 💪 🎯 ⚙️ `|` 🔬 🇪🇺 🆎:
```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009c_py310.py!}
+{!../../docs_src/python_types/tutorial009c_py310.py!}
```
& ⤴️ 👆 🏆 🚫 ✔️ 😟 🔃 📛 💖 `Optional` & `Union`. 👶
@@ -360,47 +391,53 @@ say_hi(name=None) # This works, None is valid 🎉
👉 🆎 👈 ✊ 🆎 🔢 ⬜ 🗜 🤙 **💊 🆎** ⚖️ **💊**, 🖼:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+* `List`
+* `Tuple`
+* `Set`
+* `Dict`
+* `Union`
+* `Optional`
+* ...& 🎏.
- * `List`
- * `Tuple`
- * `Set`
- * `Dict`
- * `Union`
- * `Optional`
- * ...& 🎏.
+////
-=== "🐍 3️⃣.9️⃣ & 🔛"
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
- 👆 💪 ⚙️ 🎏 💽 🆎 💊 (⏮️ ⬜ 🗜 & 🆎 🔘):
+👆 💪 ⚙️ 🎏 💽 🆎 💊 (⏮️ ⬜ 🗜 & 🆎 🔘):
- * `list`
- * `tuple`
- * `set`
- * `dict`
+* `list`
+* `tuple`
+* `set`
+* `dict`
- & 🎏 ⏮️ 🐍 3️⃣.6️⃣, ⚪️➡️ `typing` 🕹:
+ & 🎏 ⏮️ 🐍 3️⃣.6️⃣, ⚪️➡️ `typing` 🕹:
- * `Union`
- * `Optional`
- * ...& 🎏.
+* `Union`
+* `Optional`
+* ...& 🎏.
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- 👆 💪 ⚙️ 🎏 💽 🆎 💊 (⏮️ ⬜ 🗜 & 🆎 🔘):
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
- * `list`
- * `tuple`
- * `set`
- * `dict`
+👆 💪 ⚙️ 🎏 💽 🆎 💊 (⏮️ ⬜ 🗜 & 🆎 🔘):
- & 🎏 ⏮️ 🐍 3️⃣.6️⃣, ⚪️➡️ `typing` 🕹:
+* `list`
+* `tuple`
+* `set`
+* `dict`
- * `Union`
- * `Optional` (🎏 ⏮️ 🐍 3️⃣.6️⃣)
- * ...& 🎏.
+ & 🎏 ⏮️ 🐍 3️⃣.6️⃣, ⚪️➡️ `typing` 🕹:
- 🐍 3️⃣.1️⃣0️⃣, 🎛 ⚙️ 💊 `Union` & `Optional`, 👆 💪 ⚙️ ⏸ ⏸ (`|`) 📣 🇪🇺 🆎.
+* `Union`
+* `Optional` (🎏 ⏮️ 🐍 3️⃣.6️⃣)
+* ...& 🎏.
+
+🐍 3️⃣.1️⃣0️⃣, 🎛 ⚙️ 💊 `Union` & `Optional`, 👆 💪 ⚙️ ⏸ ⏸ (`|`) 📣 🇪🇺 🆎.
+
+////
### 🎓 🆎
@@ -409,13 +446,13 @@ say_hi(name=None) # This works, None is valid 🎉
➡️ 💬 👆 ✔️ 🎓 `Person`, ⏮️ 📛:
```Python hl_lines="1-3"
-{!../../../docs_src/python_types/tutorial010.py!}
+{!../../docs_src/python_types/tutorial010.py!}
```
⤴️ 👆 💪 📣 🔢 🆎 `Person`:
```Python hl_lines="6"
-{!../../../docs_src/python_types/tutorial010.py!}
+{!../../docs_src/python_types/tutorial010.py!}
```
& ⤴️, 🔄, 👆 🤚 🌐 👨🎨 🐕🦺:
@@ -424,7 +461,7 @@ say_hi(name=None) # This works, None is valid 🎉
## Pydantic 🏷
-Pydantic 🐍 🗃 🎭 📊 🔬.
+Pydantic 🐍 🗃 🎭 📊 🔬.
👆 📣 "💠" 💽 🎓 ⏮️ 🔢.
@@ -436,33 +473,45 @@ say_hi(name=None) # This works, None is valid 🎉
🖼 ⚪️➡️ 🛂 Pydantic 🩺:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python
- {!> ../../../docs_src/python_types/tutorial011.py!}
- ```
+```Python
+{!> ../../docs_src/python_types/tutorial011.py!}
+```
+
+////
+
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
+
+```Python
+{!> ../../docs_src/python_types/tutorial011_py39.py!}
+```
+
+////
-=== "🐍 3️⃣.9️⃣ & 🔛"
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
- ```Python
- {!> ../../../docs_src/python_types/tutorial011_py39.py!}
- ```
+```Python
+{!> ../../docs_src/python_types/tutorial011_py310.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python
- {!> ../../../docs_src/python_types/tutorial011_py310.py!}
- ```
+/// info
-!!! info
- 💡 🌖 🔃 Pydantic, ✅ 🚮 🩺.
+💡 🌖 🔃 Pydantic, ✅ 🚮 🩺.
+
+///
**FastAPI** 🌐 ⚓️ 🔛 Pydantic.
👆 🔜 👀 📚 🌅 🌐 👉 💡 [🔰 - 👩💻 🦮](tutorial/index.md){.internal-link target=_blank}.
-!!! tip
- Pydantic ✔️ 🎁 🎭 🕐❔ 👆 ⚙️ `Optional` ⚖️ `Union[Something, None]` 🍵 🔢 💲, 👆 💪 ✍ 🌅 🔃 ⚫️ Pydantic 🩺 🔃 ✔ 📦 🏑.
+/// tip
+
+Pydantic ✔️ 🎁 🎭 🕐❔ 👆 ⚙️ `Optional` ⚖️ `Union[Something, None]` 🍵 🔢 💲, 👆 💪 ✍ 🌅 🔃 ⚫️ Pydantic 🩺 🔃 ✔ 📦 🏑.
+
+///
## 🆎 🔑 **FastAPI**
@@ -486,5 +535,8 @@ say_hi(name=None) # This works, None is valid 🎉
⚠ 👜 👈 ⚙️ 🐩 🐍 🆎, 👁 🥉 (↩️ ❎ 🌖 🎓, 👨🎨, ♒️), **FastAPI** 🔜 📚 👷 👆.
-!!! info
- 🚥 👆 ⏪ 🚶 🔘 🌐 🔰 & 👟 🔙 👀 🌅 🔃 🆎, 👍 ℹ "🎮 🎼" ⚪️➡️ `mypy`.
+/// info
+
+🚥 👆 ⏪ 🚶 🔘 🌐 🔰 & 👟 🔙 👀 🌅 🔃 🆎, 👍 ℹ "🎮 🎼" ⚪️➡️ `mypy`.
+
+///
diff --git a/docs/em/docs/tutorial/background-tasks.md b/docs/em/docs/tutorial/background-tasks.md
index e28ead415..aed60c754 100644
--- a/docs/em/docs/tutorial/background-tasks.md
+++ b/docs/em/docs/tutorial/background-tasks.md
@@ -15,9 +15,7 @@
🥇, 🗄 `BackgroundTasks` & 🔬 🔢 👆 *➡ 🛠️ 🔢* ⏮️ 🆎 📄 `BackgroundTasks`:
-```Python hl_lines="1 13"
-{!../../../docs_src/background_tasks/tutorial001.py!}
-```
+{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *}
**FastAPI** 🔜 ✍ 🎚 🆎 `BackgroundTasks` 👆 & 🚶♀️ ⚫️ 👈 🔢.
@@ -33,17 +31,13 @@
& ✍ 🛠️ 🚫 ⚙️ `async` & `await`, 👥 🔬 🔢 ⏮️ 😐 `def`:
-```Python hl_lines="6-9"
-{!../../../docs_src/background_tasks/tutorial001.py!}
-```
+{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *}
## 🚮 🖥 📋
🔘 👆 *➡ 🛠️ 🔢*, 🚶♀️ 👆 📋 🔢 *🖥 📋* 🎚 ⏮️ 👩🔬 `.add_task()`:
-```Python hl_lines="14"
-{!../../../docs_src/background_tasks/tutorial001.py!}
-```
+{* ../../docs_src/background_tasks/tutorial001.py hl[14] *}
`.add_task()` 📨 ❌:
@@ -57,17 +51,7 @@
**FastAPI** 💭 ⚫️❔ 🔠 💼 & ❔ 🏤-⚙️ 🎏 🎚, 👈 🌐 🖥 📋 🔗 👯♂️ & 🏃 🖥 ⏮️:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="13 15 22 25"
- {!> ../../../docs_src/background_tasks/tutorial002.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="11 13 20 23"
- {!> ../../../docs_src/background_tasks/tutorial002_py310.py!}
- ```
+{* ../../docs_src/background_tasks/tutorial002.py hl[13,15,22,25] *}
👉 🖼, 📧 🔜 ✍ `log.txt` 📁 *⏮️* 📨 📨.
@@ -93,8 +77,6 @@
👫 😑 🚚 🌖 🏗 📳, 📧/👨🏭 📤 👨💼, 💖 ✳ ⚖️ ✳, ✋️ 👫 ✔ 👆 🏃 🖥 📋 💗 🛠️, & ✴️, 💗 💽.
-👀 🖼, ✅ [🏗 🚂](../project-generation.md){.internal-link target=_blank}, 👫 🌐 🔌 🥒 ⏪ 📶.
-
✋️ 🚥 👆 💪 🔐 🔢 & 🎚 ⚪️➡️ 🎏 **FastAPI** 📱, ⚖️ 👆 💪 🎭 🤪 🖥 📋 (💖 📨 📧 📨), 👆 💪 🎯 ⚙️ `BackgroundTasks`.
## 🌃
diff --git a/docs/em/docs/tutorial/bigger-applications.md b/docs/em/docs/tutorial/bigger-applications.md
index 7b4694387..78a321ae6 100644
--- a/docs/em/docs/tutorial/bigger-applications.md
+++ b/docs/em/docs/tutorial/bigger-applications.md
@@ -4,8 +4,11 @@
**FastAPI** 🚚 🏪 🧰 📊 👆 🈸 ⏪ 🚧 🌐 💪.
-!!! info
- 🚥 👆 👟 ⚪️➡️ 🏺, 👉 🔜 🌓 🏺 📗.
+/// info
+
+🚥 👆 👟 ⚪️➡️ 🏺, 👉 🔜 🌓 🏺 📗.
+
+///
## 🖼 📁 📊
@@ -26,16 +29,19 @@
│ └── admin.py
```
-!!! tip
- 📤 📚 `__init__.py` 📁: 1️⃣ 🔠 📁 ⚖️ 📁.
+/// tip
+
+📤 📚 `__init__.py` 📁: 1️⃣ 🔠 📁 ⚖️ 📁.
- 👉 ⚫️❔ ✔ 🏭 📟 ⚪️➡️ 1️⃣ 📁 🔘 ➕1️⃣.
+👉 ⚫️❔ ✔ 🏭 📟 ⚪️➡️ 1️⃣ 📁 🔘 ➕1️⃣.
- 🖼, `app/main.py` 👆 💪 ✔️ ⏸ 💖:
+🖼, `app/main.py` 👆 💪 ✔️ ⏸ 💖:
+
+```
+from app.routers import items
+```
- ```
- from app.routers import items
- ```
+///
* `app` 📁 🔌 🌐. & ⚫️ ✔️ 🛁 📁 `app/__init__.py`, ⚫️ "🐍 📦" (🗃 "🐍 🕹"): `app`.
* ⚫️ 🔌 `app/main.py` 📁. ⚫️ 🔘 🐍 📦 (📁 ⏮️ 📁 `__init__.py`), ⚫️ "🕹" 👈 📦: `app.main`.
@@ -46,7 +52,7 @@
* 📤 📁 `app/internal/` ⏮️ ➕1️⃣ 📁 `__init__.py`, ⚫️ ➕1️⃣ "🐍 📦": `app.internal`.
* & 📁 `app/internal/admin.py` ➕1️⃣ 🔁: `app.internal.admin`.
-get
🛠️
-!!! info "`@decorator` ℹ"
- 👈 `@something` ❕ 🐍 🤙 "👨🎨".
+/// info | `@decorator` ℹ
+
+👈 `@something` ❕ 🐍 🤙 "👨🎨".
+
+👆 🚮 ⚫️ 🔛 🔝 🔢. 💖 📶 📔 👒 (👤 💭 👈 🌐❔ ⚖ 👟 ⚪️➡️).
- 👆 🚮 ⚫️ 🔛 🔝 🔢. 💖 📶 📔 👒 (👤 💭 👈 🌐❔ ⚖ 👟 ⚪️➡️).
+ "👨🎨" ✊ 🔢 🔛 & 🔨 🕳 ⏮️ ⚫️.
- "👨🎨" ✊ 🔢 🔛 & 🔨 🕳 ⏮️ ⚫️.
+👆 💼, 👉 👨🎨 💬 **FastAPI** 👈 🔢 🔛 🔗 **➡** `/` ⏮️ **🛠️** `get`.
- 👆 💼, 👉 👨🎨 💬 **FastAPI** 👈 🔢 🔛 🔗 **➡** `/` ⏮️ **🛠️** `get`.
+⚫️ "**➡ 🛠️ 👨🎨**".
- ⚫️ "**➡ 🛠️ 👨🎨**".
+///
👆 💪 ⚙️ 🎏 🛠️:
@@ -274,14 +276,17 @@ https://example.com/items/foo
* `@app.patch()`
* `@app.trace()`
-!!! tip
- 👆 🆓 ⚙️ 🔠 🛠️ (🇺🇸🔍 👩🔬) 👆 🎋.
+/// tip
+
+👆 🆓 ⚙️ 🔠 🛠️ (🇺🇸🔍 👩🔬) 👆 🎋.
+
+**FastAPI** 🚫 🛠️ 🙆 🎯 🔑.
- **FastAPI** 🚫 🛠️ 🙆 🎯 🔑.
+ℹ 📥 🎁 📄, 🚫 📄.
- ℹ 📥 🎁 📄, 🚫 📄.
+🖼, 🕐❔ ⚙️ 🕹 👆 🛎 🎭 🌐 🎯 ⚙️ 🕴 `POST` 🛠️.
- 🖼, 🕐❔ ⚙️ 🕹 👆 🛎 🎭 🌐 🎯 ⚙️ 🕴 `POST` 🛠️.
+///
### 🔁 4️⃣: 🔬 **➡ 🛠️ 🔢**
@@ -291,9 +296,7 @@ https://example.com/items/foo
* **🛠️**: `get`.
* **🔢**: 🔢 🔛 "👨🎨" (🔛 `@app.get("/")`).
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[7] *}
👉 🐍 🔢.
@@ -305,18 +308,17 @@ https://example.com/items/foo
👆 💪 🔬 ⚫️ 😐 🔢 ↩️ `async def`:
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial003.py!}
-```
+{* ../../docs_src/first_steps/tutorial003.py hl[7] *}
+
+/// note
-!!! note
- 🚥 👆 🚫 💭 🔺, ✅ [🔁: *"🏃 ❓"*](../async.md#in-a-hurry){.internal-link target=_blank}.
+🚥 👆 🚫 💭 🔺, ✅ [🔁: *"🏃 ❓"*](../async.md#_2){.internal-link target=_blank}.
+
+///
### 🔁 5️⃣: 📨 🎚
-```Python hl_lines="8"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[8] *}
👆 💪 📨 `dict`, `list`, ⭐ 💲 `str`, `int`, ♒️.
diff --git a/docs/em/docs/tutorial/handling-errors.md b/docs/em/docs/tutorial/handling-errors.md
index ef7bbfa65..d73b730e1 100644
--- a/docs/em/docs/tutorial/handling-errors.md
+++ b/docs/em/docs/tutorial/handling-errors.md
@@ -25,9 +25,7 @@
### 🗄 `HTTPException`
-```Python hl_lines="1"
-{!../../../docs_src/handling_errors/tutorial001.py!}
-```
+{* ../../docs_src/handling_errors/tutorial001.py hl[1] *}
### 🤚 `HTTPException` 👆 📟
@@ -41,9 +39,7 @@
👉 🖼, 🕐❔ 👩💻 📨 🏬 🆔 👈 🚫 🔀, 🤚 ⚠ ⏮️ 👔 📟 `404`:
-```Python hl_lines="11"
-{!../../../docs_src/handling_errors/tutorial001.py!}
-```
+{* ../../docs_src/handling_errors/tutorial001.py hl[11] *}
### 📉 📨
@@ -63,12 +59,15 @@
}
```
-!!! tip
- 🕐❔ 🙋♀ `HTTPException`, 👆 💪 🚶♀️ 🙆 💲 👈 💪 🗜 🎻 🔢 `detail`, 🚫 🕴 `str`.
+/// tip
+
+🕐❔ 🙋♀ `HTTPException`, 👆 💪 🚶♀️ 🙆 💲 👈 💪 🗜 🎻 🔢 `detail`, 🚫 🕴 `str`.
+
+👆 💪 🚶♀️ `dict`, `list`, ♒️.
- 👆 💪 🚶♀️ `dict`, `list`, ♒️.
+👫 🍵 🔁 **FastAPI** & 🗜 🎻.
- 👫 🍵 🔁 **FastAPI** & 🗜 🎻.
+///
## 🚮 🛃 🎚
@@ -78,9 +77,7 @@
✋️ 💼 👆 💪 ⚫️ 🏧 😐, 👆 💪 🚮 🛃 🎚:
-```Python hl_lines="14"
-{!../../../docs_src/handling_errors/tutorial002.py!}
-```
+{* ../../docs_src/handling_errors/tutorial002.py hl[14] *}
## ❎ 🛃 ⚠ 🐕🦺
@@ -92,9 +89,7 @@
👆 💪 🚮 🛃 ⚠ 🐕🦺 ⏮️ `@app.exception_handler()`:
-```Python hl_lines="5-7 13-18 24"
-{!../../../docs_src/handling_errors/tutorial003.py!}
-```
+{* ../../docs_src/handling_errors/tutorial003.py hl[5:7,13:18,24] *}
📥, 🚥 👆 📨 `/unicorns/yolo`, *➡ 🛠️* 🔜 `raise` `UnicornException`.
@@ -106,10 +101,13 @@
{"message": "Oops! yolo did something. There goes a rainbow..."}
```
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette.requests import Request` & `from starlette.responses import JSONResponse`.
+/// note | 📡 ℹ
+
+👆 💪 ⚙️ `from starlette.requests import Request` & `from starlette.responses import JSONResponse`.
+
+**FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. 🎏 ⏮️ `Request`.
- **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. 🎏 ⏮️ `Request`.
+///
## 🔐 🔢 ⚠ 🐕🦺
@@ -129,9 +127,7 @@
⚠ 🐕🦺 🔜 📨 `Request` & ⚠.
-```Python hl_lines="2 14-16"
-{!../../../docs_src/handling_errors/tutorial004.py!}
-```
+{* ../../docs_src/handling_errors/tutorial004.py hl[2,14:16] *}
🔜, 🚥 👆 🚶 `/items/foo`, ↩️ 💆♂ 🔢 🎻 ❌ ⏮️:
@@ -160,10 +156,13 @@ path -> item_id
#### `RequestValidationError` 🆚 `ValidationError`
-!!! warning
- 👫 📡 ℹ 👈 👆 💪 🚶 🚥 ⚫️ 🚫 ⚠ 👆 🔜.
+/// warning
+
+👫 📡 ℹ 👈 👆 💪 🚶 🚥 ⚫️ 🚫 ⚠ 👆 🔜.
-`RequestValidationError` 🎧-🎓 Pydantic `ValidationError`.
+///
+
+`RequestValidationError` 🎧-🎓 Pydantic `ValidationError`.
**FastAPI** ⚙️ ⚫️ 👈, 🚥 👆 ⚙️ Pydantic 🏷 `response_model`, & 👆 💽 ✔️ ❌, 👆 🔜 👀 ❌ 👆 🕹.
@@ -179,14 +178,15 @@ path -> item_id
🖼, 👆 💪 💚 📨 ✅ ✍ 📨 ↩️ 🎻 👫 ❌:
-```Python hl_lines="3-4 9-11 22"
-{!../../../docs_src/handling_errors/tutorial004.py!}
-```
+{* ../../docs_src/handling_errors/tutorial004.py hl[3:4,9:11,22] *}
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette.responses import PlainTextResponse`.
+/// note | 📡 ℹ
- **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃.
+👆 💪 ⚙️ `from starlette.responses import PlainTextResponse`.
+
+**FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃.
+
+///
### ⚙️ `RequestValidationError` 💪
@@ -194,9 +194,7 @@ path -> item_id
👆 💪 ⚙️ ⚫️ ⏪ 🛠️ 👆 📱 🕹 💪 & ℹ ⚫️, 📨 ⚫️ 👩💻, ♒️.
-```Python hl_lines="14"
-{!../../../docs_src/handling_errors/tutorial005.py!}
-```
+{* ../../docs_src/handling_errors/tutorial005.py hl[14] *}
🔜 🔄 📨 ❌ 🏬 💖:
@@ -254,8 +252,6 @@ from starlette.exceptions import HTTPException as StarletteHTTPException
🚥 👆 💚 ⚙️ ⚠ ⤴️ ⏮️ 🎏 🔢 ⚠ 🐕🦺 ⚪️➡️ **FastAPI**, 👆 💪 🗄 & 🏤-⚙️ 🔢 ⚠ 🐕🦺 ⚪️➡️ `fastapi.exception_handlers`:
-```Python hl_lines="2-5 15 21"
-{!../../../docs_src/handling_errors/tutorial006.py!}
-```
+{* ../../docs_src/handling_errors/tutorial006.py hl[2:5,15,21] *}
👉 🖼 👆 `print`😅 ❌ ⏮️ 📶 🎨 📧, ✋️ 👆 🤚 💭. 👆 💪 ⚙️ ⚠ & ⤴️ 🏤-⚙️ 🔢 ⚠ 🐕🦺.
diff --git a/docs/em/docs/tutorial/header-params.md b/docs/em/docs/tutorial/header-params.md
index 0f33a1774..fa5e3a22b 100644
--- a/docs/em/docs/tutorial/header-params.md
+++ b/docs/em/docs/tutorial/header-params.md
@@ -6,17 +6,7 @@
🥇 🗄 `Header`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="3"
- {!> ../../../docs_src/header_params/tutorial001.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="1"
- {!> ../../../docs_src/header_params/tutorial001_py310.py!}
- ```
+{* ../../docs_src/header_params/tutorial001.py hl[3] *}
## 📣 `Header` 🔢
@@ -24,25 +14,21 @@
🥇 💲 🔢 💲, 👆 💪 🚶♀️ 🌐 ➕ 🔬 ⚖️ ✍ 🔢:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+{* ../../docs_src/header_params/tutorial001.py hl[9] *}
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial001.py!}
- ```
+/// note | 📡 ℹ
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+`Header` "👭" 🎓 `Path`, `Query` & `Cookie`. ⚫️ 😖 ⚪️➡️ 🎏 ⚠ `Param` 🎓.
- ```Python hl_lines="7"
- {!> ../../../docs_src/header_params/tutorial001_py310.py!}
- ```
+✋️ 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, `Header`, & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓.
-!!! note "📡 ℹ"
- `Header` "👭" 🎓 `Path`, `Query` & `Cookie`. ⚫️ 😖 ⚪️➡️ 🎏 ⚠ `Param` 🎓.
+///
- ✋️ 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, `Header`, & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓.
+/// info
-!!! info
- 📣 🎚, 👆 💪 ⚙️ `Header`, ↩️ ⏪ 🔢 🔜 🔬 🔢 🔢.
+📣 🎚, 👆 💪 ⚙️ `Header`, ↩️ ⏪ 🔢 🔜 🔬 🔢 🔢.
+
+///
## 🏧 🛠️
@@ -60,20 +46,13 @@
🚥 🤔 👆 💪 ❎ 🏧 🛠️ 🎦 🔠, ⚒ 🔢 `convert_underscores` `Header` `False`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/header_params/tutorial002.py!}
- ```
+{* ../../docs_src/header_params/tutorial002.py hl[10] *}
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+/// warning
- ```Python hl_lines="8"
- {!> ../../../docs_src/header_params/tutorial002_py310.py!}
- ```
+⏭ ⚒ `convert_underscores` `False`, 🐻 🤯 👈 🇺🇸🔍 🗳 & 💽 / ⚙️ 🎚 ⏮️ 🎦.
-!!! warning
- ⏭ ⚒ `convert_underscores` `False`, 🐻 🤯 👈 🇺🇸🔍 🗳 & 💽 / ⚙️ 🎚 ⏮️ 🎦.
+///
## ❎ 🎚
@@ -85,23 +64,7 @@
🖼, 📣 🎚 `X-Token` 👈 💪 😑 🌅 🌘 🕐, 👆 💪 ✍:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial003.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial003_py39.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="7"
- {!> ../../../docs_src/header_params/tutorial003_py310.py!}
- ```
+{* ../../docs_src/header_params/tutorial003.py hl[9] *}
🚥 👆 🔗 ⏮️ 👈 *➡ 🛠️* 📨 2️⃣ 🇺🇸🔍 🎚 💖:
diff --git a/docs/em/docs/tutorial/index.md b/docs/em/docs/tutorial/index.md
index 8536dc3ee..5f7532341 100644
--- a/docs/em/docs/tutorial/index.md
+++ b/docs/em/docs/tutorial/index.md
@@ -1,4 +1,4 @@
-# 🔰 - 👩💻 🦮 - 🎶
+# 🔰 - 👩💻 🦮
👉 🔰 🎦 👆 ❔ ⚙️ **FastAPI** ⏮️ 🌅 🚮 ⚒, 🔁 🔁.
@@ -52,22 +52,25 @@ $ pip install "fastapi[all]"
...👈 🔌 `uvicorn`, 👈 👆 💪 ⚙️ 💽 👈 🏃 👆 📟.
-!!! note
- 👆 💪 ❎ ⚫️ 🍕 🍕.
+/// note
- 👉 ⚫️❔ 👆 🔜 🎲 🕐 👆 💚 🛠️ 👆 🈸 🏭:
+👆 💪 ❎ ⚫️ 🍕 🍕.
- ```
- pip install fastapi
- ```
+👉 ⚫️❔ 👆 🔜 🎲 🕐 👆 💚 🛠️ 👆 🈸 🏭:
- ❎ `uvicorn` 👷 💽:
+```
+pip install "fastapi[standard]"
+```
+
+❎ `uvicorn` 👷 💽:
+
+```
+pip install "uvicorn[standard]"
+```
- ```
- pip install "uvicorn[standard]"
- ```
+ & 🎏 🔠 📦 🔗 👈 👆 💚 ⚙️.
- & 🎏 🔠 📦 🔗 👈 👆 💚 ⚙️.
+///
## 🏧 👩💻 🦮
diff --git a/docs/em/docs/tutorial/metadata.md b/docs/em/docs/tutorial/metadata.md
index 00098cdf5..eaf605de1 100644
--- a/docs/em/docs/tutorial/metadata.md
+++ b/docs/em/docs/tutorial/metadata.md
@@ -17,12 +17,13 @@
👆 💪 ⚒ 👫 ⏩:
-```Python hl_lines="3-16 19-31"
-{!../../../docs_src/metadata/tutorial001.py!}
-```
+{* ../../docs_src/metadata/tutorial001.py hl[3:16,19:31] *}
-!!! tip
- 👆 💪 ✍ ✍ `description` 🏑 & ⚫️ 🔜 ✍ 🔢.
+/// tip
+
+👆 💪 ✍ ✍ `description` 🏑 & ⚫️ 🔜 ✍ 🔢.
+
+///
⏮️ 👉 📳, 🏧 🛠️ 🩺 🔜 👀 💖:
@@ -48,25 +49,27 @@
✍ 🗃 👆 🔖 & 🚶♀️ ⚫️ `openapi_tags` 🔢:
-```Python hl_lines="3-16 18"
-{!../../../docs_src/metadata/tutorial004.py!}
-```
+{* ../../docs_src/metadata/tutorial004.py hl[3:16,18] *}
👀 👈 👆 💪 ⚙️ ✍ 🔘 📛, 🖼 "💳" 🔜 🎦 🦁 (**💳**) & "🎀" 🔜 🎦 ❕ (_🎀_).
-!!! tip
- 👆 🚫 ✔️ 🚮 🗃 🌐 🔖 👈 👆 ⚙️.
+/// tip
+
+👆 🚫 ✔️ 🚮 🗃 🌐 🔖 👈 👆 ⚙️.
+
+///
### ⚙️ 👆 🔖
⚙️ `tags` 🔢 ⏮️ 👆 *➡ 🛠️* (& `APIRouter`Ⓜ) 🛠️ 👫 🎏 🔖:
-```Python hl_lines="21 26"
-{!../../../docs_src/metadata/tutorial004.py!}
-```
+{* ../../docs_src/metadata/tutorial004.py hl[21,26] *}
+
+/// info
+
+✍ 🌅 🔃 🔖 [➡ 🛠️ 📳](path-operation-configuration.md#_3){.internal-link target=_blank}.
-!!! info
- ✍ 🌅 🔃 🔖 [➡ 🛠️ 📳](../path-operation-configuration/#tags){.internal-link target=_blank}.
+///
### ✅ 🩺
@@ -88,9 +91,7 @@
🖼, ⚒ ⚫️ 🍦 `/api/v1/openapi.json`:
-```Python hl_lines="3"
-{!../../../docs_src/metadata/tutorial002.py!}
-```
+{* ../../docs_src/metadata/tutorial002.py hl[3] *}
🚥 👆 💚 ❎ 🗄 🔗 🍕 👆 💪 ⚒ `openapi_url=None`, 👈 🔜 ❎ 🧾 👩💻 🔢 👈 ⚙️ ⚫️.
@@ -107,6 +108,4 @@
🖼, ⚒ 🦁 🎚 🍦 `/documentation` & ❎ 📄:
-```Python hl_lines="3"
-{!../../../docs_src/metadata/tutorial003.py!}
-```
+{* ../../docs_src/metadata/tutorial003.py hl[3] *}
diff --git a/docs/em/docs/tutorial/middleware.md b/docs/em/docs/tutorial/middleware.md
index 644b4690c..d203471e8 100644
--- a/docs/em/docs/tutorial/middleware.md
+++ b/docs/em/docs/tutorial/middleware.md
@@ -11,10 +11,13 @@
* ⚫️ 💪 🕳 👈 **📨** ⚖️ 🏃 🙆 💪 📟.
* ⤴️ ⚫️ 📨 **📨**.
-!!! note "📡 ℹ"
- 🚥 👆 ✔️ 🔗 ⏮️ `yield`, 🚪 📟 🔜 🏃 *⏮️* 🛠️.
+/// note | 📡 ℹ
- 🚥 📤 🙆 🖥 📋 (📄 ⏪), 👫 🔜 🏃 *⏮️* 🌐 🛠️.
+🚥 👆 ✔️ 🔗 ⏮️ `yield`, 🚪 📟 🔜 🏃 *⏮️* 🛠️.
+
+🚥 📤 🙆 🖥 📋 (📄 ⏪), 👫 🔜 🏃 *⏮️* 🌐 🛠️.
+
+///
## ✍ 🛠️
@@ -28,19 +31,23 @@
* ⤴️ ⚫️ 📨 `response` 🏗 🔗 *➡ 🛠️*.
* 👆 💪 ⤴️ 🔀 🌅 `response` ⏭ 🛬 ⚫️.
-```Python hl_lines="8-9 11 14"
-{!../../../docs_src/middleware/tutorial001.py!}
-```
+{* ../../docs_src/middleware/tutorial001.py hl[8:9,11,14] *}
+
+/// tip
+
+✔️ 🤯 👈 🛃 © 🎚 💪 🚮 ⚙️ '✖-' 🔡.
+
+✋️ 🚥 👆 ✔️ 🛃 🎚 👈 👆 💚 👩💻 🖥 💪 👀, 👆 💪 🚮 👫 👆 ⚜ 📳 ([⚜ (✖️-🇨🇳 ℹ 🤝)](cors.md){.internal-link target=_blank}) ⚙️ 🔢 `expose_headers` 📄 💃 ⚜ 🩺.
+
+///
-!!! tip
- ✔️ 🤯 👈 🛃 © 🎚 💪 🚮 ⚙️ '✖-' 🔡.
+/// note | 📡 ℹ
- ✋️ 🚥 👆 ✔️ 🛃 🎚 👈 👆 💚 👩💻 🖥 💪 👀, 👆 💪 🚮 👫 👆 ⚜ 📳 ([⚜ (✖️-🇨🇳 ℹ 🤝)](cors.md){.internal-link target=_blank}) ⚙️ 🔢 `expose_headers` 📄 💃 ⚜ 🩺.
+👆 💪 ⚙️ `from starlette.requests import Request`.
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette.requests import Request`.
+**FastAPI** 🚚 ⚫️ 🏪 👆, 👩💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃.
- **FastAPI** 🚚 ⚫️ 🏪 👆, 👩💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃.
+///
### ⏭ & ⏮️ `response`
@@ -50,9 +57,7 @@
🖼, 👆 💪 🚮 🛃 🎚 `X-Process-Time` ⚗ 🕰 🥈 👈 ⚫️ ✊ 🛠️ 📨 & 🏗 📨:
-```Python hl_lines="10 12-13"
-{!../../../docs_src/middleware/tutorial001.py!}
-```
+{* ../../docs_src/middleware/tutorial001.py hl[10,12:13] *}
## 🎏 🛠️
diff --git a/docs/em/docs/tutorial/path-operation-configuration.md b/docs/em/docs/tutorial/path-operation-configuration.md
index 916529258..c6030c089 100644
--- a/docs/em/docs/tutorial/path-operation-configuration.md
+++ b/docs/em/docs/tutorial/path-operation-configuration.md
@@ -2,8 +2,11 @@
📤 📚 🔢 👈 👆 💪 🚶♀️ 👆 *➡ 🛠️ 👨🎨* 🔗 ⚫️.
-!!! warning
- 👀 👈 👫 🔢 🚶♀️ 🔗 *➡ 🛠️ 👨🎨*, 🚫 👆 *➡ 🛠️ 🔢*.
+/// warning
+
+👀 👈 👫 🔢 🚶♀️ 🔗 *➡ 🛠️ 👨🎨*, 🚫 👆 *➡ 🛠️ 🔢*.
+
+///
## 📨 👔 📟
@@ -13,52 +16,23 @@
✋️ 🚥 👆 🚫 💭 ⚫️❔ 🔠 🔢 📟, 👆 💪 ⚙️ ⌨ 📉 `status`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="3 17"
- {!> ../../../docs_src/path_operation_configuration/tutorial001.py!}
- ```
+{* ../../docs_src/path_operation_configuration/tutorial001.py hl[3,17] *}
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- ```Python hl_lines="3 17"
- {!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+👈 👔 📟 🔜 ⚙️ 📨 & 🔜 🚮 🗄 🔗.
- ```Python hl_lines="1 15"
- {!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!}
- ```
+/// note | 📡 ℹ
-👈 👔 📟 🔜 ⚙️ 📨 & 🔜 🚮 🗄 🔗.
+👆 💪 ⚙️ `from starlette import status`.
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette import status`.
+**FastAPI** 🚚 🎏 `starlette.status` `fastapi.status` 🏪 👆, 👩💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃.
- **FastAPI** 🚚 🎏 `starlette.status` `fastapi.status` 🏪 👆, 👩💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃.
+///
## 🔖
👆 💪 🚮 🔖 👆 *➡ 🛠️*, 🚶♀️ 🔢 `tags` ⏮️ `list` `str` (🛎 1️⃣ `str`):
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="17 22 27"
- {!> ../../../docs_src/path_operation_configuration/tutorial002.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- ```Python hl_lines="17 22 27"
- {!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="15 20 25"
- {!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!}
- ```
+{* ../../docs_src/path_operation_configuration/tutorial002.py hl[17,22,27] *}
👫 🔜 🚮 🗄 🔗 & ⚙️ 🏧 🧾 🔢:
@@ -72,31 +46,13 @@
**FastAPI** 🐕🦺 👈 🎏 🌌 ⏮️ ✅ 🎻:
-```Python hl_lines="1 8-10 13 18"
-{!../../../docs_src/path_operation_configuration/tutorial002b.py!}
-```
+{* ../../docs_src/path_operation_configuration/tutorial002b.py hl[1,8:10,13,18] *}
## 📄 & 📛
👆 💪 🚮 `summary` & `description`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="20-21"
- {!> ../../../docs_src/path_operation_configuration/tutorial003.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- ```Python hl_lines="20-21"
- {!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!}
- ```
+{* ../../docs_src/path_operation_configuration/tutorial003.py hl[20:21] *}
## 📛 ⚪️➡️ #️⃣
@@ -104,23 +60,7 @@
👆 💪 ✍ ✍ #️⃣ , ⚫️ 🔜 🔬 & 🖥 ☑ (✊ 🔘 🏧 #️⃣ 📐).
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="19-27"
- {!> ../../../docs_src/path_operation_configuration/tutorial004.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- ```Python hl_lines="19-27"
- {!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="17-25"
- {!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!}
- ```
+{* ../../docs_src/path_operation_configuration/tutorial004.py hl[19:27] *}
⚫️ 🔜 ⚙️ 🎓 🩺:
@@ -130,31 +70,21 @@
👆 💪 ✔ 📨 📛 ⏮️ 🔢 `response_description`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="21"
- {!> ../../../docs_src/path_operation_configuration/tutorial005.py!}
- ```
+{* ../../docs_src/path_operation_configuration/tutorial005.py hl[21] *}
-=== "🐍 3️⃣.9️⃣ & 🔛"
+/// info
- ```Python hl_lines="21"
- {!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!}
- ```
+👀 👈 `response_description` 🔗 🎯 📨, `description` 🔗 *➡ 🛠️* 🏢.
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+///
- ```Python hl_lines="19"
- {!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!}
- ```
+/// check
-!!! info
- 👀 👈 `response_description` 🔗 🎯 📨, `description` 🔗 *➡ 🛠️* 🏢.
+🗄 ✔ 👈 🔠 *➡ 🛠️* 🚚 📨 📛.
-!!! check
- 🗄 ✔ 👈 🔠 *➡ 🛠️* 🚚 📨 📛.
+, 🚥 👆 🚫 🚚 1️⃣, **FastAPI** 🔜 🔁 🏗 1️⃣ "🏆 📨".
- , 🚥 👆 🚫 🚚 1️⃣, **FastAPI** 🔜 🔁 🏗 1️⃣ "🏆 📨".
+///
kwargs
. 🚥 👫 🚫 ✔️ 🔢 💲.
-```Python hl_lines="7"
-{!../../../docs_src/path_params_numeric_validations/tutorial003.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *}
## 🔢 🔬: 👑 🌘 ⚖️ 🌓
@@ -81,9 +60,7 @@
📥, ⏮️ `ge=1`, `item_id` 🔜 💪 🔢 🔢 "`g`🅾 🌘 ⚖️ `e`🅾" `1`.
-```Python hl_lines="8"
-{!../../../docs_src/path_params_numeric_validations/tutorial004.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial004.py hl[8] *}
## 🔢 🔬: 🌘 🌘 & 🌘 🌘 ⚖️ 🌓
@@ -92,9 +69,7 @@
* `gt`: `g`🅾 `t`👲
* `le`: `l`👭 🌘 ⚖️ `e`🅾
-```Python hl_lines="9"
-{!../../../docs_src/path_params_numeric_validations/tutorial005.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial005.py hl[9] *}
## 🔢 🔬: 🎈, 🌘 🌘 & 🌘 🌘
@@ -106,9 +81,7 @@
& 🎏 lt
.
-```Python hl_lines="11"
-{!../../../docs_src/path_params_numeric_validations/tutorial006.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial006.py hl[11] *}
## 🌃
@@ -121,18 +94,24 @@
* `lt`: `l`👭 `t`👲
* `le`: `l`👭 🌘 ⚖️ `e`🅾
-!!! info
- `Query`, `Path`, & 🎏 🎓 👆 🔜 👀 ⏪ 🏿 ⚠ `Param` 🎓.
+/// info
+
+`Query`, `Path`, & 🎏 🎓 👆 🔜 👀 ⏪ 🏿 ⚠ `Param` 🎓.
+
+🌐 👫 💰 🎏 🔢 🌖 🔬 & 🗃 👆 ✔️ 👀.
+
+///
+
+/// note | 📡 ℹ
- 🌐 👫 💰 🎏 🔢 🌖 🔬 & 🗃 👆 ✔️ 👀.
+🕐❔ 👆 🗄 `Query`, `Path` & 🎏 ⚪️➡️ `fastapi`, 👫 🤙 🔢.
-!!! note "📡 ℹ"
- 🕐❔ 👆 🗄 `Query`, `Path` & 🎏 ⚪️➡️ `fastapi`, 👫 🤙 🔢.
+👈 🕐❔ 🤙, 📨 👐 🎓 🎏 📛.
- 👈 🕐❔ 🤙, 📨 👐 🎓 🎏 📛.
+, 👆 🗄 `Query`, ❔ 🔢. & 🕐❔ 👆 🤙 ⚫️, ⚫️ 📨 👐 🎓 🌟 `Query`.
- , 👆 🗄 `Query`, ❔ 🔢. & 🕐❔ 👆 🤙 ⚫️, ⚫️ 📨 👐 🎓 🌟 `Query`.
+👫 🔢 📤 (↩️ ⚙️ 🎓 🔗) 👈 👆 👨🎨 🚫 ™ ❌ 🔃 👫 🆎.
- 👫 🔢 📤 (↩️ ⚙️ 🎓 🔗) 👈 👆 👨🎨 🚫 ™ ❌ 🔃 👫 🆎.
+👈 🌌 👆 💪 ⚙️ 👆 😐 👨🎨 & 🛠️ 🧰 🍵 ✔️ 🚮 🛃 📳 🤷♂ 📚 ❌.
- 👈 🌌 👆 💪 ⚙️ 👆 😐 👨🎨 & 🛠️ 🧰 🍵 ✔️ 🚮 🛃 📳 🤷♂ 📚 ❌.
+///
diff --git a/docs/em/docs/tutorial/path-params.md b/docs/em/docs/tutorial/path-params.md
index ea939b458..a914dc905 100644
--- a/docs/em/docs/tutorial/path-params.md
+++ b/docs/em/docs/tutorial/path-params.md
@@ -2,9 +2,7 @@
👆 💪 📣 ➡ "🔢" ⚖️ "🔢" ⏮️ 🎏 ❕ ⚙️ 🐍 📁 🎻:
-```Python hl_lines="6-7"
-{!../../../docs_src/path_params/tutorial001.py!}
-```
+{* ../../docs_src/path_params/tutorial001.py hl[6:7] *}
💲 ➡ 🔢 `item_id` 🔜 🚶♀️ 👆 🔢 ❌ `item_id`.
@@ -18,14 +16,15 @@
👆 💪 📣 🆎 ➡ 🔢 🔢, ⚙️ 🐩 🐍 🆎 ✍:
-```Python hl_lines="7"
-{!../../../docs_src/path_params/tutorial002.py!}
-```
+{* ../../docs_src/path_params/tutorial002.py hl[7] *}
👉 💼, `item_id` 📣 `int`.
-!!! check
- 👉 🔜 🤝 👆 👨🎨 🐕🦺 🔘 👆 🔢, ⏮️ ❌ ✅, 🛠️, ♒️.
+/// check
+
+👉 🔜 🤝 👆 👨🎨 🐕🦺 🔘 👆 🔢, ⏮️ ❌ ✅, 🛠️, ♒️.
+
+///
## 💽 🛠️
@@ -35,10 +34,13 @@
{"item_id":3}
```
-!!! check
- 👀 👈 💲 👆 🔢 📨 (& 📨) `3`, 🐍 `int`, 🚫 🎻 `"3"`.
+/// check
- , ⏮️ 👈 🆎 📄, **FastAPI** 🤝 👆 🏧 📨 "✍".
+👀 👈 💲 👆 🔢 📨 (& 📨) `3`, 🐍 `int`, 🚫 🎻 `"3"`.
+
+, ⏮️ 👈 🆎 📄, **FastAPI** 🤝 👆 🏧 📨 "✍".
+
+///
## 💽 🔬
@@ -63,12 +65,15 @@
🎏 ❌ 🔜 😑 🚥 👆 🚚 `float` ↩️ `int`,: http://127.0.0.1:8000/items/4.2
-!!! check
- , ⏮️ 🎏 🐍 🆎 📄, **FastAPI** 🤝 👆 💽 🔬.
+/// check
+
+, ⏮️ 🎏 🐍 🆎 📄, **FastAPI** 🤝 👆 💽 🔬.
- 👀 👈 ❌ 🎯 🇵🇸 ⚫️❔ ☝ 🌐❔ 🔬 🚫 🚶♀️.
+👀 👈 ❌ 🎯 🇵🇸 ⚫️❔ ☝ 🌐❔ 🔬 🚫 🚶♀️.
- 👉 🙃 👍 ⏪ 🛠️ & 🛠️ 📟 👈 🔗 ⏮️ 👆 🛠️.
+👉 🙃 👍 ⏪ 🛠️ & 🛠️ 📟 👈 🔗 ⏮️ 👆 🛠️.
+
+///
## 🧾
@@ -76,10 +81,13 @@
POST
.
+✋️ 🕐❔ 📨 🔌 📁, ⚫️ 🗜 `multipart/form-data`. 🚥 👆 ⚙️ `File`, **FastAPI** 🔜 💭 ⚫️ ✔️ 🤚 📁 ⚪️➡️ ☑ 🍕 💪.
-!!! warning
- 👆 💪 📣 💗 `File` & `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `multipart/form-data` ↩️ `application/json`.
+🚥 👆 💚 ✍ 🌖 🔃 👉 🔢 & 📨 🏑, 👳 🏇 🕸 🩺 POST
.
- 👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️.
+///
-## 📦 📁 📂
+/// warning
-👆 💪 ⚒ 📁 📦 ⚙️ 🐩 🆎 ✍ & ⚒ 🔢 💲 `None`:
+👆 💪 📣 💗 `File` & `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `multipart/form-data` ↩️ `application/json`.
+
+👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+///
- ```Python hl_lines="9 17"
- {!> ../../../docs_src/request_files/tutorial001_02.py!}
- ```
+## 📦 📁 📂
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+👆 💪 ⚒ 📁 📦 ⚙️ 🐩 🆎 ✍ & ⚒ 🔢 💲 `None`:
- ```Python hl_lines="7 14"
- {!> ../../../docs_src/request_files/tutorial001_02_py310.py!}
- ```
+{* ../../docs_src/request_files/tutorial001_02.py hl[9,17] *}
## `UploadFile` ⏮️ 🌖 🗃
👆 💪 ⚙️ `File()` ⏮️ `UploadFile`, 🖼, ⚒ 🌖 🗃:
-```Python hl_lines="13"
-{!../../../docs_src/request_files/tutorial001_03.py!}
-```
+{* ../../docs_src/request_files/tutorial001_03.py hl[13] *}
## 💗 📁 📂
@@ -146,40 +149,23 @@ contents = myfile.file.read()
⚙️ 👈, 📣 📇 `bytes` ⚖️ `UploadFile`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+{* ../../docs_src/request_files/tutorial002.py hl[10,15] *}
- ```Python hl_lines="10 15"
- {!> ../../../docs_src/request_files/tutorial002.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
+👆 🔜 📨, 📣, `list` `bytes` ⚖️ `UploadFile`Ⓜ.
- ```Python hl_lines="8 13"
- {!> ../../../docs_src/request_files/tutorial002_py39.py!}
- ```
+/// note | 📡 ℹ
-👆 🔜 📨, 📣, `list` `bytes` ⚖️ `UploadFile`Ⓜ.
+👆 💪 ⚙️ `from starlette.responses import HTMLResponse`.
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette.responses import HTMLResponse`.
+**FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃.
- **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃.
+///
### 💗 📁 📂 ⏮️ 🌖 🗃
& 🎏 🌌 ⏭, 👆 💪 ⚙️ `File()` ⚒ 🌖 🔢, `UploadFile`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="18"
- {!> ../../../docs_src/request_files/tutorial003.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- ```Python hl_lines="16"
- {!> ../../../docs_src/request_files/tutorial003_py39.py!}
- ```
+{* ../../docs_src/request_files/tutorial003.py hl[18] *}
## 🌃
diff --git a/docs/em/docs/tutorial/request-forms-and-files.md b/docs/em/docs/tutorial/request-forms-and-files.md
index 99aeca000..680b1a96a 100644
--- a/docs/em/docs/tutorial/request-forms-and-files.md
+++ b/docs/em/docs/tutorial/request-forms-and-files.md
@@ -2,33 +2,35 @@
👆 💪 🔬 📁 & 📨 🏑 🎏 🕰 ⚙️ `File` & `Form`.
-!!! info
- 📨 📂 📁 & /⚖️ 📨 📊, 🥇 ❎ `python-multipart`.
+/// info
- 🤶 Ⓜ. `pip install python-multipart`.
+📨 📂 📁 & /⚖️ 📨 📊, 🥇 ❎ `python-multipart`.
+
+🤶 Ⓜ. `pip install python-multipart`.
+
+///
## 🗄 `File` & `Form`
-```Python hl_lines="1"
-{!../../../docs_src/request_forms_and_files/tutorial001.py!}
-```
+{* ../../docs_src/request_forms_and_files/tutorial001.py hl[1] *}
## 🔬 `File` & `Form` 🔢
✍ 📁 & 📨 🔢 🎏 🌌 👆 🔜 `Body` ⚖️ `Query`:
-```Python hl_lines="8"
-{!../../../docs_src/request_forms_and_files/tutorial001.py!}
-```
+{* ../../docs_src/request_forms_and_files/tutorial001.py hl[8] *}
📁 & 📨 🏑 🔜 📂 📨 📊 & 👆 🔜 📨 📁 & 📨 🏑.
& 👆 💪 📣 📁 `bytes` & `UploadFile`.
-!!! warning
- 👆 💪 📣 💗 `File` & `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `multipart/form-data` ↩️ `application/json`.
+/// warning
+
+👆 💪 📣 💗 `File` & `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `multipart/form-data` ↩️ `application/json`.
+
+👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️.
- 👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️.
+///
## 🌃
diff --git a/docs/em/docs/tutorial/request-forms.md b/docs/em/docs/tutorial/request-forms.md
index fa74adae5..1cc1ea5dc 100644
--- a/docs/em/docs/tutorial/request-forms.md
+++ b/docs/em/docs/tutorial/request-forms.md
@@ -2,26 +2,25 @@
🕐❔ 👆 💪 📨 📨 🏑 ↩️ 🎻, 👆 💪 ⚙️ `Form`.
-!!! info
- ⚙️ 📨, 🥇 ❎ `python-multipart`.
+/// info
- 🤶 Ⓜ. `pip install python-multipart`.
+⚙️ 📨, 🥇 ❎ `python-multipart`.
+
+🤶 Ⓜ. `pip install python-multipart`.
+
+///
## 🗄 `Form`
🗄 `Form` ⚪️➡️ `fastapi`:
-```Python hl_lines="1"
-{!../../../docs_src/request_forms/tutorial001.py!}
-```
+{* ../../docs_src/request_forms/tutorial001.py hl[1] *}
## 🔬 `Form` 🔢
✍ 📨 🔢 🎏 🌌 👆 🔜 `Body` ⚖️ `Query`:
-```Python hl_lines="7"
-{!../../../docs_src/request_forms/tutorial001.py!}
-```
+{* ../../docs_src/request_forms/tutorial001.py hl[7] *}
🖼, 1️⃣ 🌌 Oauth2️⃣ 🔧 💪 ⚙️ (🤙 "🔐 💧") ⚫️ ✔ 📨 `username` & `password` 📨 🏑.
@@ -29,11 +28,17 @@
⏮️ `Form` 👆 💪 📣 🎏 📳 ⏮️ `Body` (& `Query`, `Path`, `Cookie`), 🔌 🔬, 🖼, 📛 (✅ `user-name` ↩️ `username`), ♒️.
-!!! info
- `Form` 🎓 👈 😖 🔗 ⚪️➡️ `Body`.
+/// info
+
+`Form` 🎓 👈 😖 🔗 ⚪️➡️ `Body`.
+
+///
+
+/// tip
-!!! tip
- 📣 📨 💪, 👆 💪 ⚙️ `Form` 🎯, ↩️ 🍵 ⚫️ 🔢 🔜 🔬 🔢 🔢 ⚖️ 💪 (🎻) 🔢.
+📣 📨 💪, 👆 💪 ⚙️ `Form` 🎯, ↩️ 🍵 ⚫️ 🔢 🔜 🔬 🔢 🔢 ⚖️ 💪 (🎻) 🔢.
+
+///
## 🔃 "📨 🏑"
@@ -41,17 +46,23 @@
**FastAPI** 🔜 ⚒ 💭 ✍ 👈 📊 ⚪️➡️ ▶️️ 🥉 ↩️ 🎻.
-!!! note "📡 ℹ"
- 📊 ⚪️➡️ 📨 🛎 🗜 ⚙️ "📻 🆎" `application/x-www-form-urlencoded`.
+/// note | 📡 ℹ
+
+📊 ⚪️➡️ 📨 🛎 🗜 ⚙️ "📻 🆎" `application/x-www-form-urlencoded`.
+
+✋️ 🕐❔ 📨 🔌 📁, ⚫️ 🗜 `multipart/form-data`. 👆 🔜 ✍ 🔃 🚚 📁 ⏭ 📃.
+
+🚥 👆 💚 ✍ 🌖 🔃 👉 🔢 & 📨 🏑, 👳 🏇 🕸 🩺 POST
.
+
+///
- ✋️ 🕐❔ 📨 🔌 📁, ⚫️ 🗜 `multipart/form-data`. 👆 🔜 ✍ 🔃 🚚 📁 ⏭ 📃.
+/// warning
- 🚥 👆 💚 ✍ 🌖 🔃 👉 🔢 & 📨 🏑, 👳 🏇 🕸 🩺 POST
.
+👆 💪 📣 💗 `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `application/x-www-form-urlencoded` ↩️ `application/json`.
-!!! warning
- 👆 💪 📣 💗 `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `application/x-www-form-urlencoded` ↩️ `application/json`.
+👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️.
- 👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️.
+///
## 🌃
diff --git a/docs/em/docs/tutorial/response-model.md b/docs/em/docs/tutorial/response-model.md
index 6ea4413f8..477376458 100644
--- a/docs/em/docs/tutorial/response-model.md
+++ b/docs/em/docs/tutorial/response-model.md
@@ -4,23 +4,7 @@
👆 💪 ⚙️ **🆎 ✍** 🎏 🌌 👆 🔜 🔢 💽 🔢 **🔢**, 👆 💪 ⚙️ Pydantic 🏷, 📇, 📖, 📊 💲 💖 🔢, 🎻, ♒️.
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="18 23"
- {!> ../../../docs_src/response_model/tutorial001_01.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- ```Python hl_lines="18 23"
- {!> ../../../docs_src/response_model/tutorial001_01_py39.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="16 21"
- {!> ../../../docs_src/response_model/tutorial001_01_py310.py!}
- ```
+{* ../../docs_src/response_model/tutorial001_01.py hl[18,23] *}
FastAPI 🔜 ⚙️ 👉 📨 🆎:
@@ -53,35 +37,25 @@ FastAPI 🔜 ⚙️ 👉 📨 🆎:
* `@app.delete()`
* ♒️.
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
+{* ../../docs_src/response_model/tutorial001.py hl[17,22,24:27] *}
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001_py39.py!}
- ```
+/// note
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+👀 👈 `response_model` 🔢 "👨🎨" 👩🔬 (`get`, `post`, ♒️). 🚫 👆 *➡ 🛠️ 🔢*, 💖 🌐 🔢 & 💪.
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001_py310.py!}
- ```
-
-!!! note
- 👀 👈 `response_model` 🔢 "👨🎨" 👩🔬 (`get`, `post`, ♒️). 🚫 👆 *➡ 🛠️ 🔢*, 💖 🌐 🔢 & 💪.
+///
`response_model` 📨 🎏 🆎 👆 🔜 📣 Pydantic 🏷 🏑,, ⚫️ 💪 Pydantic 🏷, ✋️ ⚫️ 💪, ✅ `list` Pydantic 🏷, 💖 `List[Item]`.
FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & **🗜 & ⛽ 🔢 📊** 🚮 🆎 📄.
-!!! tip
- 🚥 👆 ✔️ ⚠ 🆎 ✅ 👆 👨🎨, ✍, ♒️, 👆 💪 📣 🔢 📨 🆎 `Any`.
+/// tip
+
+🚥 👆 ✔️ ⚠ 🆎 ✅ 👆 👨🎨, ✍, ♒️, 👆 💪 📣 🔢 📨 🆎 `Any`.
- 👈 🌌 👆 💬 👨🎨 👈 👆 😫 🛬 🕳. ✋️ FastAPI 🔜 💽 🧾, 🔬, 🖥, ♒️. ⏮️ `response_model`.
+👈 🌌 👆 💬 👨🎨 👈 👆 😫 🛬 🕳. ✋️ FastAPI 🔜 💽 🧾, 🔬, 🖥, ♒️. ⏮️ `response_model`.
+
+///
### `response_model` 📫
@@ -95,37 +69,20 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & **
📥 👥 📣 `UserIn` 🏷, ⚫️ 🔜 🔌 🔢 🔐:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="9 11"
- {!> ../../../docs_src/response_model/tutorial002.py!}
- ```
+{* ../../docs_src/response_model/tutorial002.py hl[9,11] *}
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+/// info
- ```Python hl_lines="7 9"
- {!> ../../../docs_src/response_model/tutorial002_py310.py!}
- ```
+⚙️ `EmailStr`, 🥇 ❎ `email-validator`.
-!!! info
- ⚙️ `EmailStr`, 🥇 ❎ `email_validator`.
+🤶 Ⓜ. `pip install email-validator`
+⚖️ `pip install pydantic[email]`.
- 🤶 Ⓜ. `pip install email-validator`
- ⚖️ `pip install pydantic[email]`.
+///
& 👥 ⚙️ 👉 🏷 📣 👆 🔢 & 🎏 🏷 📣 👆 🔢:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="18"
- {!> ../../../docs_src/response_model/tutorial002.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="16"
- {!> ../../../docs_src/response_model/tutorial002_py310.py!}
- ```
+{* ../../docs_src/response_model/tutorial002.py hl[18] *}
🔜, 🕐❔ 🖥 🏗 👩💻 ⏮️ 🔐, 🛠️ 🔜 📨 🎏 🔐 📨.
@@ -133,52 +90,25 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & **
✋️ 🚥 👥 ⚙️ 🎏 🏷 ➕1️⃣ *➡ 🛠️*, 👥 💪 📨 👆 👩💻 🔐 🔠 👩💻.
-!!! danger
- 🙅 🏪 ✅ 🔐 👩💻 ⚖️ 📨 ⚫️ 📨 💖 👉, 🚥 👆 💭 🌐 ⚠ & 👆 💭 ⚫️❔ 👆 🔨.
+/// danger
-## 🚮 🔢 🏷
-
-👥 💪 ↩️ ✍ 🔢 🏷 ⏮️ 🔢 🔐 & 🔢 🏷 🍵 ⚫️:
+🙅 🏪 ✅ 🔐 👩💻 ⚖️ 📨 ⚫️ 📨 💖 👉, 🚥 👆 💭 🌐 ⚠ & 👆 💭 ⚫️❔ 👆 🔨.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+///
- ```Python hl_lines="9 11 16"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+## 🚮 🔢 🏷
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+👥 💪 ↩️ ✍ 🔢 🏷 ⏮️ 🔢 🔐 & 🔢 🏷 🍵 ⚫️:
- ```Python hl_lines="9 11 16"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
+{* ../../docs_src/response_model/tutorial003.py hl[9,11,16] *}
📥, ✋️ 👆 *➡ 🛠️ 🔢* 🛬 🎏 🔢 👩💻 👈 🔌 🔐:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
+{* ../../docs_src/response_model/tutorial003.py hl[24] *}
...👥 📣 `response_model` 👆 🏷 `UserOut`, 👈 🚫 🔌 🔐:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
+{* ../../docs_src/response_model/tutorial003.py hl[22] *}
, **FastAPI** 🔜 ✊ 💅 🖥 👅 🌐 💽 👈 🚫 📣 🔢 🏷 (⚙️ Pydantic).
@@ -202,17 +132,7 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & **
& 👈 💼, 👥 💪 ⚙️ 🎓 & 🧬 ✊ 📈 🔢 **🆎 ✍** 🤚 👍 🐕🦺 👨🎨 & 🧰, & 🤚 FastAPI **💽 🖥**.
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="9-13 15-16 20"
- {!> ../../../docs_src/response_model/tutorial003_01.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="7-10 13-14 18"
- {!> ../../../docs_src/response_model/tutorial003_01_py310.py!}
- ```
+{* ../../docs_src/response_model/tutorial003_01.py hl[9:13,15:16,20] *}
⏮️ 👉, 👥 🤚 🏭 🐕🦺, ⚪️➡️ 👨🎨 & ✍ 👉 📟 ☑ ⚖ 🆎, ✋️ 👥 🤚 💽 🖥 ⚪️➡️ FastAPI.
@@ -254,9 +174,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓
🏆 ⚠ 💼 🔜 [🛬 📨 🔗 🔬 ⏪ 🏧 🩺](../advanced/response-directly.md){.internal-link target=_blank}.
-```Python hl_lines="8 10-11"
-{!> ../../../docs_src/response_model/tutorial003_02.py!}
-```
+{* ../../docs_src/response_model/tutorial003_02.py hl[8,10:11] *}
👉 🙅 💼 🍵 🔁 FastAPI ↩️ 📨 🆎 ✍ 🎓 (⚖️ 🏿) `Response`.
@@ -266,9 +184,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓
👆 💪 ⚙️ 🏿 `Response` 🆎 ✍:
-```Python hl_lines="8-9"
-{!> ../../../docs_src/response_model/tutorial003_03.py!}
-```
+{* ../../docs_src/response_model/tutorial003_03.py hl[8:9] *}
👉 🔜 👷 ↩️ `RedirectResponse` 🏿 `Response`, & FastAPI 🔜 🔁 🍵 👉 🙅 💼.
@@ -278,17 +194,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓
🎏 🔜 🔨 🚥 👆 ✔️ 🕳 💖 🇪🇺 🖖 🎏 🆎 🌐❔ 1️⃣ ⚖️ 🌅 👫 🚫 ☑ Pydantic 🆎, 🖼 👉 🔜 ❌ 👶:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/response_model/tutorial003_04.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="8"
- {!> ../../../docs_src/response_model/tutorial003_04_py310.py!}
- ```
+{* ../../docs_src/response_model/tutorial003_04.py hl[10] *}
...👉 ❌ ↩️ 🆎 ✍ 🚫 Pydantic 🆎 & 🚫 👁 `Response` 🎓 ⚖️ 🏿, ⚫️ 🇪🇺 (🙆 2️⃣) 🖖 `Response` & `dict`.
@@ -300,17 +206,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓
👉 💼, 👆 💪 ❎ 📨 🏷 ⚡ ⚒ `response_model=None`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/response_model/tutorial003_05.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="7"
- {!> ../../../docs_src/response_model/tutorial003_05_py310.py!}
- ```
+{* ../../docs_src/response_model/tutorial003_05.py hl[9] *}
👉 🔜 ⚒ FastAPI 🚶 📨 🏷 ⚡ & 👈 🌌 👆 💪 ✔️ 🙆 📨 🆎 ✍ 👆 💪 🍵 ⚫️ 🤕 👆 FastAPI 🈸. 👶
@@ -318,23 +214,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓
👆 📨 🏷 💪 ✔️ 🔢 💲, 💖:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="11 13-14"
- {!> ../../../docs_src/response_model/tutorial004.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- ```Python hl_lines="11 13-14"
- {!> ../../../docs_src/response_model/tutorial004_py39.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="9 11-12"
- {!> ../../../docs_src/response_model/tutorial004_py310.py!}
- ```
+{* ../../docs_src/response_model/tutorial004.py hl[11,13:14] *}
* `description: Union[str, None] = None` (⚖️ `str | None = None` 🐍 3️⃣.1️⃣0️⃣) ✔️ 🔢 `None`.
* `tax: float = 10.5` ✔️ 🔢 `10.5`.
@@ -348,23 +228,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓
👆 💪 ⚒ *➡ 🛠️ 👨🎨* 🔢 `response_model_exclude_unset=True`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial004.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial004_py39.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial004_py310.py!}
- ```
+{* ../../docs_src/response_model/tutorial004.py hl[24] *}
& 👈 🔢 💲 🏆 🚫 🔌 📨, 🕴 💲 🤙 ⚒.
@@ -377,16 +241,22 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓
}
```
-!!! info
- FastAPI ⚙️ Pydantic 🏷 `.dict()` ⏮️ 🚮 `exclude_unset` 🔢 🏆 👉.
+/// info
+
+FastAPI ⚙️ Pydantic 🏷 `.dict()` ⏮️ 🚮 `exclude_unset` 🔢 🏆 👉.
+
+///
+
+/// info
-!!! info
- 👆 💪 ⚙️:
+👆 💪 ⚙️:
- * `response_model_exclude_defaults=True`
- * `response_model_exclude_none=True`
+* `response_model_exclude_defaults=True`
+* `response_model_exclude_none=True`
- 🔬 Pydantic 🩺 `exclude_defaults` & `exclude_none`.
+🔬 Pydantic 🩺 `exclude_defaults` & `exclude_none`.
+
+///
#### 📊 ⏮️ 💲 🏑 ⏮️ 🔢
@@ -421,10 +291,13 @@ FastAPI 🙃 🥃 (🤙, Pydantic 🙃 🥃) 🤔 👈, ✋️ `description`, `t
, 👫 🔜 🔌 🎻 📨.
-!!! tip
- 👀 👈 🔢 💲 💪 🕳, 🚫 🕴 `None`.
+/// tip
+
+👀 👈 🔢 💲 💪 🕳, 🚫 🕴 `None`.
- 👫 💪 📇 (`[]`), `float` `10.5`, ♒️.
+👫 💪 📇 (`[]`), `float` `10.5`, ♒️.
+
+///
### `response_model_include` & `response_model_exclude`
@@ -434,45 +307,31 @@ FastAPI 🙃 🥃 (🤙, Pydantic 🙃 🥃) 🤔 👈, ✋️ `description`, `t
👉 💪 ⚙️ ⏩ ⌨ 🚥 👆 ✔️ 🕴 1️⃣ Pydantic 🏷 & 💚 ❎ 💽 ⚪️➡️ 🔢.
-!!! tip
- ✋️ ⚫️ 👍 ⚙️ 💭 🔛, ⚙️ 💗 🎓, ↩️ 👫 🔢.
+/// tip
+
+✋️ ⚫️ 👍 ⚙️ 💭 🔛, ⚙️ 💗 🎓, ↩️ 👫 🔢.
- 👉 ↩️ 🎻 🔗 🏗 👆 📱 🗄 (& 🩺) 🔜 1️⃣ 🏁 🏷, 🚥 👆 ⚙️ `response_model_include` ⚖️ `response_model_exclude` 🚫 🔢.
+👉 ↩️ 🎻 🔗 🏗 👆 📱 🗄 (& 🩺) 🔜 1️⃣ 🏁 🏷, 🚥 👆 ⚙️ `response_model_include` ⚖️ `response_model_exclude` 🚫 🔢.
- 👉 ✔ `response_model_by_alias` 👈 👷 ➡.
+👉 ✔ `response_model_by_alias` 👈 👷 ➡.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+///
- ```Python hl_lines="31 37"
- {!> ../../../docs_src/response_model/tutorial005.py!}
- ```
+{* ../../docs_src/response_model/tutorial005.py hl[31,37] *}
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+/// tip
- ```Python hl_lines="29 35"
- {!> ../../../docs_src/response_model/tutorial005_py310.py!}
- ```
+❕ `{"name", "description"}` ✍ `set` ⏮️ 📚 2️⃣ 💲.
-!!! tip
- ❕ `{"name", "description"}` ✍ `set` ⏮️ 📚 2️⃣ 💲.
+⚫️ 🌓 `set(["name", "description"])`.
- ⚫️ 🌓 `set(["name", "description"])`.
+///
#### ⚙️ `list`Ⓜ ↩️ `set`Ⓜ
🚥 👆 💭 ⚙️ `set` & ⚙️ `list` ⚖️ `tuple` ↩️, FastAPI 🔜 🗜 ⚫️ `set` & ⚫️ 🔜 👷 ☑:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="31 37"
- {!> ../../../docs_src/response_model/tutorial006.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="29 35"
- {!> ../../../docs_src/response_model/tutorial006_py310.py!}
- ```
+{* ../../docs_src/response_model/tutorial006.py hl[31,37] *}
## 🌃
diff --git a/docs/em/docs/tutorial/response-status-code.md b/docs/em/docs/tutorial/response-status-code.md
index e5149de7d..413ceb916 100644
--- a/docs/em/docs/tutorial/response-status-code.md
+++ b/docs/em/docs/tutorial/response-status-code.md
@@ -8,17 +8,21 @@
* `@app.delete()`
* ♒️.
-```Python hl_lines="6"
-{!../../../docs_src/response_status_code/tutorial001.py!}
-```
+{* ../../docs_src/response_status_code/tutorial001.py hl[6] *}
-!!! note
- 👀 👈 `status_code` 🔢 "👨🎨" 👩🔬 (`get`, `post`, ♒️). 🚫 👆 *➡ 🛠️ 🔢*, 💖 🌐 🔢 & 💪.
+/// note
+
+👀 👈 `status_code` 🔢 "👨🎨" 👩🔬 (`get`, `post`, ♒️). 🚫 👆 *➡ 🛠️ 🔢*, 💖 🌐 🔢 & 💪.
+
+///
`status_code` 🔢 📨 🔢 ⏮️ 🇺🇸🔍 👔 📟.
-!!! info
- `status_code` 💪 👐 📨 `IntEnum`, ✅ 🐍 `http.HTTPStatus`.
+/// info
+
+`status_code` 💪 👐 📨 `IntEnum`, ✅ 🐍 `http.HTTPStatus`.
+
+///
⚫️ 🔜:
@@ -27,15 +31,21 @@
await
support, we should declare our function with normal `def` instead of `async def`.
-
-Also, Couchbase recommends not using a single `Bucket` object in multiple "threads", so, we can just get the bucket directly and pass it to our utility functions:
-
-```Python hl_lines="49-53"
-{!../../../docs_src/nosql_databases/tutorial001.py!}
-```
-
-## Recap
-
-You can integrate any third party NoSQL database, just using their standard packages.
-
-The same applies to any other external tool, system or API.
diff --git a/docs/en/docs/advanced/openapi-callbacks.md b/docs/en/docs/advanced/openapi-callbacks.md
index 71924ce8b..ca9065a89 100644
--- a/docs/en/docs/advanced/openapi-callbacks.md
+++ b/docs/en/docs/advanced/openapi-callbacks.md
@@ -31,14 +31,15 @@ It will have a *path operation* that will receive an `Invoice` body, and a query
This part is pretty normal, most of the code is probably already familiar to you:
-```Python hl_lines="9-13 36-53"
-{!../../../docs_src/openapi_callbacks/tutorial001.py!}
-```
+{* ../../docs_src/openapi_callbacks/tutorial001.py hl[9:13,36:53] *}
+
+/// tip
-!!! 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
@@ -61,10 +62,13 @@ That documentation will show up in the Swagger UI at `/docs` in your API, and it
This example doesn't implement the callback itself (that could be just a line of code), only the documentation part.
-!!! tip
- The actual callback is just an HTTP request.
+/// tip
+
+The actual callback is just an HTTP request.
- When implementing the callback yourself, you could use something like HTTPX or Requests.
+When implementing the callback yourself, you could use something like HTTPX or Requests.
+
+///
## Write the callback documentation code
@@ -74,18 +78,19 @@ But, you already know how to easily create automatic documentation for an API wi
So we are going to use that same knowledge to document how the *external API* should look like... by creating the *path operation(s)* that the external API should implement (the ones your API will call).
-!!! tip
- When writing the code to document a callback, it might be useful to imagine that you are that *external developer*. And that you are currently implementing the *external API*, not *your API*.
+/// tip
+
+When writing the code to document a callback, it might be useful to imagine that you are that *external developer*. And that you are currently implementing the *external API*, not *your API*.
+
+Temporarily adopting this point of view (of the *external developer*) can help you feel like it's more obvious where to put the parameters, the Pydantic model for the body, for the response, etc. for that *external API*.
- Temporarily adopting this point of view (of the *external developer*) can help you feel like it's more obvious where to put the parameters, the Pydantic model for the body, for the response, etc. for that *external API*.
+///
### Create a callback `APIRouter`
First create a new `APIRouter` that will contain one or more callbacks.
-```Python hl_lines="3 25"
-{!../../../docs_src/openapi_callbacks/tutorial001.py!}
-```
+{* ../../docs_src/openapi_callbacks/tutorial001.py hl[3,25] *}
### Create the callback *path operation*
@@ -96,18 +101,16 @@ It should look just like a normal FastAPI *path operation*:
* It should probably have a declaration of the body it should receive, e.g. `body: InvoiceEvent`.
* And it could also have a declaration of the response it should return, e.g. `response_model=InvoiceEventReceived`.
-```Python hl_lines="16-18 21-22 28-32"
-{!../../../docs_src/openapi_callbacks/tutorial001.py!}
-```
+{* ../../docs_src/openapi_callbacks/tutorial001.py hl[16:18,21:22,28:32] *}
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`:
@@ -131,7 +134,7 @@ with a JSON body of:
}
```
-Then *your API* will process the invoice, and at some point later, send a callback request to the `callback_url` (the *external API*):
+then *your API* will process the invoice, and at some point later, send a callback request to the `callback_url` (the *external API*):
```
https://www.external.org/events/invoices/2expen51ve
@@ -154,8 +157,11 @@ and it would expect a response from that *external API* with a JSON body like:
}
```
-!!! tip
- Notice how the callback URL used contains the URL received as a query parameter in `callback_url` (`https://www.external.org/events`) and also the invoice `id` from inside of the JSON body (`2expen51ve`).
+/// tip
+
+Notice how the callback URL used contains the URL received as a query parameter in `callback_url` (`https://www.external.org/events`) and also the invoice `id` from inside of the JSON body (`2expen51ve`).
+
+///
### Add the callback router
@@ -163,17 +169,18 @@ At this point you have the *callback path operation(s)* needed (the one(s) that
Now use the parameter `callbacks` in *your API's path operation decorator* to pass the attribute `.routes` (that's actually just a `list` of routes/*path operations*) from that callback router:
-```Python hl_lines="35"
-{!../../../docs_src/openapi_callbacks/tutorial001.py!}
-```
+{* ../../docs_src/openapi_callbacks/tutorial001.py hl[35] *}
+
+/// tip
+
+Notice that you are not passing the router itself (`invoices_callback_router`) to `callback=`, but the attribute `.routes`, as in `invoices_callback_router.routes`.
-!!! tip
- Notice that you are not passing the router itself (`invoices_callback_router`) to `callback=`, but the attribute `.routes`, as in `invoices_callback_router.routes`.
+///
### Check the docs
-Now you can start your app with Uvicorn and go to http://127.0.0.1:8000/docs.
+Now you can start your app and go to http://127.0.0.1:8000/docs.
-You will see your docs including a "Callback" section for your *path operation* that shows how the *external API* should look like:
+You will see your docs including a "Callbacks" section for your *path operation* that shows how the *external API* should look like:
-
-
+
+
-
-
+
+
@@ -23,11 +29,11 @@
**Documentation**: https://fastapi.tiangolo.com
-**Source Code**: https://github.com/tiangolo/fastapi
+**Source Code**: https://github.com/fastapi/fastapi
---
-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 based on standard Python type hints.
The key features are:
@@ -63,7 +69,7 @@ The key features are:
"_[...] 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._"
-
uvicorn main:app --reload
...fastapi dev main.py
...ujson
- for faster JSON "parsing".
-* email_validator
- for email validation.
+* email-validator
- for email validation.
Used by Starlette:
* httpx
- Required if you want to use the `TestClient`.
* jinja2
- Required if you want to use the default template configuration.
-* python-multipart
- Required if you want to support form "parsing", with `request.form()`.
-* itsdangerous
- Required for `SessionMiddleware` support.
-* pyyaml
- Required for Starlette's `SchemaGenerator` support (you probably don't need it with FastAPI).
-* ujson
- Required if you want to use `UJSONResponse`.
+* python-multipart
- Required if you want to support form "parsing", with `request.form()`.
Used by FastAPI / Starlette:
-* uvicorn
- for the server that loads and serves your application.
-* orjson
- Required if you want to use `ORJSONResponse`.
+* uvicorn
- for the server that loads and serves your application. This includes `uvicorn[standard]`, which includes some dependencies (e.g. `uvloop`) needed for high performance serving.
+* `fastapi-cli` - to provide the `fastapi` command.
+
+### Without `standard` Dependencies
+
+If you don't want to include the `standard` optional dependencies, you can install with `pip install fastapi` instead of `pip install "fastapi[standard]"`.
-You can install all of these with `pip install "fastapi[all]"`.
+### Additional Optional Dependencies
+
+There are some additional dependencies you might want to install.
+
+Additional optional Pydantic dependencies:
+
+* pydantic-settings
- for settings management.
+* pydantic-extra-types
- for extra types to be used with Pydantic.
+
+Additional optional FastAPI dependencies:
+
+* orjson
- Required if you want to use `ORJSONResponse`.
+* ujson
- Required if you want to use `UJSONResponse`.
## License
diff --git a/docs/en/docs/js/chat.js b/docs/en/docs/js/chat.js
deleted file mode 100644
index debdef4da..000000000
--- a/docs/en/docs/js/chat.js
+++ /dev/null
@@ -1,3 +0,0 @@
-((window.gitter = {}).chat = {}).options = {
- room: 'tiangolo/fastapi'
-};
diff --git a/docs/en/docs/js/custom.js b/docs/en/docs/js/custom.js
index 8e3be4c13..4c0ada312 100644
--- a/docs/en/docs/js/custom.js
+++ b/docs/en/docs/js/custom.js
@@ -1,25 +1,3 @@
-const div = document.querySelector('.github-topic-projects')
-
-async function getDataBatch(page) {
- const response = await fetch(`https://api.github.com/search/repositories?q=topic:fastapi&per_page=100&page=${page}`, { headers: { Accept: 'application/vnd.github.mercy-preview+json' } })
- const data = await response.json()
- return data
-}
-
-async function getData() {
- let page = 1
- let data = []
- let dataBatch = await getDataBatch(page)
- data = data.concat(dataBatch.items)
- const totalCount = dataBatch.total_count
- while (data.length < totalCount) {
- page += 1
- dataBatch = await getDataBatch(page)
- data = data.concat(dataBatch.items)
- }
- return data
-}
-
function setupTermynal() {
document.querySelectorAll(".use-termynal").forEach(node => {
node.style.display = "block";
@@ -35,7 +13,7 @@ function setupTermynal() {
function createTermynals() {
document
- .querySelectorAll(`.${termynalActivateClass} .highlight`)
+ .querySelectorAll(`.${termynalActivateClass} .highlight code`)
.forEach(node => {
const text = node.textContent;
const lines = text.split("\n");
@@ -147,7 +125,7 @@ async function showRandomAnnouncement(groupId, timeInterval) {
children = shuffle(children)
let index = 0
const announceRandom = () => {
- children.forEach((el, i) => {el.style.display = "none"});
+ children.forEach((el, i) => { el.style.display = "none" });
children[index].style.display = "block"
index = (index + 1) % children.length
}
@@ -158,23 +136,10 @@ async function showRandomAnnouncement(groupId, timeInterval) {
}
async function main() {
- if (div) {
- data = await getData()
- div.innerHTML = '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).
+* 🔨 Add MkDocs hook that renames sections based on the first index file. PR [#9737](https://github.com/tiangolo/fastapi/pull/9737) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Make cron jobs run only on main repo, not on forks, to avoid error notifications from missing tokens. PR [#9735](https://github.com/tiangolo/fastapi/pull/9735) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update MkDocs for other languages. PR [#9734](https://github.com/tiangolo/fastapi/pull/9734) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Refactor Docs CI, run in multiple workers with a dynamic matrix to optimize speed. PR [#9732](https://github.com/tiangolo/fastapi/pull/9732) by [@tiangolo](https://github.com/tiangolo).
+* 🔥 Remove old internal GitHub Action watch-previews that is no longer needed. PR [#9730](https://github.com/tiangolo/fastapi/pull/9730) by [@tiangolo](https://github.com/tiangolo).
+* ⬆️ Upgrade MkDocs and MkDocs Material. PR [#9729](https://github.com/tiangolo/fastapi/pull/9729) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Build and deploy docs only on docs changes. PR [#9728](https://github.com/tiangolo/fastapi/pull/9728) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.98.0
+
+### Features
+
+* ✨ Allow disabling `redirect_slashes` at the FastAPI app level. PR [#3432](https://github.com/tiangolo/fastapi/pull/3432) by [@cyberlis](https://github.com/cyberlis).
+
+### Docs
+
+* 📝 Update docs on Pydantic using ujson internally. PR [#5804](https://github.com/tiangolo/fastapi/pull/5804) by [@mvasilkov](https://github.com/mvasilkov).
+* ✏ Rewording in `docs/en/docs/tutorial/debugging.md`. PR [#9581](https://github.com/tiangolo/fastapi/pull/9581) by [@ivan-abc](https://github.com/ivan-abc).
+* 📝 Add german blog post (Domain-driven Design mit Python und FastAPI). PR [#9261](https://github.com/tiangolo/fastapi/pull/9261) by [@msander](https://github.com/msander).
+* ✏️ Tweak wording in `docs/en/docs/tutorial/security/index.md`. PR [#9561](https://github.com/tiangolo/fastapi/pull/9561) by [@jyothish-mohan](https://github.com/jyothish-mohan).
+* 📝 Update `Annotated` notes in `docs/en/docs/tutorial/schema-extra-example.md`. PR [#9620](https://github.com/tiangolo/fastapi/pull/9620) by [@Alexandrhub](https://github.com/Alexandrhub).
+* ✏️ Fix typo `Annotation` -> `Annotated` in `docs/en/docs/tutorial/query-params-str-validations.md`. PR [#9625](https://github.com/tiangolo/fastapi/pull/9625) by [@mccricardo](https://github.com/mccricardo).
+* 📝 Use in memory database for testing SQL in docs. PR [#1223](https://github.com/tiangolo/fastapi/pull/1223) by [@HarshaLaxman](https://github.com/HarshaLaxman).
+
+### Translations
+
+* 🌐 Add Russian translation for `docs/ru/docs/tutorial/metadata.md`. PR [#9681](https://github.com/tiangolo/fastapi/pull/9681) by [@TabarakoAkula](https://github.com/TabarakoAkula).
+* 🌐 Fix typo in Spanish translation for `docs/es/docs/tutorial/first-steps.md`. PR [#9571](https://github.com/tiangolo/fastapi/pull/9571) by [@lilidl-nft](https://github.com/lilidl-nft).
+* 🌐 Add Russian translation for `docs/tutorial/path-operation-configuration.md`. PR [#9696](https://github.com/tiangolo/fastapi/pull/9696) by [@TabarakoAkula](https://github.com/TabarakoAkula).
+* 🌐 Add Chinese translation for `docs/zh/docs/advanced/security/index.md`. PR [#9666](https://github.com/tiangolo/fastapi/pull/9666) by [@lordqyxz](https://github.com/lordqyxz).
+* 🌐 Add Chinese translations for `docs/zh/docs/advanced/settings.md`. PR [#9652](https://github.com/tiangolo/fastapi/pull/9652) by [@ChoyeonChern](https://github.com/ChoyeonChern).
+* 🌐 Add Chinese translations for `docs/zh/docs/advanced/websockets.md`. PR [#9651](https://github.com/tiangolo/fastapi/pull/9651) by [@ChoyeonChern](https://github.com/ChoyeonChern).
+* 🌐 Add Chinese translation for `docs/zh/docs/tutorial/testing.md`. PR [#9641](https://github.com/tiangolo/fastapi/pull/9641) by [@wdh99](https://github.com/wdh99).
+* 🌐 Add Russian translation for `docs/tutorial/extra-models.md`. PR [#9619](https://github.com/tiangolo/fastapi/pull/9619) by [@ivan-abc](https://github.com/ivan-abc).
+* 🌐 Add Russian translation for `docs/tutorial/cors.md`. PR [#9608](https://github.com/tiangolo/fastapi/pull/9608) by [@ivan-abc](https://github.com/ivan-abc).
+* 🌐 Add Polish translation for `docs/pl/docs/features.md`. PR [#5348](https://github.com/tiangolo/fastapi/pull/5348) by [@mbroton](https://github.com/mbroton).
+* 🌐 Add Russian translation for `docs/ru/docs/tutorial/body-nested-models.md`. PR [#9605](https://github.com/tiangolo/fastapi/pull/9605) by [@Alexandrhub](https://github.com/Alexandrhub).
+
+### Internal
+
+* ⬆ Bump ruff from 0.0.272 to 0.0.275. PR [#9721](https://github.com/tiangolo/fastapi/pull/9721) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Update uvicorn[standard] requirement from <0.21.0,>=0.12.0 to >=0.12.0,<0.23.0. PR [#9463](https://github.com/tiangolo/fastapi/pull/9463) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump mypy from 1.3.0 to 1.4.0. PR [#9719](https://github.com/tiangolo/fastapi/pull/9719) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Update pre-commit requirement from <3.0.0,>=2.17.0 to >=2.17.0,<4.0.0. PR [#9251](https://github.com/tiangolo/fastapi/pull/9251) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump pypa/gh-action-pypi-publish from 1.8.5 to 1.8.6. PR [#9482](https://github.com/tiangolo/fastapi/pull/9482) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ✏️ Fix tooltips for light/dark theme toggler in docs. PR [#9588](https://github.com/tiangolo/fastapi/pull/9588) by [@pankaj1707k](https://github.com/pankaj1707k).
+* 🔧 Set minimal hatchling version needed to build the package. PR [#9240](https://github.com/tiangolo/fastapi/pull/9240) by [@mgorny](https://github.com/mgorny).
+* 📝 Add repo link to PyPI. PR [#9559](https://github.com/tiangolo/fastapi/pull/9559) by [@JacobCoffee](https://github.com/JacobCoffee).
+* ✏️ Fix typos in data for tests. PR [#4958](https://github.com/tiangolo/fastapi/pull/4958) by [@ryanrussell](https://github.com/ryanrussell).
+* 🔧 Update sponsors, add Flint. PR [#9699](https://github.com/tiangolo/fastapi/pull/9699) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Lint in CI only once, only with one version of Python, run tests with all of them. PR [#9686](https://github.com/tiangolo/fastapi/pull/9686) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.97.0
+
+### Features
+
+* ✨ Add support for `dependencies` in WebSocket routes. PR [#4534](https://github.com/tiangolo/fastapi/pull/4534) by [@paulo-raca](https://github.com/paulo-raca).
+* ✨ Add exception handler for `WebSocketRequestValidationError` (which also allows to override it). PR [#6030](https://github.com/tiangolo/fastapi/pull/6030) by [@kristjanvalur](https://github.com/kristjanvalur).
+
+### Refactors
+
+* ⬆️ Upgrade and fully migrate to Ruff, remove isort, includes a couple of tweaks suggested by the new version of Ruff. PR [#9660](https://github.com/tiangolo/fastapi/pull/9660) by [@tiangolo](https://github.com/tiangolo).
+* ♻️ Update internal type annotations and upgrade mypy. PR [#9658](https://github.com/tiangolo/fastapi/pull/9658) by [@tiangolo](https://github.com/tiangolo).
+* ♻️ Simplify `AsyncExitStackMiddleware` as without Python 3.6 `AsyncExitStack` is always available. PR [#9657](https://github.com/tiangolo/fastapi/pull/9657) by [@tiangolo](https://github.com/tiangolo).
+
+### Upgrades
+
+* ⬆️ Upgrade Black. PR [#9661](https://github.com/tiangolo/fastapi/pull/9661) by [@tiangolo](https://github.com/tiangolo).
+
+### Internal
+
+* 💚 Update CI cache to fix installs when dependencies change. PR [#9659](https://github.com/tiangolo/fastapi/pull/9659) by [@tiangolo](https://github.com/tiangolo).
+* ⬇️ Separate requirements for development into their own requirements.txt files, they shouldn't be extras. PR [#9655](https://github.com/tiangolo/fastapi/pull/9655) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.96.1
+
+### Fixes
+
+* 🐛 Fix `HTTPException` header type annotations. PR [#9648](https://github.com/tiangolo/fastapi/pull/9648) by [@tiangolo](https://github.com/tiangolo).
+* 🐛 Fix OpenAPI model fields int validations, `gte` to `ge`. PR [#9635](https://github.com/tiangolo/fastapi/pull/9635) by [@tiangolo](https://github.com/tiangolo).
+
+### Upgrades
+
+* 📌 Update minimum version of Pydantic to >=1.7.4. This fixes an issue when trying to use an old version of Pydantic. PR [#9567](https://github.com/tiangolo/fastapi/pull/9567) by [@Kludex](https://github.com/Kludex).
+
+### Refactors
+
+* ♻ Remove `media_type` from `ORJSONResponse` as it's inherited from the parent class. PR [#5805](https://github.com/tiangolo/fastapi/pull/5805) by [@Kludex](https://github.com/Kludex).
+* ♻ Instantiate `HTTPException` only when needed, optimization refactor. PR [#5356](https://github.com/tiangolo/fastapi/pull/5356) by [@pawamoy](https://github.com/pawamoy).
+
+### Docs
+
+* 🔥 Remove link to Pydantic's benchmark, as it was removed there. PR [#5811](https://github.com/tiangolo/fastapi/pull/5811) by [@Kludex](https://github.com/Kludex).
+
+### Translations
+
+* 🌐 Fix spelling in Indonesian translation of `docs/id/docs/tutorial/index.md`. PR [#5635](https://github.com/tiangolo/fastapi/pull/5635) by [@purwowd](https://github.com/purwowd).
+* 🌐 Add Russian translation for `docs/ru/docs/tutorial/index.md`. PR [#5896](https://github.com/tiangolo/fastapi/pull/5896) by [@Wilidon](https://github.com/Wilidon).
+* 🌐 Add Chinese translations for `docs/zh/docs/advanced/response-change-status-code.md` and `docs/zh/docs/advanced/response-headers.md`. PR [#9544](https://github.com/tiangolo/fastapi/pull/9544) by [@ChoyeonChern](https://github.com/ChoyeonChern).
+* 🌐 Add Russian translation for `docs/ru/docs/tutorial/schema-extra-example.md`. PR [#9621](https://github.com/tiangolo/fastapi/pull/9621) by [@Alexandrhub](https://github.com/Alexandrhub).
+
+### Internal
+
+* 🔧 Add sponsor Platform.sh. PR [#9650](https://github.com/tiangolo/fastapi/pull/9650) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Add custom token to Smokeshow and Preview Docs for download-artifact, to prevent API rate limits. PR [#9646](https://github.com/tiangolo/fastapi/pull/9646) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Add custom tokens for GitHub Actions to avoid rate limits. PR [#9647](https://github.com/tiangolo/fastapi/pull/9647) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.96.0
+
+### Features
+
+* ⚡ Update `create_cloned_field` to use a global cache and improve startup performance. PR [#4645](https://github.com/tiangolo/fastapi/pull/4645) by [@madkinsz](https://github.com/madkinsz) and previous original PR by [@huonw](https://github.com/huonw).
+
+### Docs
+
+* 📝 Update Deta deployment tutorial for compatibility with Deta Space. PR [#6004](https://github.com/tiangolo/fastapi/pull/6004) by [@mikBighne98](https://github.com/mikBighne98).
+* ✏️ Fix typo in Deta deployment tutorial. PR [#9501](https://github.com/tiangolo/fastapi/pull/9501) by [@lemonyte](https://github.com/lemonyte).
+
+### Translations
+
+* 🌐 Add Russian translation for `docs/tutorial/body.md`. PR [#3885](https://github.com/tiangolo/fastapi/pull/3885) by [@solomein-sv](https://github.com/solomein-sv).
+* 🌐 Add Russian translation for `docs/ru/docs/tutorial/static-files.md`. PR [#9580](https://github.com/tiangolo/fastapi/pull/9580) by [@Alexandrhub](https://github.com/Alexandrhub).
+* 🌐 Add Russian translation for `docs/ru/docs/tutorial/query-params.md`. PR [#9584](https://github.com/tiangolo/fastapi/pull/9584) by [@Alexandrhub](https://github.com/Alexandrhub).
+* 🌐 Add Russian translation for `docs/ru/docs/tutorial/first-steps.md`. PR [#9471](https://github.com/tiangolo/fastapi/pull/9471) by [@AGolicyn](https://github.com/AGolicyn).
+* 🌐 Add Russian translation for `docs/ru/docs/tutorial/debugging.md`. PR [#9579](https://github.com/tiangolo/fastapi/pull/9579) by [@Alexandrhub](https://github.com/Alexandrhub).
+* 🌐 Add Russian translation for `docs/ru/docs/tutorial/path-params.md`. PR [#9519](https://github.com/tiangolo/fastapi/pull/9519) by [@AGolicyn](https://github.com/AGolicyn).
+* 🌐 Add Chinese translation for `docs/zh/docs/tutorial/static-files.md`. PR [#9436](https://github.com/tiangolo/fastapi/pull/9436) by [@wdh99](https://github.com/wdh99).
+* 🌐 Update Spanish translation including new illustrations in `docs/es/docs/async.md`. PR [#9483](https://github.com/tiangolo/fastapi/pull/9483) by [@andresbermeoq](https://github.com/andresbermeoq).
+* 🌐 Add Russian translation for `docs/ru/docs/tutorial/path-params-numeric-validations.md`. PR [#9563](https://github.com/tiangolo/fastapi/pull/9563) by [@ivan-abc](https://github.com/ivan-abc).
+* 🌐 Add Russian translation for `docs/ru/docs/deployment/concepts.md`. PR [#9577](https://github.com/tiangolo/fastapi/pull/9577) by [@Xewus](https://github.com/Xewus).
+* 🌐 Add Russian translation for `docs/ru/docs/tutorial/body-multiple-params.md`. PR [#9586](https://github.com/tiangolo/fastapi/pull/9586) by [@Alexandrhub](https://github.com/Alexandrhub).
+
+### Internal
+
+* 👥 Update FastAPI People. PR [#9602](https://github.com/tiangolo/fastapi/pull/9602) by [@github-actions[bot]](https://github.com/apps/github-actions).
+* 🔧 Update sponsors, remove InvestSuite. PR [#9612](https://github.com/tiangolo/fastapi/pull/9612) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.95.2
+
+* ⬆️ Upgrade Starlette version to `>=0.27.0` for a security release. PR [#9541](https://github.com/tiangolo/fastapi/pull/9541) by [@tiangolo](https://github.com/tiangolo). Details on [Starlette's security advisory](https://github.com/encode/starlette/security/advisories/GHSA-v5gw-mw7f-84px).
+
+### Translations
+
+* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/events.md`. PR [#9326](https://github.com/tiangolo/fastapi/pull/9326) by [@oandersonmagalhaes](https://github.com/oandersonmagalhaes).
+* 🌐 Add Russian translation for `docs/ru/docs/deployment/manually.md`. PR [#9417](https://github.com/tiangolo/fastapi/pull/9417) by [@Xewus](https://github.com/Xewus).
+* 🌐 Add setup for translations to Lao. PR [#9396](https://github.com/tiangolo/fastapi/pull/9396) by [@TheBrown](https://github.com/TheBrown).
+* 🌐 Add Russian translation for `docs/ru/docs/tutorial/testing.md`. PR [#9403](https://github.com/tiangolo/fastapi/pull/9403) by [@Xewus](https://github.com/Xewus).
+* 🌐 Add Russian translation for `docs/ru/docs/deployment/https.md`. PR [#9428](https://github.com/tiangolo/fastapi/pull/9428) by [@Xewus](https://github.com/Xewus).
* ✏ Fix command to install requirements in Windows. PR [#9445](https://github.com/tiangolo/fastapi/pull/9445) by [@MariiaRomanuik](https://github.com/MariiaRomanuik).
* 🌐 Add French translation for `docs/fr/docs/advanced/response-directly.md`. PR [#9415](https://github.com/tiangolo/fastapi/pull/9415) by [@axel584](https://github.com/axel584).
* 🌐 Initiate Czech translation setup. PR [#9288](https://github.com/tiangolo/fastapi/pull/9288) by [@3p1463k](https://github.com/3p1463k).
* ✏ Fix typo in Portuguese docs for `docs/pt/docs/index.md`. PR [#9337](https://github.com/tiangolo/fastapi/pull/9337) by [@lucasbalieiro](https://github.com/lucasbalieiro).
* 🌐 Add Russian translation for `docs/ru/docs/tutorial/response-status-code.md`. PR [#9370](https://github.com/tiangolo/fastapi/pull/9370) by [@nadia3373](https://github.com/nadia3373).
+
+### Internal
+
+* 🐛 Fix `flask.escape` warning for internal tests. PR [#9468](https://github.com/tiangolo/fastapi/pull/9468) by [@samuelcolvin](https://github.com/samuelcolvin).
+* ✅ Refactor 2 tests, for consistency and simplification. PR [#9504](https://github.com/tiangolo/fastapi/pull/9504) by [@tiangolo](https://github.com/tiangolo).
+* ✅ Refactor OpenAPI tests, prepare for Pydantic v2. PR [#9503](https://github.com/tiangolo/fastapi/pull/9503) by [@tiangolo](https://github.com/tiangolo).
* ⬆ Bump dawidd6/action-download-artifact from 2.26.0 to 2.27.0. PR [#9394](https://github.com/tiangolo/fastapi/pull/9394) by [@dependabot[bot]](https://github.com/apps/dependabot).
* 💚 Disable setup-python pip cache in CI. PR [#9438](https://github.com/tiangolo/fastapi/pull/9438) by [@tiangolo](https://github.com/tiangolo).
* ⬆ Bump pypa/gh-action-pypi-publish from 1.6.4 to 1.8.5. PR [#9346](https://github.com/tiangolo/fastapi/pull/9346) by [@dependabot[bot]](https://github.com/apps/dependabot).
@@ -2392,7 +4971,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Add support and tests for Pydantic dataclasses in `response_model`. PR [#454](https://github.com/tiangolo/fastapi/pull/454) by [@dconathan](https://github.com/dconathan).
* Fix typo in OAuth2 JWT tutorial. PR [#447](https://github.com/tiangolo/fastapi/pull/447) by [@pablogamboa](https://github.com/pablogamboa).
* Use the `media_type` parameter in `Body()` params to set the media type in OpenAPI for `requestBody`. PR [#439](https://github.com/tiangolo/fastapi/pull/439) by [@divums](https://github.com/divums).
-* Add article [Deploying a scikit-learn model with ONNX and FastAPI](https://medium.com/@nico.axtmann95/deploying-a-scikit-learn-model-with-onnx-und-fastapi-1af398268915) by [https://www.linkedin.com/in/nico-axtmann](Nico Axtmann). PR [#438](https://github.com/tiangolo/fastapi/pull/438) by [@naxty](https://github.com/naxty).
+* Add article [Deploying a scikit-learn model with ONNX and FastAPI](https://medium.com/@nico.axtmann95/deploying-a-scikit-learn-model-with-onnx-und-fastapi-1af398268915) by [Nico Axtmann](https://www.linkedin.com/in/nico-axtmann). PR [#438](https://github.com/tiangolo/fastapi/pull/438) by [@naxty](https://github.com/naxty).
* Allow setting custom `422` (validation error) response/schema in OpenAPI.
* And use media type from response class instead of fixed `application/json` (the default).
* PR [#437](https://github.com/tiangolo/fastapi/pull/437) by [@divums](https://github.com/divums).
@@ -2454,7 +5033,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
@@ -2558,7 +5137,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* New documentation about exceptions handlers:
* [Install custom exception handlers](https://fastapi.tiangolo.com/tutorial/handling-errors/#install-custom-exception-handlers).
* [Override the default exception handlers](https://fastapi.tiangolo.com/tutorial/handling-errors/#override-the-default-exception-handlers).
- * [Re-use **FastAPI's** exception handlers](https://fastapi.tiangolo.com/tutorial/handling-errors/#re-use-fastapis-exception-handlers).
+ * [Reuse **FastAPI's** exception handlers](https://fastapi.tiangolo.com/tutorial/handling-errors/#reuse-fastapis-exception-handlers).
* PR [#273](https://github.com/tiangolo/fastapi/pull/273).
* Fix support for *paths* in *path parameters* without needing explicit `Path(...)`.
@@ -2614,7 +5193,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 000000000..8c7cac43b
--- /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 178297192..34685fcc4 100644
--- a/docs/en/docs/tutorial/background-tasks.md
+++ b/docs/en/docs/tutorial/background-tasks.md
@@ -9,15 +9,13 @@ This includes, for example:
* Email notifications sent after performing an action:
* As connecting to an email server and sending an email tends to be "slow" (several seconds), you can return the response right away and send the email notification in the background.
* Processing data:
- * For example, let's say you receive a file that must go through a slow process, you can return a response of "Accepted" (HTTP 202) and process it in the background.
+ * For example, let's say you receive a file that must go through a slow process, you can return a response of "Accepted" (HTTP 202) and process the file in the background.
## Using `BackgroundTasks`
First, import `BackgroundTasks` and define a parameter in your *path operation function* with a type declaration of `BackgroundTasks`:
-```Python hl_lines="1 13"
-{!../../../docs_src/background_tasks/tutorial001.py!}
-```
+{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *}
**FastAPI** will create the object of type `BackgroundTasks` for you and pass it as that parameter.
@@ -33,17 +31,13 @@ In this case, the task function will write to a file (simulating sending an emai
And as the write operation doesn't use `async` and `await`, we define the function with normal `def`:
-```Python hl_lines="6-9"
-{!../../../docs_src/background_tasks/tutorial001.py!}
-```
+{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *}
## Add the background task
Inside of your *path operation function*, pass your task function to the *background tasks* object with the method `.add_task()`:
-```Python hl_lines="14"
-{!../../../docs_src/background_tasks/tutorial001.py!}
-```
+{* ../../docs_src/background_tasks/tutorial001.py hl[14] *}
`.add_task()` receives as arguments:
@@ -55,43 +49,11 @@ Inside of your *path operation function*, pass your task function to the *backgr
Using `BackgroundTasks` also works with the dependency injection system, you can declare a parameter of type `BackgroundTasks` at multiple levels: in a *path operation function*, in a dependency (dependable), in a sub-dependency, etc.
-**FastAPI** knows what to do in each case and how to re-use the same object, so that all the background tasks are merged together and are run in the background afterwards:
+**FastAPI** knows what to do in each case and how to reuse the same object, so that all the background tasks are merged together and are run in the background afterwards:
-=== "Python 3.10+"
- ```Python hl_lines="13 15 22 25"
- {!> ../../../docs_src/background_tasks/tutorial002_an_py310.py!}
- ```
+{* ../../docs_src/background_tasks/tutorial002_an_py310.py hl[13,15,22,25] *}
-=== "Python 3.9+"
-
- ```Python hl_lines="13 15 22 25"
- {!> ../../../docs_src/background_tasks/tutorial002_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="14 16 23 26"
- {!> ../../../docs_src/background_tasks/tutorial002_an.py!}
- ```
-
-=== "Python 3.10+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="11 13 20 23"
- {!> ../../../docs_src/background_tasks/tutorial002_py310.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="13 15 22 25"
- {!> ../../../docs_src/background_tasks/tutorial002.py!}
- ```
In this example, the messages will be written to the `log.txt` file *after* the response is sent.
@@ -117,8 +79,6 @@ If you need to perform heavy background computation and you don't necessarily ne
They tend to require more complex configurations, a message/job queue manager, like RabbitMQ or Redis, but they allow you to run background tasks in multiple processes, and especially, in multiple servers.
-To see an example, check the [Project Generators](../project-generation.md){.internal-link target=_blank}, they all include Celery already configured.
-
But if you need to access variables and objects from the same **FastAPI** app, or you need to perform small background tasks (like sending an email notification), you can simply just use `BackgroundTasks`.
## Recap
diff --git a/docs/en/docs/tutorial/bigger-applications.md b/docs/en/docs/tutorial/bigger-applications.md
index daa7353a2..f5f29a173 100644
--- a/docs/en/docs/tutorial/bigger-applications.md
+++ b/docs/en/docs/tutorial/bigger-applications.md
@@ -1,11 +1,14 @@
# Bigger Applications - Multiple Files
-If you are building an application or a web API, it's rarely the case that you can put everything on a single file.
+If you are building an application or a web API, it's rarely the case that you can put everything in a single file.
**FastAPI** provides a convenience tool to structure your application while keeping all the flexibility.
-!!! info
- If you come from Flask, this would be the equivalent of Flask's Blueprints.
+/// info
+
+If you come from Flask, this would be the equivalent of Flask's Blueprints.
+
+///
## An example file structure
@@ -26,16 +29,19 @@ Let's say you have a file structure like this:
│ └── admin.py
```
-!!! tip
- There are several `__init__.py` files: one in each directory or subdirectory.
+/// tip
+
+There are several `__init__.py` files: one in each directory or subdirectory.
- This is what allows importing code from one file into another.
+This is what allows importing code from one file into another.
- For example, in `app/main.py` you could have a line like:
+For example, in `app/main.py` you could have a line like:
+
+```
+from app.routers import items
+```
- ```
- from app.routers import items
- ```
+///
* The `app` directory contains everything. And it has an empty file `app/__init__.py`, so it is a "Python package" (a collection of "Python modules"): `app`.
* It contains an `app/main.py` file. As it is inside a Python package (a directory with a file `__init__.py`), it is a "module" of that package: `app.main`.
@@ -46,7 +52,7 @@ Let's say you have a file structure like this:
* There's also a subdirectory `app/internal/` with another file `__init__.py`, so it's another "Python subpackage": `app.internal`.
* And the file `app/internal/admin.py` is another submodule: `app.internal.admin`.
-get
operation
-!!! info "`@decorator` Info"
- That `@something` syntax in Python is called a "decorator".
+/// info | `@decorator` Info
- You put it on top of a function. Like a pretty decorative hat (I guess that's where the term came from).
+That `@something` syntax in Python is called a "decorator".
- A "decorator" takes the function below and does something with it.
+You put it on top of a function. Like a pretty decorative hat (I guess that's where the term came from).
- In our case, this decorator tells **FastAPI** that the function below corresponds to the **path** `/` with an **operation** `get`.
+A "decorator" takes the function below and does something with it.
- It is the "**path operation decorator**".
+In our case, this decorator tells **FastAPI** that the function below corresponds to the **path** `/` with an **operation** `get`.
+
+It is the "**path operation decorator**".
+
+///
You can also use the other operations:
@@ -274,14 +264,17 @@ And the more exotic ones:
* `@app.patch()`
* `@app.trace()`
-!!! tip
- You are free to use each operation (HTTP method) as you wish.
+/// tip
+
+You are free to use each operation (HTTP method) as you wish.
- **FastAPI** doesn't enforce any specific meaning.
+**FastAPI** doesn't enforce any specific meaning.
- The information here is presented as a guideline, not a requirement.
+The information here is presented as a guideline, not a requirement.
- For example, when using GraphQL you normally perform all the actions using only `POST` operations.
+For example, when using GraphQL you normally perform all the actions using only `POST` operations.
+
+///
### Step 4: define the **path operation function**
@@ -291,9 +284,7 @@ This is our "**path operation function**":
* **operation**: is `get`.
* **function**: is the function below the "decorator" (below `@app.get("/")`).
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[7] *}
This is a Python function.
@@ -305,18 +296,17 @@ In this case, it is an `async` function.
You could also define it as a normal function instead of `async def`:
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial003.py!}
-```
+{* ../../docs_src/first_steps/tutorial003.py hl[7] *}
-!!! note
- If you don't know the difference, check the [Async: *"In a hurry?"*](../async.md#in-a-hurry){.internal-link target=_blank}.
+/// note
+
+If you don't know the difference, check the [Async: *"In a hurry?"*](../async.md#in-a-hurry){.internal-link target=_blank}.
+
+///
### Step 5: return the content
-```Python hl_lines="8"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[8] *}
You can return a `dict`, `list`, singular values as `str`, `int`, etc.
@@ -328,6 +318,6 @@ There are many other objects and models that will be automatically converted to
* Import `FastAPI`.
* Create an `app` instance.
-* Write a **path operation decorator** (like `@app.get("/")`).
-* Write a **path operation function** (like `def root(): ...` above).
-* Run the development server (like `uvicorn main:app --reload`).
+* Write a **path operation decorator** using decorators like `@app.get("/")`.
+* Define a **path operation function**; for example, `def root(): ...`.
+* Run the development server using the command `fastapi dev`.
diff --git a/docs/en/docs/tutorial/handling-errors.md b/docs/en/docs/tutorial/handling-errors.md
index 8c30326ce..5b8e677e4 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.
@@ -25,9 +25,7 @@ To return HTTP responses with errors to the client you use `HTTPException`.
### Import `HTTPException`
-```Python hl_lines="1"
-{!../../../docs_src/handling_errors/tutorial001.py!}
-```
+{* ../../docs_src/handling_errors/tutorial001.py hl[1] *}
### Raise an `HTTPException` in your code
@@ -37,13 +35,11 @@ Because it's a Python exception, you don't `return` it, you `raise` it.
This also means that if you are inside a utility function that you are calling inside of your *path operation function*, and you raise the `HTTPException` from inside of that utility function, it won't run the rest of the code in the *path operation function*, it will terminate that request right away and send the HTTP error from the `HTTPException` to the client.
-The benefit of raising an exception over `return`ing a value will be more evident in the section about Dependencies and Security.
+The benefit of raising an exception over returning a value will be more evident in the section about Dependencies and Security.
In this example, when the client requests an item by an ID that doesn't exist, raise an exception with a status code of `404`:
-```Python hl_lines="11"
-{!../../../docs_src/handling_errors/tutorial001.py!}
-```
+{* ../../docs_src/handling_errors/tutorial001.py hl[11] *}
### The resulting response
@@ -63,12 +59,15 @@ But if the client requests `http://example.com/items/bar` (a non-existent `item_
}
```
-!!! tip
- When raising an `HTTPException`, you can pass any value that can be converted to JSON as the parameter `detail`, not only `str`.
+/// tip
+
+When raising an `HTTPException`, you can pass any value that can be converted to JSON as the parameter `detail`, not only `str`.
- You could pass a `dict`, a `list`, etc.
+You could pass a `dict`, a `list`, etc.
- They are handled automatically by **FastAPI** and converted to JSON.
+They are handled automatically by **FastAPI** and converted to JSON.
+
+///
## Add custom headers
@@ -78,9 +77,7 @@ You probably won't need to use it directly in your code.
But in case you needed it for an advanced scenario, you can add custom headers:
-```Python hl_lines="14"
-{!../../../docs_src/handling_errors/tutorial002.py!}
-```
+{* ../../docs_src/handling_errors/tutorial002.py hl[14] *}
## Install custom exception handlers
@@ -92,9 +89,7 @@ And you want to handle this exception globally with FastAPI.
You could add a custom exception handler with `@app.exception_handler()`:
-```Python hl_lines="5-7 13-18 24"
-{!../../../docs_src/handling_errors/tutorial003.py!}
-```
+{* ../../docs_src/handling_errors/tutorial003.py hl[5:7,13:18,24] *}
Here, if you request `/unicorns/yolo`, the *path operation* will `raise` a `UnicornException`.
@@ -106,10 +101,13 @@ So, you will receive a clean error, with an HTTP status code of `418` and a JSON
{"message": "Oops! yolo did something. There goes a rainbow..."}
```
-!!! note "Technical Details"
- You could also use `from starlette.requests import Request` and `from starlette.responses import JSONResponse`.
+/// note | Technical Details
+
+You could also use `from starlette.requests import Request` and `from starlette.responses import JSONResponse`.
- **FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. The same with `Request`.
+**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. The same with `Request`.
+
+///
## Override the default exception handlers
@@ -129,9 +127,7 @@ To override it, import the `RequestValidationError` and use it with `@app.except
The exception handler will receive a `Request` and the exception.
-```Python hl_lines="2 14-16"
-{!../../../docs_src/handling_errors/tutorial004.py!}
-```
+{* ../../docs_src/handling_errors/tutorial004.py hl[2,14:16] *}
Now, if you go to `/items/foo`, instead of getting the default JSON error with:
@@ -160,14 +156,17 @@ path -> item_id
#### `RequestValidationError` vs `ValidationError`
-!!! warning
- These are technical details that you might skip if it's not important for you now.
+/// warning
-`RequestValidationError` is a sub-class of Pydantic's `ValidationError`.
+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`.
**FastAPI** uses it so that, if you use a Pydantic model in `response_model`, and your data has an error, you will see the error in your log.
-But the client/user will not see it. Instead, the client will receive an "Internal Server Error" with a HTTP status code `500`.
+But the client/user will not see it. Instead, the client will receive an "Internal Server Error" with an HTTP status code `500`.
It should be this way because if you have a Pydantic `ValidationError` in your *response* or anywhere in your code (not in the client's *request*), it's actually a bug in your code.
@@ -179,14 +178,15 @@ The same way, you can override the `HTTPException` handler.
For example, you could want to return a plain text response instead of JSON for these errors:
-```Python hl_lines="3-4 9-11 22"
-{!../../../docs_src/handling_errors/tutorial004.py!}
-```
+{* ../../docs_src/handling_errors/tutorial004.py hl[3:4,9:11,22] *}
+
+/// note | Technical Details
-!!! note "Technical Details"
- You could also use `from starlette.responses import PlainTextResponse`.
+You could also use `from starlette.responses import PlainTextResponse`.
- **FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette.
+**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette.
+
+///
### Use the `RequestValidationError` body
@@ -194,9 +194,7 @@ The `RequestValidationError` contains the `body` it received with invalid data.
You could use it while developing your app to log the body and debug it, return it to the user, etc.
-```Python hl_lines="14"
-{!../../../docs_src/handling_errors/tutorial005.py!}
-```
+{* ../../docs_src/handling_errors/tutorial005.py hl[14] *}
Now try sending an invalid item like:
@@ -234,9 +232,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.
@@ -250,12 +246,10 @@ In this example, to be able to have both `HTTPException`s in the same code, Star
from starlette.exceptions import HTTPException as StarletteHTTPException
```
-### Re-use **FastAPI**'s exception handlers
+### Reuse **FastAPI**'s exception handlers
-If you want to use the exception along with the same default exception handlers from **FastAPI**, You can import and re-use the default exception handlers from `fastapi.exception_handlers`:
+If you want to use the exception along with the same default exception handlers from **FastAPI**, you can import and reuse the default exception handlers from `fastapi.exception_handlers`:
-```Python hl_lines="2-5 15 21"
-{!../../../docs_src/handling_errors/tutorial006.py!}
-```
+{* ../../docs_src/handling_errors/tutorial006.py hl[2:5,15,21] *}
-In this example you are just `print`ing the error with a very expressive message, but you get the idea. You can use the exception and then just re-use the default exception handlers.
+In this example you are just printing the error with a very expressive message, but you get the idea. You can use the exception and then just reuse the default exception handlers.
diff --git a/docs/en/docs/tutorial/header-param-models.md b/docs/en/docs/tutorial/header-param-models.md
new file mode 100644
index 000000000..4cdf09705
--- /dev/null
+++ b/docs/en/docs/tutorial/header-param-models.md
@@ -0,0 +1,72 @@
+# Header Parameter Models
+
+If you have a group of related **header parameters**, you can create a **Pydantic model** to declare them.
+
+This would allow you to **re-use the model** in **multiple places** and also to declare validations and metadata for all the parameters at once. 😎
+
+/// note
+
+This is supported since FastAPI version `0.115.0`. 🤓
+
+///
+
+## Header Parameters with a Pydantic Model
+
+Declare the **header parameters** that you need in a **Pydantic model**, and then declare the parameter as `Header`:
+
+{* ../../docs_src/header_param_models/tutorial001_an_py310.py hl[9:14,18] *}
+
+**FastAPI** will **extract** the data for **each field** from the **headers** in the request and give you the Pydantic model you defined.
+
+## Check the Docs
+
+You can see the required headers in the docs UI at `/docs`:
+
+contact
fieldsParameter | Type | Description |
---|---|---|
name | str | The identifying name of the contact person/organization. |
url | str | The URL pointing to the contact information. MUST be in the format of a URL. |
email | str | The email address of the contact person/organization. MUST be in the format of an email address. |
license_info
fieldsParameter | Type | Description |
---|---|---|
name | str | REQUIRED (if a license_info is set). The license name used for the API. |
url | str | A URL to the license used for the API. MUST be in the format of a URL. |
license_info
fieldsParameter | Type | Description |
---|---|---|
name | str | REQUIRED (if a license_info is set). The license name used for the API. |
identifier | str | An SPDX license expression for the API. The identifier field is mutually exclusive of the url field. Available since OpenAPI 3.1.0, FastAPI 0.99.0. |
url | str | A URL to the license used for the API. MUST be in the format of a URL. |
kwargs
. Even if they don't have a default value.
-```Python hl_lines="7"
-{!../../../docs_src/path_params_numeric_validations/tutorial003.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *}
### Better with `Annotated`
-Have in mind that if you use `Annotated`, as you are not using function parameter default values, you won't have this problem, and you probably won't need to use `*`.
-
-=== "Python 3.9+"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!}
- ```
+Keep in mind that if you use `Annotated`, as you are not using function parameter default values, you won't have this problem, and you probably won't need to use `*`.
-=== "Python 3.6+"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!}
- ```
+{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py hl[10] *}
## Number validations: greater than or equal
@@ -186,26 +107,7 @@ With `Query` and `Path` (and others you'll see later) you can declare number con
Here, with `ge=1`, `item_id` will need to be an integer number "`g`reater than or `e`qual" to `1`.
-=== "Python 3.9+"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="8"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!}
- ```
+{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py hl[10] *}
## Number validations: greater than and less than or equal
@@ -214,26 +116,7 @@ The same applies for:
* `gt`: `g`reater `t`han
* `le`: `l`ess than or `e`qual
-=== "Python 3.9+"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!}
- ```
+{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py hl[10] *}
## Number validations: floats, greater than and less than
@@ -245,26 +128,7 @@ So, `0.5` would be a valid value. But `0.0` or `0` would not.
And the same for lt
.
-=== "Python 3.9+"
-
- ```Python hl_lines="13"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="12"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="11"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!}
- ```
+{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py hl[13] *}
## Recap
@@ -277,18 +141,24 @@ And you can also declare numeric validations:
* `lt`: `l`ess `t`han
* `le`: `l`ess than or `e`qual
-!!! info
- `Query`, `Path`, and other classes you will see later are subclasses of a common `Param` class.
+/// info
+
+`Query`, `Path`, and other classes you will see later are subclasses of a common `Param` class.
+
+All of them share the same parameters for additional validation and metadata you have seen.
+
+///
+
+/// note | Technical Details
- All of them share the same parameters for additional validation and metadata you have seen.
+When you import `Query`, `Path` and others from `fastapi`, they are actually functions.
-!!! note "Technical Details"
- When you import `Query`, `Path` and others from `fastapi`, they are actually functions.
+That when called, return instances of classes of the same name.
- That when called, return instances of classes of the same name.
+So, you import `Query`, which is a function. And when you call it, it returns an instance of a class also named `Query`.
- So, you import `Query`, which is a function. And when you call it, it returns an instance of a class also named `Query`.
+These functions are there (instead of just using the classes directly) so that your editor doesn't mark errors about their types.
- These functions are there (instead of just using the classes directly) so that your editor doesn't mark errors about their types.
+That way you can use your normal editor and coding tools without having to add custom configurations to disregard those errors.
- That way you can use your normal editor and coding tools without having to add custom configurations to disregard those errors.
+///
diff --git a/docs/en/docs/tutorial/path-params.md b/docs/en/docs/tutorial/path-params.md
index a0d70692e..7e83d3ae5 100644
--- a/docs/en/docs/tutorial/path-params.md
+++ b/docs/en/docs/tutorial/path-params.md
@@ -2,9 +2,7 @@
You can declare path "parameters" or "variables" with the same syntax used by Python format strings:
-```Python hl_lines="6-7"
-{!../../../docs_src/path_params/tutorial001.py!}
-```
+{* ../../docs_src/path_params/tutorial001.py hl[6:7] *}
The value of the path parameter `item_id` will be passed to your function as the argument `item_id`.
@@ -18,14 +16,15 @@ So, if you run this example and go to conversion
@@ -35,10 +34,13 @@ If you run this example and open your browser at "parsing".
+Notice that the value your function received (and returned) is `3`, as a Python `int`, not a string `"3"`.
+
+So, with that type declaration, **FastAPI** gives you automatic request "parsing".
+
+///
## Data validation
@@ -46,16 +48,18 @@ But if you go to the browser at http://127.0.0.1:8000/items/4.2
-!!! check
- So, with the same Python type declaration, **FastAPI** gives you data validation.
+/// check
+
+So, with the same Python type declaration, **FastAPI** gives you data validation.
- Notice that the error also clearly states exactly the point where the validation didn't pass.
+Notice that the error also clearly states exactly the point where the validation didn't pass.
- This is incredibly helpful while developing and debugging code that interacts with your API.
+This is incredibly helpful while developing and debugging code that interacts with your API.
+
+///
## Documentation
@@ -76,14 +83,17 @@ And when you open your browser at
-!!! check
- Again, just with that same Python type declaration, **FastAPI** gives you automatic, interactive documentation (integrating Swagger UI).
+/// check
+
+Again, just with that same Python type declaration, **FastAPI** gives you automatic, interactive documentation (integrating Swagger UI).
+
+Notice that the path parameter is declared to be an integer.
- Notice that the path parameter is declared to be an integer.
+///
## Standards-based benefits, alternative documentation
-And because the generated schema is from the OpenAPI standard, there are many compatible tools.
+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 +103,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.
@@ -109,17 +119,13 @@ And then you can also have a path `/users/{user_id}` to get data about a specifi
Because *path operations* are evaluated in order, you need to make sure that the path for `/users/me` is declared before the one for `/users/{user_id}`:
-```Python hl_lines="6 11"
-{!../../../docs_src/path_params/tutorial003.py!}
-```
+{* ../../docs_src/path_params/tutorial003.py hl[6,11] *}
Otherwise, the path for `/users/{user_id}` would match also for `/users/me`, "thinking" that it's receiving a parameter `user_id` with a value of `"me"`.
Similarly, you cannot redefine a path operation:
-```Python hl_lines="6 11"
-{!../../../docs_src/path_params/tutorial003b.py!}
-```
+{* ../../docs_src/path_params/tutorial003b.py hl[6,11] *}
The first one will always be used since the path matches first.
@@ -135,23 +141,25 @@ By inheriting from `str` the API docs will be able to know that the values must
Then create class attributes with fixed values, which will be the available valid values:
-```Python hl_lines="1 6-9"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial005.py hl[1,6:9] *}
-!!! info
- Enumerations (or enums) are available in Python since version 3.4.
+/// info
-!!! tip
- If you are wondering, "AlexNet", "ResNet", and "LeNet" are just names of Machine Learning models.
+Enumerations (or enums) are available in Python since version 3.4.
+
+///
+
+/// tip
+
+If you are wondering, "AlexNet", "ResNet", and "LeNet" are just names of Machine Learning models.
+
+///
### Declare a *path parameter*
Then create a *path parameter* with a type annotation using the enum class you created (`ModelName`):
-```Python hl_lines="16"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial005.py hl[16] *}
### Check the docs
@@ -167,20 +175,19 @@ The value of the *path parameter* will be an *enumeration member*.
You can compare it with the *enumeration member* in your created enum `ModelName`:
-```Python hl_lines="17"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial005.py hl[17] *}
#### Get the *enumeration value*
You can get the actual value (a `str` in this case) using `model_name.value`, or in general, `your_enum_member.value`:
-```Python hl_lines="20"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial005.py hl[20] *}
-!!! tip
- You could also access the value `"lenet"` with `ModelName.lenet.value`.
+/// tip
+
+You could also access the value `"lenet"` with `ModelName.lenet.value`.
+
+///
#### Return *enumeration members*
@@ -188,9 +195,7 @@ You can return *enum members* from your *path operation*, even nested in a JSON
They will be converted to their corresponding values (strings in this case) before returning them to the client:
-```Python hl_lines="18 21 23"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial005.py hl[18,21,23] *}
In your client you will get a JSON response like:
@@ -229,14 +234,15 @@ In this case, the name of the parameter is `file_path`, and the last part, `:pat
So, you can use it with:
-```Python hl_lines="6"
-{!../../../docs_src/path_params/tutorial004.py!}
-```
+{* ../../docs_src/path_params/tutorial004.py hl[6] *}
+
+/// tip
+
+You could need the parameter to contain `/home/johndoe/myfile.txt`, with a leading slash (`/`).
-!!! tip
- You could need the parameter to contain `/home/johndoe/myfile.txt`, with a leading slash (`/`).
+In that case, the URL would be: `/files//home/johndoe/myfile.txt`, with a double slash (`//`) between `files` and `home`.
- In that case, the URL would be: `/files//home/johndoe/myfile.txt`, with a double slash (`//`) between `files` and `home`.
+///
## Recap
diff --git a/docs/en/docs/tutorial/query-param-models.md b/docs/en/docs/tutorial/query-param-models.md
new file mode 100644
index 000000000..84d82931a
--- /dev/null
+++ b/docs/en/docs/tutorial/query-param-models.md
@@ -0,0 +1,68 @@
+# Query Parameter Models
+
+If you have a group of **query parameters** that are related, you can create a **Pydantic model** to declare them.
+
+This would allow you to **re-use the model** in **multiple places** and also to declare validations and metadata for all the parameters at once. 😎
+
+/// note
+
+This is supported since FastAPI version `0.115.0`. 🤓
+
+///
+
+## Query Parameters with a Pydantic Model
+
+Declare the **query parameters** that you need in a **Pydantic model**, and then declare the parameter as `Query`:
+
+{* ../../docs_src/query_param_models/tutorial001_an_py310.py hl[9:13,17] *}
+
+**FastAPI** will **extract** the data for **each field** from the **query parameters** in the request and give you the Pydantic model you defined.
+
+## Check the Docs
+
+You can see the query parameters in the docs UI at `/docs`:
+
+POST
.
+///
-!!! warning
- You can declare multiple `File` and `Form` parameters in a *path operation*, but you can't also declare `Body` fields that you expect to receive as JSON, as the request will have the body encoded using `multipart/form-data` instead of `application/json`.
-
- This is not a limitation of **FastAPI**, it's part of the HTTP protocol.
+## What is "Form Data"
-## Optional File Upload
+The way HTML forms (``) sends the data to the server normally uses a "special" encoding for that data, it's different from JSON.
-You can make a file optional by using standard type annotations and setting a default value of `None`:
+**FastAPI** will make sure to read that data from the right place instead of JSON.
-=== "Python 3.10+"
+/// note | Technical Details
- ```Python hl_lines="9 17"
- {!> ../../../docs_src/request_files/tutorial001_02_an_py310.py!}
- ```
+Data from forms is normally encoded using the "media type" `application/x-www-form-urlencoded` when it doesn't include files.
-=== "Python 3.9+"
+But when the form includes files, it is encoded as `multipart/form-data`. If you use `File`, **FastAPI** will know it has to get the files from the correct part of the body.
- ```Python hl_lines="9 17"
- {!> ../../../docs_src/request_files/tutorial001_02_an_py39.py!}
- ```
+If you want to read more about these encodings and form fields, head to the MDN web docs for POST
.
-=== "Python 3.6+"
+///
- ```Python hl_lines="10 18"
- {!> ../../../docs_src/request_files/tutorial001_02_an.py!}
- ```
+/// warning
-=== "Python 3.10+ non-Annotated"
+You can declare multiple `File` and `Form` parameters in a *path operation*, but you can't also declare `Body` fields that you expect to receive as JSON, as the request will have the body encoded using `multipart/form-data` instead of `application/json`.
- !!! tip
- Prefer to use the `Annotated` version if possible.
+This is not a limitation of **FastAPI**, it's part of the HTTP protocol.
- ```Python hl_lines="7 15"
- {!> ../../../docs_src/request_files/tutorial001_02_py310.py!}
- ```
+///
-=== "Python 3.6+ non-Annotated"
+## Optional File Upload
- !!! tip
- Prefer to use the `Annotated` version if possible.
+You can make a file optional by using standard type annotations and setting a default value of `None`:
- ```Python hl_lines="9 17"
- {!> ../../../docs_src/request_files/tutorial001_02.py!}
- ```
+{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *}
## `UploadFile` with Additional Metadata
You can also use `File()` with `UploadFile`, for example, to set additional metadata:
-=== "Python 3.9+"
-
- ```Python hl_lines="9 15"
- {!> ../../../docs_src/request_files/tutorial001_03_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="8 14"
- {!> ../../../docs_src/request_files/tutorial001_03_an.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="7 13"
- {!> ../../../docs_src/request_files/tutorial001_03.py!}
- ```
+{* ../../docs_src/request_files/tutorial001_03_an_py39.py hl[9,15] *}
## Multiple File Uploads
@@ -238,76 +153,23 @@ They would be associated to the same "form field" sent using "form data".
To use that, declare a list of `bytes` or `UploadFile`:
-=== "Python 3.9+"
-
- ```Python hl_lines="10 15"
- {!> ../../../docs_src/request_files/tutorial002_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="11 16"
- {!> ../../../docs_src/request_files/tutorial002_an.py!}
- ```
-
-=== "Python 3.9+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
+{* ../../docs_src/request_files/tutorial002_an_py39.py hl[10,15] *}
- ```Python hl_lines="8 13"
- {!> ../../../docs_src/request_files/tutorial002_py39.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
+You will receive, as declared, a `list` of `bytes` or `UploadFile`s.
- ```Python hl_lines="10 15"
- {!> ../../../docs_src/request_files/tutorial002.py!}
- ```
+/// note | Technical Details
-You will receive, as declared, a `list` of `bytes` or `UploadFile`s.
+You could also use `from starlette.responses import HTMLResponse`.
-!!! note "Technical Details"
- You could also use `from starlette.responses import HTMLResponse`.
+**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette.
- **FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette.
+///
### Multiple File Uploads with Additional Metadata
And the same way as before, you can use `File()` to set additional parameters, even for `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+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="9 16"
- {!> ../../../docs_src/request_files/tutorial003_py39.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="11 18"
- {!> ../../../docs_src/request_files/tutorial003.py!}
- ```
+{* ../../docs_src/request_files/tutorial003_an_py39.py hl[11,18:20] *}
## Recap
diff --git a/docs/en/docs/tutorial/request-form-models.md b/docs/en/docs/tutorial/request-form-models.md
new file mode 100644
index 000000000..79046a3f6
--- /dev/null
+++ b/docs/en/docs/tutorial/request-form-models.md
@@ -0,0 +1,78 @@
+# Form Models
+
+You can use **Pydantic models** to declare **form fields** in FastAPI.
+
+/// info
+
+To use forms, first install `python-multipart`.
+
+Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install it, for example:
+
+```console
+$ pip install python-multipart
+```
+
+///
+
+/// note
+
+This is supported since FastAPI version `0.113.0`. 🤓
+
+///
+
+## Pydantic Models for Forms
+
+You just need to declare a **Pydantic model** with the fields you want to receive as **form fields**, and then declare the parameter as `Form`:
+
+{* ../../docs_src/request_form_models/tutorial001_an_py39.py hl[9:11,15] *}
+
+**FastAPI** will **extract** the data for **each field** from the **form data** in the request and give you the Pydantic model you defined.
+
+## Check the Docs
+
+You can verify it in the docs UI at `/docs`:
+
+POST
.
+
+///
- But when the form includes files, it is encoded as `multipart/form-data`. You'll read about handling files in the next chapter.
+/// warning
- If you want to read more about these encodings and form fields, head to the MDN web docs for POST
.
+You can declare multiple `Form` parameters in a *path operation*, but you can't also declare `Body` fields that you expect to receive as JSON, as the request will have the body encoded using `application/x-www-form-urlencoded` instead of `application/json`.
-!!! warning
- You can declare multiple `Form` parameters in a *path operation*, but you can't also declare `Body` fields that you expect to receive as JSON, as the request will have the body encoded using `application/x-www-form-urlencoded` instead of `application/json`.
+This is not a limitation of **FastAPI**, it's part of the HTTP protocol.
- This is not a limitation of **FastAPI**, it's part of the HTTP protocol.
+///
## Recap
diff --git a/docs/en/docs/tutorial/response-model.md b/docs/en/docs/tutorial/response-model.md
index 2181cfb5a..e7837086f 100644
--- a/docs/en/docs/tutorial/response-model.md
+++ b/docs/en/docs/tutorial/response-model.md
@@ -4,23 +4,7 @@ You can declare the type used for the response by annotating the *path operation
You can use **type annotations** the same way you would for input data in function **parameters**, you can use Pydantic models, lists, dictionaries, scalar values like integers, booleans, etc.
-=== "Python 3.10+"
-
- ```Python hl_lines="16 21"
- {!> ../../../docs_src/response_model/tutorial001_01_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="18 23"
- {!> ../../../docs_src/response_model/tutorial001_01_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="18 23"
- {!> ../../../docs_src/response_model/tutorial001_01.py!}
- ```
+{* ../../docs_src/response_model/tutorial001_01_py310.py hl[16,21] *}
FastAPI will use this return type to:
@@ -53,35 +37,25 @@ You can use the `response_model` parameter in any of the *path operations*:
* `@app.delete()`
* etc.
-=== "Python 3.10+"
-
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001_py39.py!}
- ```
+{* ../../docs_src/response_model/tutorial001_py310.py hl[17,22,24:27] *}
-=== "Python 3.6+"
+/// note
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001.py!}
- ```
+Notice that `response_model` is a parameter of the "decorator" method (`get`, `post`, etc). Not of your *path operation function*, like all the parameters and body.
-!!! note
- Notice that `response_model` is a parameter of the "decorator" method (`get`, `post`, etc). Not of your *path operation function*, like all the parameters and body.
+///
`response_model` receives the same type you would declare for a Pydantic model field, so, it can be a Pydantic model, but it can also be, e.g. a `list` of Pydantic models, like `List[Item]`.
FastAPI will use this `response_model` to do all the data documentation, validation, etc. and also to **convert and filter the output data** to its type declaration.
-!!! tip
- If you have strict type checks in your editor, mypy, etc, you can declare the function return type as `Any`.
+/// tip
- That way you tell the editor that you are intentionally returning anything. But FastAPI will still do the data documentation, validation, filtering, etc. with the `response_model`.
+If you have strict type checks in your editor, mypy, etc, you can declare the function return type as `Any`.
+
+That way you tell the editor that you are intentionally returning anything. But FastAPI will still do the data documentation, validation, filtering, etc. with the `response_model`.
+
+///
### `response_model` Priority
@@ -95,37 +69,29 @@ You can also use `response_model=None` to disable creating a response model for
Here we are declaring a `UserIn` model, it will contain a plaintext password:
-=== "Python 3.10+"
+{* ../../docs_src/response_model/tutorial002_py310.py hl[7,9] *}
- ```Python hl_lines="7 9"
- {!> ../../../docs_src/response_model/tutorial002_py310.py!}
- ```
+/// info
-=== "Python 3.6+"
+To use `EmailStr`, first install `email-validator`.
- ```Python hl_lines="9 11"
- {!> ../../../docs_src/response_model/tutorial002.py!}
- ```
+Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install it, for example:
-!!! info
- To use `EmailStr`, first install `email_validator`.
-
- E.g. `pip install email-validator`
- or `pip install pydantic[email]`.
+```console
+$ pip install email-validator
+```
-And we are using this model to declare our input and the same model to declare our output:
+or with:
-=== "Python 3.10+"
+```console
+$ pip install "pydantic[email]"
+```
- ```Python hl_lines="16"
- {!> ../../../docs_src/response_model/tutorial002_py310.py!}
- ```
+///
-=== "Python 3.6+"
+And we are using this model to declare our input and the same model to declare our output:
- ```Python hl_lines="18"
- {!> ../../../docs_src/response_model/tutorial002.py!}
- ```
+{* ../../docs_src/response_model/tutorial002_py310.py hl[16] *}
Now, whenever a browser is creating a user with a password, the API will return the same password in the response.
@@ -133,52 +99,25 @@ In this case, it might not be a problem, because it's the same user sending the
But if we use the same model for another *path operation*, we could be sending our user's passwords to every client.
-!!! danger
- Never store the plain password of a user or send it in a response like this, unless you know all the caveats and you know what you are doing.
+/// danger
-## Add an output model
+Never store the plain password of a user or send it in a response like this, unless you know all the caveats and you know what you are doing.
-We can instead create an input model with the plaintext password and an output model without it:
-
-=== "Python 3.10+"
+///
- ```Python hl_lines="9 11 16"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
+## Add an output model
-=== "Python 3.6+"
+We can instead create an input model with the plaintext password and an output model without it:
- ```Python hl_lines="9 11 16"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+{* ../../docs_src/response_model/tutorial003_py310.py hl[9,11,16] *}
Here, even though our *path operation function* is returning the same input user that contains the password:
-=== "Python 3.10+"
-
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+{* ../../docs_src/response_model/tutorial003_py310.py hl[24] *}
...we declared the `response_model` to be our model `UserOut`, that doesn't include the password:
-=== "Python 3.10+"
-
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+{* ../../docs_src/response_model/tutorial003_py310.py hl[22] *}
So, **FastAPI** will take care of filtering out all the data that is not declared in the output model (using Pydantic).
@@ -192,9 +131,9 @@ That's why in this example we have to declare it in the `response_model` paramet
## Return Type and Data Filtering
-Let's continue from the previous example. We wanted to **annotate the function with one type** but return something that includes **more data**.
+Let's continue from the previous example. We wanted to **annotate the function with one type**, but we wanted to be able to return from the function something that actually includes **more data**.
-We want FastAPI to keep **filtering** the data using the response model.
+We want FastAPI to keep **filtering** the data using the response model. So that even though the function returns more data, the response will only include the fields declared in the response model.
In the previous example, because the classes were different, we had to use the `response_model` parameter. But that also means that we don't get the support from the editor and tools checking the function return type.
@@ -202,17 +141,7 @@ But in most of the cases where we need to do something like this, we want the mo
And in those cases, we can use classes and inheritance to take advantage of function **type annotations** to get better support in the editor and tools, and still get the FastAPI **data filtering**.
-=== "Python 3.10+"
-
- ```Python hl_lines="7-10 13-14 18"
- {!> ../../../docs_src/response_model/tutorial003_01_py310.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="9-13 15-16 20"
- {!> ../../../docs_src/response_model/tutorial003_01.py!}
- ```
+{* ../../docs_src/response_model/tutorial003_01_py310.py hl[7:10,13:14,18] *}
With this, we get tooling support, from editors and mypy as this code is correct in terms of types, but we also get the data filtering from FastAPI.
@@ -254,11 +183,9 @@ There might be cases where you return something that is not a valid Pydantic fie
The most common case would be [returning a Response directly as explained later in the advanced docs](../advanced/response-directly.md){.internal-link target=_blank}.
-```Python hl_lines="8 10-11"
-{!> ../../../docs_src/response_model/tutorial003_02.py!}
-```
+{* ../../docs_src/response_model/tutorial003_02.py hl[8,10:11] *}
-This simple case is handled automatically by FastAPI because the return type annotation is the class (or a subclass) of `Response`.
+This simple case is handled automatically by FastAPI because the return type annotation is the class (or a subclass of) `Response`.
And tools will also be happy because both `RedirectResponse` and `JSONResponse` are subclasses of `Response`, so the type annotation is correct.
@@ -266,9 +193,7 @@ And tools will also be happy because both `RedirectResponse` and `JSONResponse`
You can also use a subclass of `Response` in the type annotation:
-```Python hl_lines="8-9"
-{!> ../../../docs_src/response_model/tutorial003_03.py!}
-```
+{* ../../docs_src/response_model/tutorial003_03.py hl[8:9] *}
This will also work because `RedirectResponse` is a subclass of `Response`, and FastAPI will automatically handle this simple case.
@@ -278,17 +203,7 @@ But when you return some other arbitrary object that is not a valid Pydantic typ
The same would happen if you had something like a union between different types where one or more of them are not valid Pydantic types, for example this would fail 💥:
-=== "Python 3.10+"
-
- ```Python hl_lines="8"
- {!> ../../../docs_src/response_model/tutorial003_04_py310.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/response_model/tutorial003_04.py!}
- ```
+{* ../../docs_src/response_model/tutorial003_04_py310.py hl[8] *}
...this fails because the type annotation is not a Pydantic type and is not just a single `Response` class or subclass, it's a union (any of the two) between a `Response` and a `dict`.
@@ -300,17 +215,7 @@ But you might want to still keep the return type annotation in the function to g
In this case, you can disable the response model generation by setting `response_model=None`:
-=== "Python 3.10+"
-
- ```Python hl_lines="7"
- {!> ../../../docs_src/response_model/tutorial003_05_py310.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/response_model/tutorial003_05.py!}
- ```
+{* ../../docs_src/response_model/tutorial003_05_py310.py hl[7] *}
This will make FastAPI skip the response model generation and that way you can have any return type annotations you need without it affecting your FastAPI application. 🤓
@@ -318,27 +223,11 @@ This will make FastAPI skip the response model generation and that way you can h
Your response model could have default values, like:
-=== "Python 3.10+"
-
- ```Python hl_lines="9 11-12"
- {!> ../../../docs_src/response_model/tutorial004_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="11 13-14"
- {!> ../../../docs_src/response_model/tutorial004_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="11 13-14"
- {!> ../../../docs_src/response_model/tutorial004.py!}
- ```
+{* ../../docs_src/response_model/tutorial004_py310.py hl[9,11:12] *}
* `description: Union[str, None] = None` (or `str | None = None` in Python 3.10) has a default of `None`.
* `tax: float = 10.5` has a default of `10.5`.
-* `tags: List[str] = []` as a default of an empty list: `[]`.
+* `tags: List[str] = []` has a default of an empty list: `[]`.
but you might want to omit them from the result if they were not actually stored.
@@ -348,23 +237,7 @@ For example, if you have models with many optional attributes in a NoSQL databas
You can set the *path operation decorator* parameter `response_model_exclude_unset=True`:
-=== "Python 3.10+"
-
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial004_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial004_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial004.py!}
- ```
+{* ../../docs_src/response_model/tutorial004_py310.py hl[22] *}
and those default values won't be included in the response, only the values actually set.
@@ -377,16 +250,30 @@ So, if you send a request to that *path operation* for the item with ID `foo`, t
}
```
-!!! info
- FastAPI uses Pydantic model's `.dict()` with its `exclude_unset` parameter to achieve this.
+/// info
+
+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
-!!! info
- You can also use:
+You can also use:
- * `response_model_exclude_defaults=True`
- * `response_model_exclude_none=True`
+* `response_model_exclude_defaults=True`
+* `response_model_exclude_none=True`
- as described in the Pydantic docs 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
@@ -421,10 +308,13 @@ FastAPI is smart enough (actually, Pydantic is smart enough) to realize that, ev
So, they will be included in the JSON response.
-!!! tip
- Notice that the default values can be anything, not only `None`.
+/// tip
+
+Notice that the default values can be anything, not only `None`.
- They can be a list (`[]`), a `float` of `10.5`, etc.
+They can be a list (`[]`), a `float` of `10.5`, etc.
+
+///
### `response_model_include` and `response_model_exclude`
@@ -434,45 +324,31 @@ They take a `set` of `str` with the name of the attributes to include (omitting
This can be used as a quick shortcut if you have only one Pydantic model and want to remove some data from the output.
-!!! tip
- But it is still recommended to use the ideas above, using multiple classes, instead of these parameters.
+/// tip
+
+But it is still recommended to use the ideas above, using multiple classes, instead of these parameters.
- This is because the JSON Schema generated in your app's OpenAPI (and the docs) will still be the one for the complete model, even if you use `response_model_include` or `response_model_exclude` to omit some attributes.
+This is because the JSON Schema generated in your app's OpenAPI (and the docs) will still be the one for the complete model, even if you use `response_model_include` or `response_model_exclude` to omit some attributes.
- This also applies to `response_model_by_alias` that works similarly.
+This also applies to `response_model_by_alias` that works similarly.
-=== "Python 3.10+"
+///
- ```Python hl_lines="29 35"
- {!> ../../../docs_src/response_model/tutorial005_py310.py!}
- ```
+{* ../../docs_src/response_model/tutorial005_py310.py hl[29,35] *}
-=== "Python 3.6+"
+/// tip
- ```Python hl_lines="31 37"
- {!> ../../../docs_src/response_model/tutorial005.py!}
- ```
+The syntax `{"name", "description"}` creates a `set` with those two values.
-!!! tip
- The syntax `{"name", "description"}` creates a `set` with those two values.
+It is equivalent to `set(["name", "description"])`.
- It is equivalent to `set(["name", "description"])`.
+///
#### Using `list`s instead of `set`s
If you forget to use a `set` and use a `list` or `tuple` instead, FastAPI will still convert it to a `set` and it will work correctly:
-=== "Python 3.10+"
-
- ```Python hl_lines="29 35"
- {!> ../../../docs_src/response_model/tutorial006_py310.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="31 37"
- {!> ../../../docs_src/response_model/tutorial006.py!}
- ```
+{* ../../docs_src/response_model/tutorial006_py310.py hl[29,35] *}
## Recap
diff --git a/docs/en/docs/tutorial/response-status-code.md b/docs/en/docs/tutorial/response-status-code.md
index 646378aa1..41bf02a8f 100644
--- a/docs/en/docs/tutorial/response-status-code.md
+++ b/docs/en/docs/tutorial/response-status-code.md
@@ -8,17 +8,21 @@ The same way you can specify a response model, you can also declare the HTTP sta
* `@app.delete()`
* etc.
-```Python hl_lines="6"
-{!../../../docs_src/response_status_code/tutorial001.py!}
-```
+{* ../../docs_src/response_status_code/tutorial001.py hl[6] *}
-!!! note
- Notice that `status_code` is a parameter of the "decorator" method (`get`, `post`, etc). Not of your *path operation function*, like all the parameters and body.
+/// note
+
+Notice that `status_code` is a parameter of the "decorator" method (`get`, `post`, etc). Not of your *path operation function*, like all the parameters and body.
+
+///
The `status_code` parameter receives a number with the HTTP status code.
-!!! info
- `status_code` can alternatively also receive an `IntEnum`, such as Python's `http.HTTPStatus`.
+/// info
+
+`status_code` can alternatively also receive an `IntEnum`, such as Python's `http.HTTPStatus`.
+
+///
It will:
@@ -27,15 +31,21 @@ It will:
fastapi run --workers 4 main.py +INFO Using path main.py +INFO Resolved absolute path /home/user/code/awesomeapp/main.py +INFO Searching for package file structure from directories with __init__.py files +INFO Importing from /home/user/code/awesomeapp + + ╭─ Python module file ─╮ + │ │ + │ 🐍 main.py │ + │ │ + ╰──────────────────────╯ + +INFO Importing module main +INFO Found importable FastAPI app + + ╭─ Importable FastAPI app ─╮ + │ │ + │ from main import app │ + │ │ + ╰──────────────────────────╯ + +INFO Using import string main:app + + ╭─────────── FastAPI CLI - Production mode ───────────╮ + │ │ + │ Serving at: http://0.0.0.0:8000 │ + │ │ + │ API docs: http://0.0.0.0:8000/docs │ + │ │ + │ Running in production mode, for development use: │ + │ │ + │ fastapi dev │ + │ │ + ╰─────────────────────────────────────────────────────╯ + +INFO: Uvicorn running on http://0.0.0.0:8000 (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. ++``` + +
+ +**FastAPI** no existiría si no fuera por el trabajo previo de otros. + +Ha habido muchas herramientas creadas antes que han ayudado a inspirar su creación. + +He estado evitando la creación de un nuevo framework durante varios años. Primero traté de resolver todas las funcionalidades cubiertas por **FastAPI** usando varios frameworks, complementos y herramientas diferentes. + +Pero en algún momento, no había otra opción que crear algo que proporcionara todas estas funcionalidades, tomando las mejores ideas de herramientas anteriores y combinándolas de la mejor manera posible, usando funcionalidades del lenguaje que ni siquiera estaban disponibles antes (anotaciones de tipos de Python 3.6+). + ++ +## Investigación + +Al usar todas las alternativas anteriores, tuve la oportunidad de aprender de todas ellas, tomar ideas y combinarlas de la mejor manera que pude encontrar para mí y los equipos de desarrolladores con los que he trabajado. + +Por ejemplo, estaba claro que idealmente debería estar basado en las anotaciones de tipos estándar de Python. + +También, el mejor enfoque era usar estándares ya existentes. + +Entonces, antes de siquiera empezar a programar **FastAPI**, pasé varios meses estudiando las especificaciones de OpenAPI, JSON Schema, OAuth2, etc. Entendiendo su relación, superposición y diferencias. + +## Diseño + +Luego pasé algún tiempo diseñando la "API" de desarrollador que quería tener como usuario (como desarrollador usando FastAPI). + +Probé varias ideas en los editores de Python más populares: PyCharm, VS Code, editores basados en Jedi. + +Según la última Encuesta de Desarrolladores de Python, estos editores cubren alrededor del 80% de los usuarios. + +Esto significa que **FastAPI** fue específicamente probado con los editores usados por el 80% de los desarrolladores de Python. Y como la mayoría de los otros editores tienden a funcionar de manera similar, todos sus beneficios deberían funcionar prácticamente para todos los editores. + +De esa manera, pude encontrar las mejores maneras de reducir la duplicación de código tanto como fuera posible, para tener autocompletado en todas partes, chequeos de tipos y errores, etc. + +Todo de una manera que proporcionara la mejor experiencia de desarrollo para todos los desarrolladores. + +## Requisitos + +Después de probar varias alternativas, decidí que iba a usar **Pydantic** por sus ventajas. + +Luego contribuí a este, para hacerlo totalmente compatible con JSON Schema, para soportar diferentes maneras de definir declaraciones de restricciones, y para mejorar el soporte de los editores (chequeo de tipos, autocompletado) basado en las pruebas en varios editores. + +Durante el desarrollo, también contribuí a **Starlette**, el otro requisito clave. + +## Desarrollo + +Para cuando comencé a crear el propio **FastAPI**, la mayoría de las piezas ya estaban en su lugar, el diseño estaba definido, los requisitos y herramientas estaban listos, y el conocimiento sobre los estándares y especificaciones estaba claro y fresco. + +## Futuro + +A este punto, ya está claro que **FastAPI** con sus ideas está siendo útil para muchas personas. + +Está siendo elegido sobre alternativas anteriores por adaptarse mejor a muchos casos de uso. + +Muchos desarrolladores y equipos ya dependen de **FastAPI** para sus proyectos (incluyéndome a mí y a mi equipo). + +Pero aún así, hay muchas mejoras y funcionalidades por venir. + +**FastAPI** tiene un gran futuro por delante. + +Y [tu ayuda](help-fastapi.md){.internal-link target=_blank} es muy apreciada. diff --git a/docs/es/docs/how-to/conditional-openapi.md b/docs/es/docs/how-to/conditional-openapi.md new file mode 100644 index 000000000..4f806ef6c --- /dev/null +++ b/docs/es/docs/how-to/conditional-openapi.md @@ -0,0 +1,56 @@ +# OpenAPI Condicional + +Si lo necesitaras, podrías usar configuraciones y variables de entorno para configurar OpenAPI condicionalmente según el entorno, e incluso desactivarlo por completo. + +## Sobre seguridad, APIs y documentación + +Ocultar las interfaces de usuario de la documentación en producción *no debería* ser la forma de proteger tu API. + +Eso no añade ninguna seguridad extra a tu API, las *path operations* seguirán estando disponibles donde están. + +Si hay una falla de seguridad en tu código, seguirá existiendo. + +Ocultar la documentación solo hace que sea más difícil entender cómo interactuar con tu API y podría dificultar más depurarla en producción. Podría considerarse simplemente una forma de Seguridad mediante oscuridad. + +Si quieres asegurar tu API, hay varias cosas mejores que puedes hacer, por ejemplo: + +* Asegúrate de tener modelos Pydantic bien definidos para tus request bodies y responses. +* Configura los permisos y roles necesarios usando dependencias. +* Nunca guardes contraseñas en texto plano, solo hashes de contraseñas. +* Implementa y utiliza herramientas criptográficas bien conocidas, como Passlib y JWT tokens, etc. +* Añade controles de permisos más detallados con OAuth2 scopes donde sea necesario. +* ...etc. + +No obstante, podrías tener un caso de uso muy específico donde realmente necesites desactivar la documentación de la API para algún entorno (por ejemplo, para producción) o dependiendo de configuraciones de variables de entorno. + +## OpenAPI condicional desde configuraciones y variables de entorno + +Puedes usar fácilmente las mismas configuraciones de Pydantic para configurar tu OpenAPI generado y las interfaces de usuario de la documentación. + +Por ejemplo: + +{* ../../docs_src/conditional_openapi/tutorial001.py hl[6,11] *} + +Aquí declaramos la configuración `openapi_url` con el mismo valor predeterminado de `"/openapi.json"`. + +Y luego la usamos al crear la app de `FastAPI`. + +Entonces podrías desactivar OpenAPI (incluyendo las UI de documentación) configurando la variable de entorno `OPENAPI_URL` a una string vacía, así: + +
- FastAPI framework, alto desempeño, fácil de aprender, rápido de programar, listo para producción + FastAPI framework, alto rendimiento, fácil de aprender, rápido de programar, listo para producción
--- **Documentación**: https://fastapi.tiangolo.com -**Código Fuente**: https://github.com/tiangolo/fastapi +**Código Fuente**: https://github.com/fastapi/fastapi --- -FastAPI es un web framework moderno y rápido (de alto rendimiento) para construir APIs con Python 3.6+ basado en las anotaciones de tipos estándar de Python. -Sus características principales son: +FastAPI es un framework web moderno, rápido (de alto rendimiento), para construir APIs con Python basado en las anotaciones de tipos estándar de Python. -* **Rapidez**: Alto rendimiento, a la par con **NodeJS** y **Go** (gracias a Starlette y Pydantic). [Uno de los frameworks de Python más rápidos](#rendimiento). +Las características clave son: -* **Rápido de programar**: Incrementa la velocidad de desarrollo entre 200% y 300%. * -* **Menos errores**: Reduce los errores humanos (de programador) aproximadamente un 40%. * -* **Intuitivo**: Gran soporte en los editores con auto completado en todas partes. Gasta menos tiempo debugging. -* **Fácil**: Está diseñado para ser fácil de usar y aprender. Gastando menos tiempo leyendo documentación. -* **Corto**: Minimiza la duplicación de código. Múltiples funcionalidades con cada declaración de parámetros. Menos errores. -* **Robusto**: Crea código listo para producción con documentación automática interactiva. -* **Basado en estándares**: Basado y totalmente compatible con los estándares abiertos para APIs: OpenAPI (conocido previamente como Swagger) y JSON Schema. +* **Rápido**: Muy alto rendimiento, a la par con **NodeJS** y **Go** (gracias a Starlette y Pydantic). [Uno de los frameworks Python más rápidos disponibles](#performance). +* **Rápido de programar**: Aumenta la velocidad para desarrollar funcionalidades en aproximadamente un 200% a 300%. * +* **Menos bugs**: Reduce en aproximadamente un 40% los errores inducidos por humanos (desarrolladores). * +* **Intuitivo**: Gran soporte para editores. Autocompletado en todas partes. Menos tiempo depurando. +* **Fácil**: Diseñado para ser fácil de usar y aprender. Menos tiempo leyendo documentación. +* **Corto**: Minimiza la duplicación de código. Múltiples funcionalidades desde cada declaración de parámetro. Menos bugs. +* **Robusto**: Obtén código listo para producción. Con documentación interactiva automática. +* **Basado en estándares**: Basado (y completamente compatible) con los estándares abiertos para APIs: OpenAPI (anteriormente conocido como Swagger) y JSON Schema. -* Esta estimación está basada en pruebas con un equipo de desarrollo interno contruyendo aplicaciones listas para producción. +* estimación basada en pruebas con un equipo de desarrollo interno, construyendo aplicaciones de producción. ## Sponsors @@ -58,41 +67,47 @@ Sus características principales son: ## Opiniones -"_[...] 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._" +"_[...] Estoy usando **FastAPI** un montón estos días. [...] De hecho, estoy planeando usarlo para todos los servicios de **ML de mi equipo en Microsoft**. Algunos de ellos se están integrando en el núcleo del producto **Windows** y algunos productos de **Office**._" -uvicorn main:app --reload
...fastapi dev main.py
...ujson
- para "parsing" de JSON más rápido.
-* email_validator
- para validación de emails.
+* email-validator
- para validación de correos electrónicos.
+
+Usadas por Starlette:
+
+* httpx
- Requerido si deseas usar el `TestClient`.
+* jinja2
- Requerido si deseas usar la configuración de plantilla predeterminada.
+* python-multipart
- Requerido si deseas soportar "parsing" de forms, con `request.form()`.
+
+Usadas por FastAPI / Starlette:
+
+* uvicorn
- para el servidor que carga y sirve tu aplicación. Esto incluye `uvicorn[standard]`, que incluye algunas dependencias (por ejemplo, `uvloop`) necesarias para servir con alto rendimiento.
+* `fastapi-cli` - para proporcionar el comando `fastapi`.
+
+### Sin Dependencias `standard`
+
+Si no deseas incluir las dependencias opcionales `standard`, puedes instalar con `pip install fastapi` en lugar de `pip install "fastapi[standard]"`.
+
+### Dependencias Opcionales Adicionales
-Usados por Starlette:
+Existen algunas dependencias adicionales que podrías querer instalar.
-* httpx
- Requerido si quieres usar el `TestClient`.
-* jinja2
- Requerido si quieres usar la configuración por defecto de templates.
-* python-multipart
- Requerido si quieres dar soporte a "parsing" de formularios, con `request.form()`.
-* itsdangerous
- Requerido para dar soporte a `SessionMiddleware`.
-* pyyaml
- Requerido para dar soporte al `SchemaGenerator` de Starlette (probablemente no lo necesites con FastAPI).
-* graphene
- Requerido para dar soporte a `GraphQLApp`.
-* ujson
- Requerido si quieres usar `UJSONResponse`.
+Dependencias opcionales adicionales de Pydantic:
-Usado por FastAPI / Starlette:
+* pydantic-settings
- para la gestión de configuraciones.
+* pydantic-extra-types
- para tipos extra para ser usados con Pydantic.
-* uvicorn
- para el servidor que carga y sirve tu aplicación.
-* orjson
- Requerido si quieres usar `ORJSONResponse`.
+Dependencias opcionales adicionales de FastAPI:
-Puedes instalarlos con `pip install fastapi[all]`.
+* orjson
- Requerido si deseas usar `ORJSONResponse`.
+* ujson
- Requerido si deseas usar `UJSONResponse`.
## Licencia
-Este proyecto está licenciado bajo los términos de la licencia del MIT.
+Este proyecto tiene licencia bajo los términos de la licencia MIT.
diff --git a/docs/es/docs/learn/index.md b/docs/es/docs/learn/index.md
new file mode 100644
index 000000000..cc6c7cc3f
--- /dev/null
+++ b/docs/es/docs/learn/index.md
@@ -0,0 +1,5 @@
+# Aprende
+
+Aquí están las secciones introductorias y los tutoriales para aprender **FastAPI**.
+
+Podrías considerar esto un **libro**, un **curso**, la forma **oficial** y recomendada de aprender FastAPI. 😎
diff --git a/docs/es/docs/project-generation.md b/docs/es/docs/project-generation.md
new file mode 100644
index 000000000..559995151
--- /dev/null
+++ b/docs/es/docs/project-generation.md
@@ -0,0 +1,28 @@
+# Plantilla Full Stack FastAPI
+
+Las plantillas, aunque normalmente vienen con una configuración específica, están diseñadas para ser flexibles y personalizables. Esto te permite modificarlas y adaptarlas a los requisitos de tu proyecto, haciéndolas un excelente punto de partida. 🏁
+
+Puedes usar esta plantilla para comenzar, ya que incluye gran parte de la configuración inicial, seguridad, base de datos y algunos endpoints de API ya hechos para ti.
+
+Repositorio de GitHub: Plantilla Full Stack FastAPI
+
+## Plantilla Full Stack FastAPI - Tecnología y Funcionalidades
+
+- ⚡ [**FastAPI**](https://fastapi.tiangolo.com) para la API del backend en Python.
+ - 🧰 [SQLModel](https://sqlmodel.tiangolo.com) para las interacciones con bases de datos SQL en Python (ORM).
+ - 🔍 [Pydantic](https://docs.pydantic.dev), utilizado por FastAPI, para la validación de datos y gestión de configuraciones.
+ - 💾 [PostgreSQL](https://www.postgresql.org) como base de datos SQL.
+- 🚀 [React](https://react.dev) para el frontend.
+ - 💃 Usando TypeScript, hooks, [Vite](https://vitejs.dev), y otras partes de una stack moderna de frontend.
+ - 🎨 [Chakra UI](https://chakra-ui.com) para los componentes del frontend.
+ - 🤖 Un cliente de frontend generado automáticamente.
+ - 🧪 [Playwright](https://playwright.dev) para pruebas End-to-End.
+ - 🦇 Soporte para modo oscuro.
+- 🐋 [Docker Compose](https://www.docker.com) para desarrollo y producción.
+- 🔒 Hashing seguro de contraseñas por defecto.
+- 🔑 Autenticación con tokens JWT.
+- 📫 Recuperación de contraseñas basada en email.
+- ✅ Pruebas con [Pytest](https://pytest.org).
+- 📞 [Traefik](https://traefik.io) como proxy inverso / balanceador de carga.
+- 🚢 Instrucciones de despliegue usando Docker Compose, incluyendo cómo configurar un proxy Traefik frontend para manejar certificados HTTPS automáticos.
+- 🏭 CI (integración continua) y CD (despliegue continuo) basados en GitHub Actions.
diff --git a/docs/es/docs/python-types.md b/docs/es/docs/python-types.md
index e9fd61629..769204f8f 100644
--- a/docs/es/docs/python-types.md
+++ b/docs/es/docs/python-types.md
@@ -1,29 +1,30 @@
-# Introducción a los Tipos de Python
+# Introducción a Tipos en Python
-**Python 3.6+** tiene soporte para "type hints" opcionales.
+Python tiene soporte para "anotaciones de tipos" opcionales (también llamadas "type hints").
-Estos **type hints** son una nueva sintáxis, desde Python 3.6+, que permite declarar el tipo de una variable.
+Estas **"anotaciones de tipos"** o type hints son una sintaxis especial que permite declarar el tipo de una variable.
-Usando las declaraciones de tipos para tus variables, los editores y otras herramientas pueden proveerte un soporte mejor.
+Al declarar tipos para tus variables, los editores y herramientas te pueden proporcionar un mejor soporte.
-Este es solo un **tutorial corto** sobre los Python type hints. Solo cubre lo mínimo necesario para usarlos con **FastAPI**... realmente es muy poco lo que necesitas.
+Este es solo un **tutorial rápido / recordatorio** sobre las anotaciones de tipos en Python. Cubre solo lo mínimo necesario para usarlas con **FastAPI**... que en realidad es muy poco.
-Todo **FastAPI** está basado en estos type hints, lo que le da muchas ventajas y beneficios.
+**FastAPI** se basa completamente en estas anotaciones de tipos, dándole muchas ventajas y beneficios.
-Pero, así nunca uses **FastAPI** te beneficiarás de aprender un poco sobre los type hints.
+Pero incluso si nunca usas **FastAPI**, te beneficiaría aprender un poco sobre ellas.
-!!! note "Nota"
- Si eres un experto en Python y ya lo sabes todo sobre los type hints, salta al siguiente capítulo.
+/// note | Nota
+
+Si eres un experto en Python, y ya sabes todo sobre las anotaciones de tipos, salta al siguiente capítulo.
+
+///
## Motivación
Comencemos con un ejemplo simple:
-```Python
-{!../../../docs_src/python_types/tutorial001.py!}
-```
+{* ../../docs_src/python_types/tutorial001.py *}
-Llamar este programa nos muestra el siguiente output:
+Llamar a este programa genera:
```
John Doe
@@ -31,39 +32,37 @@ John Doe
La función hace lo siguiente:
-* Toma un `first_name` y un `last_name`.
-* Convierte la primera letra de cada uno en una letra mayúscula con `title()`.
-* Las concatena con un espacio en la mitad.
+* Toma un `first_name` y `last_name`.
+* Convierte la primera letra de cada uno a mayúsculas con `title()`.
+* Concatena ambos con un espacio en el medio.
-```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial001.py!}
-```
+{* ../../docs_src/python_types/tutorial001.py hl[2] *}
### Edítalo
Es un programa muy simple.
-Ahora, imagina que lo estás escribiendo desde ceros.
+Pero ahora imagina que lo escribieras desde cero.
-En algún punto habrías comenzado con la definición de la función, tenías los parámetros listos...
+En algún momento habrías empezado la definición de la función, tenías los parámetros listos...
-Pero, luego tienes que llamar "ese método que convierte la primera letra en una mayúscula".
+Pero luego tienes que llamar "ese método que convierte la primera letra a mayúscula".
-Era `upper`? O era `uppercase`? `first_uppercase`? `capitalize`?
+¿Era `upper`? ¿Era `uppercase`? `first_uppercase`? `capitalize`?
-Luego lo intentas con el viejo amigo de los programadores, el autocompletado del editor.
+Entonces, pruebas con el amigo del viejo programador, el autocompletado del editor.
-Escribes el primer parámetro de la función `first_name`, luego un punto (`.`) y luego presionas `Ctrl+Space` para iniciar el autocompletado.
+Escribes el primer parámetro de la función, `first_name`, luego un punto (`.`) y luego presionas `Ctrl+Espacio` para activar el autocompletado.
-Tristemente, no obtienes nada útil:
+Pero, tristemente, no obtienes nada útil:
-get
+* usando una get
operation
-!!! info "Información sobre `@decorator`"
- Esa sintaxis `@algo` se llama un "decorador" en Python.
+/// info | Información sobre `@decorator`
- Lo pones encima de una función. Es como un lindo sombrero decorado (creo que de ahí salió el concepto).
+Esa sintaxis `@algo` en Python se llama un "decorador".
- Un "decorador" toma la función que tiene debajo y hace algo con ella.
+Lo pones encima de una función. Como un bonito sombrero decorativo (supongo que de ahí viene el término).
- En nuestro caso, este decorador le dice a **FastAPI** que la función que está debajo corresponde al **path** `/` con una **operación** `get`.
+Un "decorador" toma la función de abajo y hace algo con ella.
- Es el "**decorador de operaciones de path**".
+En nuestro caso, este decorador le dice a **FastAPI** que la función de abajo corresponde al **path** `/` con una **operation** `get`.
+
+Es el "**path operation decorator**".
+
+///
También puedes usar las otras operaciones:
@@ -267,67 +265,67 @@ También puedes usar las otras operaciones:
* `@app.put()`
* `@app.delete()`
-y las más exóticas:
+Y los más exóticos:
* `@app.options()`
* `@app.head()`
* `@app.patch()`
* `@app.trace()`
-!!! tip "Consejo"
- Tienes la libertad de usar cada operación (método de HTTP) como quieras.
+/// tip
+
+Eres libre de usar cada operación (método HTTP) como quieras.
- **FastAPI** no impone ningún significado específico.
+**FastAPI** no fuerza ningún significado específico.
- La información que está presentada aquí es una guía, no un requerimiento.
+La información aquí se presenta como una guía, no un requisito.
- Por ejemplo, cuando usas GraphQL normalmente realizas todas las acciones usando únicamente operaciones `POST`.
+Por ejemplo, cuando usas GraphQL normalmente realizas todas las acciones usando solo operaciones `POST`.
-### Paso 4: define la **función de la operación de path**
+///
-Esta es nuestra "**función de la operación de path**":
+### Paso 4: define la **path operation function**
+
+Esta es nuestra "**path operation function**":
* **path**: es `/`.
-* **operación**: es `get`.
-* **función**: es la función debajo del "decorador" (debajo de `@app.get("/")`).
+* **operation**: es `get`.
+* **function**: es la función debajo del "decorador" (debajo de `@app.get("/")`).
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[7] *}
-Esto es una función de Python.
+Esta es una función de Python.
-Esta función será llamada por **FastAPI** cada vez que reciba un request en la URL "`/`" usando una operación `GET`.
+Será llamada por **FastAPI** cuando reciba un request en la URL "`/`" usando una operación `GET`.
-En este caso es una función `async`.
+En este caso, es una función `async`.
---
-También podrías definirla como una función normal, en vez de `async def`:
+También podrías definirla como una función normal en lugar de `async def`:
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial003.py!}
-```
+{* ../../docs_src/first_steps/tutorial003.py hl[7] *}
-!!! note "Nota"
- Si no sabes la diferencia, revisa el [Async: *"¿Tienes prisa?"*](../async.md#in-a-hurry){.internal-link target=_blank}.
+/// note | Nota
-### Paso 5: devuelve el contenido
+Si no sabes la diferencia, revisa la sección [Async: *"¿Tienes prisa?"*](../async.md#in-a-hurry){.internal-link target=_blank}.
-```Python hl_lines="8"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+///
+
+### Paso 5: retorna el contenido
+
+{* ../../docs_src/first_steps/tutorial001.py hl[8] *}
-Puedes devolver `dict`, `list`, valores singulares como un `str`, `int`, etc.
+Puedes retornar un `dict`, `list`, valores singulares como `str`, `int`, etc.
-También puedes devolver modelos de Pydantic (ya verás más sobre esto más adelante).
+También puedes retornar modelos de Pydantic (verás más sobre eso más adelante).
-Hay muchos objetos y modelos que pueden ser convertidos automáticamente a JSON (incluyendo ORMs, etc.). Intenta usar tus favoritos, es muy probable que ya tengan soporte.
+Hay muchos otros objetos y modelos que serán automáticamente convertidos a JSON (incluyendo ORMs, etc). Intenta usar tus favoritos, es altamente probable que ya sean compatibles.
-## Repaso
+## Recapitulación
* Importa `FastAPI`.
-* Crea un instance de `app`.
-* Escribe un **decorador de operación de path** (como `@app.get("/")`).
-* Escribe una **función de la operación de path** (como `def root(): ...` arriba).
-* Corre el servidor de desarrollo (como `uvicorn main:app --reload`).
+* Crea una instancia `app`.
+* Escribe un **path operation decorator** usando decoradores como `@app.get("/")`.
+* Define una **path operation function**; por ejemplo, `def root(): ...`.
+* Ejecuta el servidor de desarrollo usando el comando `fastapi dev`.
diff --git a/docs/es/docs/tutorial/handling-errors.md b/docs/es/docs/tutorial/handling-errors.md
new file mode 100644
index 000000000..2e4464989
--- /dev/null
+++ b/docs/es/docs/tutorial/handling-errors.md
@@ -0,0 +1,255 @@
+# Manejo de Errores
+
+Existen muchas situaciones en las que necesitas notificar un error a un cliente que está usando tu API.
+
+Este cliente podría ser un navegador con un frontend, un código de otra persona, un dispositivo IoT, etc.
+
+Podrías necesitar decirle al cliente que:
+
+* El cliente no tiene suficientes privilegios para esa operación.
+* El cliente no tiene acceso a ese recurso.
+* El ítem al que el cliente intentaba acceder no existe.
+* etc.
+
+En estos casos, normalmente devolverías un **código de estado HTTP** en el rango de **400** (de 400 a 499).
+
+Esto es similar a los códigos de estado HTTP 200 (de 200 a 299). Esos códigos de estado "200" significan que de alguna manera hubo un "éxito" en el request.
+
+Los códigos de estado en el rango de 400 significan que hubo un error por parte del cliente.
+
+¿Recuerdas todos esos errores de **"404 Not Found"** (y chistes)?
+
+## Usa `HTTPException`
+
+Para devolver responses HTTP con errores al cliente, usa `HTTPException`.
+
+### Importa `HTTPException`
+
+{* ../../docs_src/handling_errors/tutorial001.py hl[1] *}
+
+### Lanza un `HTTPException` en tu código
+
+`HTTPException` es una excepción de Python normal con datos adicionales relevantes para APIs.
+
+Debido a que es una excepción de Python, no la `return`, sino que la `raise`.
+
+Esto también significa que si estás dentro de una función de utilidad que estás llamando dentro de tu *path operation function*, y lanzas el `HTTPException` desde dentro de esa función de utilidad, no se ejecutará el resto del código en la *path operation function*, terminará ese request de inmediato y enviará el error HTTP del `HTTPException` al cliente.
+
+El beneficio de lanzar una excepción en lugar de `return`ar un valor será más evidente en la sección sobre Dependencias y Seguridad.
+
+En este ejemplo, cuando el cliente solicita un ítem por un ID que no existe, lanza una excepción con un código de estado de `404`:
+
+{* ../../docs_src/handling_errors/tutorial001.py hl[11] *}
+
+### El response resultante
+
+Si el cliente solicita `http://example.com/items/foo` (un `item_id` `"foo"`), ese cliente recibirá un código de estado HTTP de 200, y un response JSON de:
+
+```JSON
+{
+ "item": "The Foo Wrestlers"
+}
+```
+
+Pero si el cliente solicita `http://example.com/items/bar` (un `item_id` inexistente `"bar"`), ese cliente recibirá un código de estado HTTP de 404 (el error "no encontrado"), y un response JSON de:
+
+```JSON
+{
+ "detail": "Item not found"
+}
+```
+
+/// tip | Consejo
+
+Cuando lanzas un `HTTPException`, puedes pasar cualquier valor que pueda convertirse a JSON como el parámetro `detail`, no solo `str`.
+
+Podrías pasar un `dict`, un `list`, etc.
+
+Son manejados automáticamente por **FastAPI** y convertidos a JSON.
+
+///
+
+## Agrega headers personalizados
+
+Existen algunas situaciones en las que es útil poder agregar headers personalizados al error HTTP. Por ejemplo, para algunos tipos de seguridad.
+
+Probablemente no necesitarás usarlos directamente en tu código.
+
+Pero en caso de que los necesites para un escenario avanzado, puedes agregar headers personalizados:
+
+{* ../../docs_src/handling_errors/tutorial002.py hl[14] *}
+
+## Instalar manejadores de excepciones personalizados
+
+Puedes agregar manejadores de excepciones personalizados con las mismas utilidades de excepciones de Starlette.
+
+Supongamos que tienes una excepción personalizada `UnicornException` que tú (o un paquete que usas) podría lanzar.
+
+Y quieres manejar esta excepción globalmente con FastAPI.
+
+Podrías agregar un manejador de excepciones personalizado con `@app.exception_handler()`:
+
+{* ../../docs_src/handling_errors/tutorial003.py hl[5:7,13:18,24] *}
+
+Aquí, si solicitas `/unicorns/yolo`, la *path operation* lanzará un `UnicornException`.
+
+Pero será manejado por el `unicorn_exception_handler`.
+
+Así que recibirás un error limpio, con un código de estado HTTP de `418` y un contenido JSON de:
+
+```JSON
+{"message": "Oops! yolo did something. There goes a rainbow..."}
+```
+
+/// note | Nota Técnica
+
+También podrías usar `from starlette.requests import Request` y `from starlette.responses import JSONResponse`.
+
+**FastAPI** ofrece las mismas `starlette.responses` como `fastapi.responses` solo como una conveniencia para ti, el desarrollador. Pero la mayoría de los responses disponibles vienen directamente de Starlette. Lo mismo con `Request`.
+
+///
+
+## Sobrescribir los manejadores de excepciones predeterminados
+
+**FastAPI** tiene algunos manejadores de excepciones predeterminados.
+
+Estos manejadores se encargan de devolver los responses JSON predeterminadas cuando lanzas un `HTTPException` y cuando el request tiene datos inválidos.
+
+Puedes sobrescribir estos manejadores de excepciones con los tuyos propios.
+
+### Sobrescribir excepciones de validación de request
+
+Cuando un request contiene datos inválidos, **FastAPI** lanza internamente un `RequestValidationError`.
+
+Y también incluye un manejador de excepciones predeterminado para ello.
+
+Para sobrescribirlo, importa el `RequestValidationError` y úsalo con `@app.exception_handler(RequestValidationError)` para decorar el manejador de excepciones.
+
+El manejador de excepciones recibirá un `Request` y la excepción.
+
+{* ../../docs_src/handling_errors/tutorial004.py hl[2,14:16] *}
+
+Ahora, si vas a `/items/foo`, en lugar de obtener el error JSON por defecto con:
+
+```JSON
+{
+ "detail": [
+ {
+ "loc": [
+ "path",
+ "item_id"
+ ],
+ "msg": "value is not a valid integer",
+ "type": "type_error.integer"
+ }
+ ]
+}
+```
+
+obtendrás una versión en texto, con:
+
+```
+1 validation error
+path -> item_id
+ value is not a valid integer (type=type_error.integer)
+```
+
+#### `RequestValidationError` vs `ValidationError`
+
+/// warning | Advertencia
+
+Estos son detalles técnicos que podrías omitir si no es importante para ti en este momento.
+
+///
+
+`RequestValidationError` es una subclase de `ValidationError` de Pydantic.
+
+**FastAPI** la usa para que, si usas un modelo Pydantic en `response_model`, y tus datos tienen un error, lo verás en tu log.
+
+Pero el cliente/usuario no lo verá. En su lugar, el cliente recibirá un "Error Interno del Servidor" con un código de estado HTTP `500`.
+
+Debería ser así porque si tienes un `ValidationError` de Pydantic en tu *response* o en cualquier lugar de tu código (no en el *request* del cliente), en realidad es un bug en tu código.
+
+Y mientras lo arreglas, tus clientes/usuarios no deberían tener acceso a información interna sobre el error, ya que eso podría exponer una vulnerabilidad de seguridad.
+
+### Sobrescribir el manejador de errores de `HTTPException`
+
+De la misma manera, puedes sobrescribir el manejador de `HTTPException`.
+
+Por ejemplo, podrías querer devolver un response de texto plano en lugar de JSON para estos errores:
+
+{* ../../docs_src/handling_errors/tutorial004.py hl[3:4,9:11,22] *}
+
+/// note | Nota Técnica
+
+También podrías usar `from starlette.responses import PlainTextResponse`.
+
+**FastAPI** ofrece las mismas `starlette.responses` como `fastapi.responses` solo como una conveniencia para ti, el desarrollador. Pero la mayoría de los responses disponibles vienen directamente de Starlette.
+
+///
+
+### Usar el body de `RequestValidationError`
+
+El `RequestValidationError` contiene el `body` que recibió con datos inválidos.
+
+Podrías usarlo mientras desarrollas tu aplicación para registrar el body y depurarlo, devolverlo al usuario, etc.
+
+{* ../../docs_src/handling_errors/tutorial005.py hl[14] *}
+
+Ahora intenta enviar un ítem inválido como:
+
+```JSON
+{
+ "title": "towel",
+ "size": "XL"
+}
+```
+
+Recibirás un response que te dirá que los datos son inválidos conteniendo el body recibido:
+
+```JSON hl_lines="12-15"
+{
+ "detail": [
+ {
+ "loc": [
+ "body",
+ "size"
+ ],
+ "msg": "value is not a valid integer",
+ "type": "type_error.integer"
+ }
+ ],
+ "body": {
+ "title": "towel",
+ "size": "XL"
+ }
+}
+```
+
+#### `HTTPException` de FastAPI vs `HTTPException` de Starlette
+
+**FastAPI** tiene su propio `HTTPException`.
+
+Y la clase de error `HTTPException` de **FastAPI** hereda de la clase de error `HTTPException` de Starlette.
+
+La única diferencia es que el `HTTPException` de **FastAPI** acepta cualquier dato JSON-able para el campo `detail`, mientras que el `HTTPException` de Starlette solo acepta strings para ello.
+
+Así que puedes seguir lanzando un `HTTPException` de **FastAPI** como de costumbre en tu código.
+
+Pero cuando registras un manejador de excepciones, deberías registrarlo para el `HTTPException` de Starlette.
+
+De esta manera, si alguna parte del código interno de Starlette, o una extensión o complemento de Starlette, lanza un `HTTPException` de Starlette, tu manejador podrá capturarlo y manejarlo.
+
+En este ejemplo, para poder tener ambos `HTTPException` en el mismo código, las excepciones de Starlette son renombradas a `StarletteHTTPException`:
+
+```Python
+from starlette.exceptions import HTTPException as StarletteHTTPException
+```
+
+### Reutilizar los manejadores de excepciones de **FastAPI**
+
+Si quieres usar la excepción junto con los mismos manejadores de excepciones predeterminados de **FastAPI**, puedes importar y reutilizar los manejadores de excepciones predeterminados de `fastapi.exception_handlers`:
+
+{* ../../docs_src/handling_errors/tutorial006.py hl[2:5,15,21] *}
+
+En este ejemplo solo estás `print`eando el error con un mensaje muy expresivo, pero te haces una idea. Puedes usar la excepción y luego simplemente reutilizar los manejadores de excepciones predeterminados.
diff --git a/docs/es/docs/tutorial/header-param-models.md b/docs/es/docs/tutorial/header-param-models.md
new file mode 100644
index 000000000..3676231e6
--- /dev/null
+++ b/docs/es/docs/tutorial/header-param-models.md
@@ -0,0 +1,56 @@
+# Modelos de Parámetros de Header
+
+Si tienes un grupo de **parámetros de header** relacionados, puedes crear un **modelo Pydantic** para declararlos.
+
+Esto te permitirá **reutilizar el modelo** en **múltiples lugares** y también declarar validaciones y metadatos para todos los parámetros al mismo tiempo. 😎
+
+/// note | Nota
+
+Esto es compatible desde la versión `0.115.0` de FastAPI. 🤓
+
+///
+
+## Parámetros de Header con un Modelo Pydantic
+
+Declara los **parámetros de header** que necesitas en un **modelo Pydantic**, y luego declara el parámetro como `Header`:
+
+{* ../../docs_src/header_param_models/tutorial001_an_py310.py hl[9:14,18] *}
+
+**FastAPI** **extraerá** los datos para **cada campo** de los **headers** en el request y te dará el modelo Pydantic que definiste.
+
+## Revisa la Documentación
+
+Puedes ver los headers requeridos en la interfaz de documentación en `/docs`:
+
+contact
fieldsParámetro | Tipo | Descripción |
---|---|---|
name | str | El nombre identificativo de la persona/organización de contacto. |
url | str | La URL que apunta a la información de contacto. DEBE tener el formato de una URL. |
email | str | La dirección de correo electrónico de la persona/organización de contacto. DEBE tener el formato de una dirección de correo. |
license_info
fieldsParámetro | Tipo | Descripción |
---|---|---|
name | str | REQUERIDO (si se establece un license_info ). El nombre de la licencia utilizada para la API. |
identifier | str | Una expresión de licencia SPDX para la API. El campo identifier es mutuamente excluyente del campo url . Disponible desde OpenAPI 3.1.0, FastAPI 0.99.0. |
url | str | Una URL a la licencia utilizada para la API. DEBE tener el formato de una URL. |
kwargs
. Incluso si no tienen un valor por defecto.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *}
+
+### Mejor con `Annotated`
+
+Ten en cuenta que si usas `Annotated`, como no estás usando valores por defecto de los parámetros de la función, no tendrás este problema y probablemente no necesitarás usar `*`.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py hl[10] *}
+
+## Validaciones numéricas: mayor o igual
+
+Con `Query` y `Path` (y otros que verás más adelante) puedes declarar restricciones numéricas.
+
+Aquí, con `ge=1`, `item_id` necesitará ser un número entero "`g`reater than or `e`qual" a `1`.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py hl[10] *}
+
+## Validaciones numéricas: mayor que y menor o igual
+
+Lo mismo aplica para:
+
+* `gt`: `g`reater `t`han
+* `le`: `l`ess than or `e`qual
+
+{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py hl[10] *}
+
+## Validaciones numéricas: flotantes, mayor y menor
+
+Las validaciones numéricas también funcionan para valores `float`.
+
+Aquí es donde se convierte en importante poder declarar gt
y no solo ge
. Ya que con esto puedes requerir, por ejemplo, que un valor sea mayor que `0`, incluso si es menor que `1`.
+
+Así, `0.5` sería un valor válido. Pero `0.0` o `0` no lo serían.
+
+Y lo mismo para lt
.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py hl[13] *}
+
+## Resumen
+
+Con `Query`, `Path` (y otros que aún no has visto) puedes declarar metadatos y validaciones de string de las mismas maneras que con [Parámetros de Query y Validaciones de String](query-params-str-validations.md){.internal-link target=_blank}.
+
+Y también puedes declarar validaciones numéricas:
+
+* `gt`: `g`reater `t`han
+* `ge`: `g`reater than or `e`qual
+* `lt`: `l`ess `t`han
+* `le`: `l`ess than or `e`qual
+
+/// info | Información
+
+`Query`, `Path` y otras clases que verás más adelante son subclases de una clase común `Param`.
+
+Todas ellas comparten los mismos parámetros para validación adicional y metadatos que has visto.
+
+///
+
+/// note | Nota técnica
+
+Cuando importas `Query`, `Path` y otros de `fastapi`, en realidad son funciones.
+
+Que cuando se llaman, retornan instances de clases con el mismo nombre.
+
+Así que importas `Query`, que es una función. Y cuando la llamas, retorna una instance de una clase también llamada `Query`.
+
+Estas funciones están allí (en lugar de usar simplemente las clases directamente) para que tu editor no marque errores sobre sus tipos.
+
+De esa forma puedes usar tu editor y herramientas de programación normales sin tener que agregar configuraciones personalizadas para omitir esos errores.
+
+///
diff --git a/docs/es/docs/tutorial/path-params.md b/docs/es/docs/tutorial/path-params.md
index 6432de1cd..12a1b647b 100644
--- a/docs/es/docs/tutorial/path-params.md
+++ b/docs/es/docs/tutorial/path-params.md
@@ -1,14 +1,12 @@
-# Parámetros de path
+# Parámetros de Path
-Puedes declarar los "parámetros" o "variables" con la misma sintaxis que usan los format strings de Python:
+Puedes declarar "parámetros" o "variables" de path con la misma sintaxis que se usa en los format strings de Python:
-```Python hl_lines="6-7"
-{!../../../docs_src/path_params/tutorial001.py!}
-```
+{* ../../docs_src/path_params/tutorial001.py hl[6:7] *}
-El valor del parámetro de path `item_id` será pasado a tu función como el argumento `item_id`.
+El valor del parámetro de path `item_id` se pasará a tu función como el argumento `item_id`.
-Entonces, si corres este ejemplo y vas a http://127.0.0.1:8000/items/foo, verás una respuesta de:
+Así que, si ejecutas este ejemplo y vas a http://127.0.0.1:8000/items/foo, verás un response de:
```JSON
{"item_id":"foo"}
@@ -16,175 +14,190 @@ Entonces, si corres este ejemplo y vas a Conversión de datos
+## Conversión de datos
-Si corres este ejemplo y abres tu navegador en http://127.0.0.1:8000/items/3 verás una respuesta de:
+Si ejecutas este ejemplo y abres tu navegador en http://127.0.0.1:8000/items/3, verás un response de:
```JSON
{"item_id":3}
```
-!!! check "Revisa"
- Observa que el valor que recibió (y devolvió) tu función es `3`, como un Python `int`, y no un string `"3"`.
+/// check | Revisa
- Entonces, con esa declaración de tipos **FastAPI** te da "parsing" automático del request.
+Nota que el valor que tu función recibió (y devolvió) es `3`, como un `int` de Python, no un string `"3"`.
+
+Entonces, con esa declaración de tipo, **FastAPI** te ofrece "parsing" automático de requests.
+
+///
## Validación de datos
-Pero si abres tu navegador en http://127.0.0.1:8000/items/foo verás este lindo error de HTTP:
+Pero si vas al navegador en http://127.0.0.1:8000/items/foo, verás un bonito error HTTP de:
```JSON
{
- "detail": [
- {
- "loc": [
- "path",
- "item_id"
- ],
- "msg": "value is not a valid integer",
- "type": "type_error.integer"
- }
- ]
+ "detail": [
+ {
+ "type": "int_parsing",
+ "loc": [
+ "path",
+ "item_id"
+ ],
+ "msg": "Input should be a valid integer, unable to parse string as an integer",
+ "input": "foo",
+ "url": "https://errors.pydantic.dev/2.1/v/int_parsing"
+ }
+ ]
}
```
-debido a que el parámetro de path `item_id` tenía el valor `"foo"`, que no es un `int`.
+porque el parámetro de path `item_id` tenía un valor de `"foo"`, que no es un `int`.
+
+El mismo error aparecería si proporcionaras un `float` en lugar de un `int`, como en: http://127.0.0.1:8000/items/4.2
-El mismo error aparecería si pasaras un `float` en vez de un `int` como en: http://127.0.0.1:8000/items/4.2
+/// check | Revisa
-!!! check "Revisa"
- Así, con la misma declaración de tipo de Python, **FastAPI** te da validación de datos.
+Entonces, con la misma declaración de tipo de Python, **FastAPI** te ofrece validación de datos.
- Observa que el error también muestra claramente el punto exacto en el que no pasó la validación.
+Nota que el error también indica claramente el punto exacto donde la validación falló.
- Esto es increíblemente útil cuando estás desarrollando y debugging código que interactúa con tu API.
+Esto es increíblemente útil mientras desarrollas y depuras código que interactúa con tu API.
+
+///
## Documentación
-Cuando abras tu navegador en http://127.0.0.1:8000/docs verás la documentación automática e interactiva del API como:
+Y cuando abras tu navegador en http://127.0.0.1:8000/docs, verás una documentación de API automática e interactiva como:
POST
.
+
+///
+
+/// warning | Advertencia
+
+Puedes declarar múltiples parámetros `File` y `Form` en una *path operation*, pero no puedes declarar campos `Body` que esperas recibir como JSON, ya que el request tendrá el cuerpo codificado usando `multipart/form-data` en lugar de `application/json`.
+
+Esto no es una limitación de **FastAPI**, es parte del protocolo HTTP.
+
+///
+
+## Subida de Archivos Opcional
+
+Puedes hacer un archivo opcional utilizando anotaciones de tipos estándar y estableciendo un valor por defecto de `None`:
+
+{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *}
+
+## `UploadFile` con Metadatos Adicionales
+
+También puedes usar `File()` con `UploadFile`, por ejemplo, para establecer metadatos adicionales:
+
+{* ../../docs_src/request_files/tutorial001_03_an_py39.py hl[9,15] *}
+
+## Subidas de Múltiples Archivos
+
+Es posible subir varios archivos al mismo tiempo.
+
+Estarían asociados al mismo "campo de formulario" enviado usando "form data".
+
+Para usar eso, declara una lista de `bytes` o `UploadFile`:
+
+{* ../../docs_src/request_files/tutorial002_an_py39.py hl[10,15] *}
+
+Recibirás, como se declaró, una `list` de `bytes` o `UploadFile`s.
+
+/// note | Detalles Técnicos
+
+También podrías usar `from starlette.responses import HTMLResponse`.
+
+**FastAPI** proporciona las mismas `starlette.responses` como `fastapi.responses` solo como una conveniencia para ti, el desarrollador. Pero la mayoría de los responses disponibles vienen directamente de Starlette.
+
+///
+
+### Subidas de Múltiples Archivos con Metadatos Adicionales
+
+Y de la misma manera que antes, puedes usar `File()` para establecer parámetros adicionales, incluso para `UploadFile`:
+
+{* ../../docs_src/request_files/tutorial003_an_py39.py hl[11,18:20] *}
+
+## Recapitulación
+
+Usa `File`, `bytes` y `UploadFile` para declarar archivos que se subirán en el request, enviados como form data.
diff --git a/docs/es/docs/tutorial/request-form-models.md b/docs/es/docs/tutorial/request-form-models.md
new file mode 100644
index 000000000..9d5d7495a
--- /dev/null
+++ b/docs/es/docs/tutorial/request-form-models.md
@@ -0,0 +1,78 @@
+# Modelos de Formulario
+
+Puedes usar **modelos de Pydantic** para declarar **campos de formulario** en FastAPI.
+
+/// info | Información
+
+Para usar formularios, primero instala `python-multipart`.
+
+Asegúrate de crear un [entorno virtual](../virtual-environments.md){.internal-link target=_blank}, activarlo, y luego instalarlo, por ejemplo:
+
+```console
+$ pip install python-multipart
+```
+
+///
+
+/// note | Nota
+
+Esto es compatible desde la versión `0.113.0` de FastAPI. 🤓
+
+///
+
+## Modelos de Pydantic para Formularios
+
+Solo necesitas declarar un **modelo de Pydantic** con los campos que quieres recibir como **campos de formulario**, y luego declarar el parámetro como `Form`:
+
+{* ../../docs_src/request_form_models/tutorial001_an_py39.py hl[9:11,15] *}
+
+**FastAPI** **extraerá** los datos de **cada campo** de los **form data** en el request y te dará el modelo de Pydantic que definiste.
+
+## Revisa la Documentación
+
+Puedes verificarlo en la interfaz de documentación en `/docs`:
+
+POST
.
+
+///
+
+/// warning | Advertencia
+
+Puedes declarar múltiples parámetros `Form` en una *path operation*, pero no puedes también declarar campos `Body` que esperas recibir como JSON, ya que el request tendrá el body codificado usando `application/x-www-form-urlencoded` en lugar de `application/json`.
+
+Esto no es una limitación de **FastAPI**, es parte del protocolo HTTP.
+
+///
+
+## Recapitulación
+
+Usa `Form` para declarar parámetros de entrada de datos de formulario.
diff --git a/docs/es/docs/tutorial/response-model.md b/docs/es/docs/tutorial/response-model.md
new file mode 100644
index 000000000..09682f51b
--- /dev/null
+++ b/docs/es/docs/tutorial/response-model.md
@@ -0,0 +1,357 @@
+# Modelo de Response - Tipo de Retorno
+
+Puedes declarar el tipo utilizado para el response anotando el **tipo de retorno** de la *path operation function*.
+
+Puedes utilizar **anotaciones de tipos** de la misma manera que lo harías para datos de entrada en **parámetros** de función, puedes utilizar modelos de Pydantic, listas, diccionarios, valores escalares como enteros, booleanos, etc.
+
+{* ../../docs_src/response_model/tutorial001_01_py310.py hl[16,21] *}
+
+FastAPI usará este tipo de retorno para:
+
+* **Validar** los datos devueltos.
+ * Si los datos son inválidos (por ejemplo, falta un campo), significa que el código de *tu* aplicación está defectuoso, no devolviendo lo que debería, y retornará un error del servidor en lugar de devolver datos incorrectos. De esta manera, tú y tus clientes pueden estar seguros de que recibirán los datos y la forma de los datos esperada.
+* Agregar un **JSON Schema** para el response, en la *path operation* de OpenAPI.
+ * Esto será utilizado por la **documentación automática**.
+ * También será utilizado por herramientas de generación automática de código de cliente.
+
+Pero lo más importante:
+
+* **Limitará y filtrará** los datos de salida a lo que se define en el tipo de retorno.
+ * Esto es particularmente importante para la **seguridad**, veremos más sobre eso a continuación.
+
+## Parámetro `response_model`
+
+Hay algunos casos en los que necesitas o quieres devolver algunos datos que no son exactamente lo que declara el tipo.
+
+Por ejemplo, podrías querer **devolver un diccionario** u objeto de base de datos, pero **declararlo como un modelo de Pydantic**. De esta manera el modelo de Pydantic haría toda la documentación de datos, validación, etc. para el objeto que devolviste (por ejemplo, un diccionario u objeto de base de datos).
+
+Si añadiste la anotación del tipo de retorno, las herramientas y editores se quejarían con un error (correcto) diciéndote que tu función está devolviendo un tipo (por ejemplo, un dict) que es diferente de lo que declaraste (por ejemplo, un modelo de Pydantic).
+
+En esos casos, puedes usar el parámetro del decorador de path operation `response_model` en lugar del tipo de retorno.
+
+Puedes usar el parámetro `response_model` en cualquiera de las *path operations*:
+
+* `@app.get()`
+* `@app.post()`
+* `@app.put()`
+* `@app.delete()`
+* etc.
+
+{* ../../docs_src/response_model/tutorial001_py310.py hl[17,22,24:27] *}
+
+/// note | Nota
+
+Observa que `response_model` es un parámetro del método "decorador" (`get`, `post`, etc). No de tu *path operation function*, como todos los parámetros y el cuerpo.
+
+///
+
+`response_model` recibe el mismo tipo que declararías para un campo de modelo Pydantic, por lo que puede ser un modelo de Pydantic, pero también puede ser, por ejemplo, un `list` de modelos de Pydantic, como `List[Item]`.
+
+FastAPI usará este `response_model` para hacer toda la documentación de datos, validación, etc. y también para **convertir y filtrar los datos de salida** a su declaración de tipo.
+
+/// tip | Consejo
+
+Si tienes chequeos estrictos de tipos en tu editor, mypy, etc., puedes declarar el tipo de retorno de la función como `Any`.
+
+De esa manera le dices al editor que intencionalmente estás devolviendo cualquier cosa. Pero FastAPI todavía hará la documentación de datos, validación, filtrado, etc. con `response_model`.
+
+///
+
+### Prioridad del `response_model`
+
+Si declaras tanto un tipo de retorno como un `response_model`, el `response_model` tomará prioridad y será utilizado por FastAPI.
+
+De esta manera puedes añadir anotaciones de tipos correctas a tus funciones incluso cuando estás devolviendo un tipo diferente al modelo de response, para ser utilizado por el editor y herramientas como mypy. Y aún así puedes hacer que FastAPI realice la validación de datos, documentación, etc. usando el `response_model`.
+
+También puedes usar `response_model=None` para desactivar la creación de un modelo de response para esa *path operation*, podrías necesitar hacerlo si estás añadiendo anotaciones de tipos para cosas que no son campos válidos de Pydantic, verás un ejemplo de eso en una de las secciones a continuación.
+
+## Devolver los mismos datos de entrada
+
+Aquí estamos declarando un modelo `UserIn`, contendrá una contraseña en texto plano:
+
+{* ../../docs_src/response_model/tutorial002_py310.py hl[7,9] *}
+
+/// info | Información
+
+Para usar `EmailStr`, primero instala `email-validator`.
+
+Asegúrate de crear un [entorno virtual](../virtual-environments.md){.internal-link target=_blank}, activarlo, y luego instalarlo, por ejemplo:
+
+```console
+$ pip install email-validator
+```
+
+o con:
+
+```console
+$ pip install "pydantic[email]"
+```
+
+///
+
+Y estamos usando este modelo para declarar nuestra entrada y el mismo modelo para declarar nuestra salida:
+
+{* ../../docs_src/response_model/tutorial002_py310.py hl[16] *}
+
+Ahora, cada vez que un navegador esté creando un usuario con una contraseña, la API devolverá la misma contraseña en el response.
+
+En este caso, podría no ser un problema, porque es el mismo usuario que envía la contraseña.
+
+Pero si usamos el mismo modelo para otra *path operation*, podríamos estar enviando las contraseñas de nuestros usuarios a cada cliente.
+
+/// danger | Peligro
+
+Nunca almacenes la contraseña en texto plano de un usuario ni la envíes en un response como esta, a menos que conozcas todas las advertencias y sepas lo que estás haciendo.
+
+///
+
+## Añadir un modelo de salida
+
+Podemos en cambio crear un modelo de entrada con la contraseña en texto plano y un modelo de salida sin ella:
+
+{* ../../docs_src/response_model/tutorial003_py310.py hl[9,11,16] *}
+
+Aquí, aunque nuestra *path operation function* está devolviendo el mismo usuario de entrada que contiene la contraseña:
+
+{* ../../docs_src/response_model/tutorial003_py310.py hl[24] *}
+
+...hemos declarado el `response_model` para ser nuestro modelo `UserOut`, que no incluye la contraseña:
+
+{* ../../docs_src/response_model/tutorial003_py310.py hl[22] *}
+
+Entonces, **FastAPI** se encargará de filtrar todos los datos que no estén declarados en el modelo de salida (usando Pydantic).
+
+### `response_model` o Tipo de Retorno
+
+En este caso, como los dos modelos son diferentes, si anotáramos el tipo de retorno de la función como `UserOut`, el editor y las herramientas se quejarían de que estamos devolviendo un tipo inválido, ya que son clases diferentes.
+
+Por eso en este ejemplo tenemos que declararlo en el parámetro `response_model`.
+
+...pero sigue leyendo abajo para ver cómo superar eso.
+
+## Tipo de Retorno y Filtrado de Datos
+
+Continuemos con el ejemplo anterior. Queríamos **anotar la función con un tipo**, pero queríamos poder devolver desde la función algo que en realidad incluya **más datos**.
+
+Queremos que FastAPI continúe **filtrando** los datos usando el modelo de response. Para que, incluso cuando la función devuelva más datos, el response solo incluya los campos declarados en el modelo de response.
+
+En el ejemplo anterior, debido a que las clases eran diferentes, tuvimos que usar el parámetro `response_model`. Pero eso también significa que no obtenemos el soporte del editor y las herramientas verificando el tipo de retorno de la función.
+
+Pero en la mayoría de los casos en los que necesitamos hacer algo como esto, queremos que el modelo solo **filtre/elimine** algunos de los datos como en este ejemplo.
+
+Y en esos casos, podemos usar clases y herencia para aprovechar las **anotaciones de tipos** de funciones para obtener mejor soporte en el editor y herramientas, y aún así obtener el **filtrado de datos** de FastAPI.
+
+{* ../../docs_src/response_model/tutorial003_01_py310.py hl[7:10,13:14,18] *}
+
+Con esto, obtenemos soporte de las herramientas, de los editores y mypy ya que este código es correcto en términos de tipos, pero también obtenemos el filtrado de datos de FastAPI.
+
+¿Cómo funciona esto? Vamos a echarle un vistazo. 🤓
+
+### Anotaciones de Tipos y Herramientas
+
+Primero vamos a ver cómo los editores, mypy y otras herramientas verían esto.
+
+`BaseUser` tiene los campos base. Luego `UserIn` hereda de `BaseUser` y añade el campo `password`, por lo que incluirá todos los campos de ambos modelos.
+
+Anotamos el tipo de retorno de la función como `BaseUser`, pero en realidad estamos devolviendo una instancia de `UserIn`.
+
+El editor, mypy y otras herramientas no se quejarán de esto porque, en términos de tipificación, `UserIn` es una subclase de `BaseUser`, lo que significa que es un tipo *válido* cuando se espera algo que es un `BaseUser`.
+
+### Filtrado de Datos en FastAPI
+
+Ahora, para FastAPI, verá el tipo de retorno y se asegurará de que lo que devuelves incluya **solo** los campos que están declarados en el tipo.
+
+FastAPI realiza varias cosas internamente con Pydantic para asegurarse de que esas mismas reglas de herencia de clases no se utilicen para el filtrado de datos devueltos, de lo contrario, podrías terminar devolviendo muchos más datos de los que esperabas.
+
+De esta manera, puedes obtener lo mejor de ambos mundos: anotaciones de tipos con **soporte de herramientas** y **filtrado de datos**.
+
+## Verlo en la documentación
+
+Cuando veas la documentación automática, puedes verificar que el modelo de entrada y el modelo de salida tendrán cada uno su propio JSON Schema:
+
+
-
-
+
+
-
-
+
+
@@ -23,18 +29,18 @@
**مستندات**: https://fastapi.tiangolo.com
-**کد منبع**: https://github.com/tiangolo/fastapi
+**کد منبع**: https://github.com/fastapi/fastapi
---
FastAPI یک وب فریمورک مدرن و سریع (با کارایی بالا) برای ایجاد APIهای متنوع (وب، وبسوکت و غبره) با زبان پایتون نسخه +۳.۶ است. این فریمورک با رعایت کامل راهنمای نوع داده (Type Hint) ایجاد شده است.
ویژگیهای کلیدی این فریمورک عبارتند از:
-* **سرعت**: کارایی بسیار بالا و قابل مقایسه با **NodeJS** و **Go** (با تشکر از Starlette و Pydantic). [یکی از سریعترین فریمورکهای پایتونی موجود](#performance).
+* **سرعت**: کارایی بسیار بالا و قابل مقایسه با **NodeJS** و **Go** (با تشکر از Starlette و Pydantic). [یکی از سریعترین فریمورکهای پایتونی موجود](#_10).
-* **کدنویسی سریع**: افزایش ۲۰۰ تا ۳۰۰ درصدی سرعت توسعه فابلیتهای جدید. *
+* **کدنویسی سریع**: افزایش ۲۰۰ تا ۳۰۰ درصدی سرعت توسعه قابلیتهای جدید. *
* **باگ کمتر**: کاهش ۴۰ درصدی خطاهای انسانی (برنامهنویسی). *
-* **غریزی**: پشتیبانی فوقالعاده در محیطهای توسعه یکپارچه (IDE). تکمیل در همه بخشهای کد. کاهش زمان رفع باگ.
+* **هوشمندانه**: پشتیبانی فوقالعاده در محیطهای توسعه یکپارچه (IDE). تکمیل در همه بخشهای کد. کاهش زمان رفع باگ.
* **آسان**: طراحی شده برای یادگیری و استفاده آسان. کاهش زمان مورد نیاز برای مراجعه به مستندات.
* **کوچک**: کاهش تکرار در کد. چندین قابلیت برای هر پارامتر (منظور پارامترهای ورودی تابع هندلر میباشد، به بخش خلاصه در همین صفحه مراجعه شود). باگ کمتر.
* **استوار**: ایجاد کدی آماده برای استفاده در محیط پروداکشن و تولید خودکار مستندات تعاملی
@@ -60,7 +66,7 @@ FastAPI یک وب فریمورک مدرن و سریع (با کارایی با
async def
... نیز استفاده کنیدuvicorn main:app --reload
...ujson
- برای "تجزیه (parse)" سریعتر JSON .
-* email_validator
- برای اعتبارسنجی آدرسهای ایمیل.
+* email-validator
- برای اعتبارسنجی آدرسهای ایمیل.
استفاده شده توسط Starlette:
* 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` استفاده کنید.
استفاده شده توسط FastAPI / Starlette:
* uvicorn
- برای سرور اجرا کننده برنامه وب.
* orjson
- در صورتی که بخواهید از `ORJSONResponse` استفاده کنید.
+* ujson
- در صورتی که بخواهید از `UJSONResponse` استفاده کنید.
میتوان همه این موارد را با استفاده از دستور `pip install fastapi[all]`. به صورت یکجا نصب کرد.
diff --git a/docs/fa/docs/tutorial/middleware.md b/docs/fa/docs/tutorial/middleware.md
new file mode 100644
index 000000000..75b1c4c5c
--- /dev/null
+++ b/docs/fa/docs/tutorial/middleware.md
@@ -0,0 +1,63 @@
+# میانافزار - middleware
+
+شما میتوانید میانافزارها را در **FastAPI** اضافه کنید.
+
+"میانافزار" یک تابع است که با هر درخواست(request) قبل از پردازش توسط هر path operation (عملیات مسیر) خاص کار میکند. همچنین با هر پاسخ(response) قبل از بازگشت آن نیز کار میکند.
+
+* هر **درخواستی (request)** که به برنامه شما می آید را می گیرد.
+* سپس می تواند کاری برای آن **درخواست** انجام دهید یا هر کد مورد نیازتان را اجرا کنید.
+* سپس **درخواست** را به بخش دیگری از برنامه (توسط یک path operation مشخص) برای پردازش ارسال می کند.
+* سپس **پاسخ** تولید شده توسط برنامه را (توسط یک path operation مشخص) دریافت میکند.
+* می تواند کاری با **پاسخ** انجام دهید یا هر کد مورد نیازتان را اجرا کند.
+* سپس **پاسخ** را برمی گرداند.
+
+/// توجه | جزئیات فنی
+
+در صورت وجود وابستگی هایی با `yield`، کد خروجی **پس از** اجرای میانافزار اجرا خواهد شد.
+
+در صورت وجود هر گونه وظایف پس زمینه (که در ادامه توضیح داده میشوند)، تمام میانافزارها *پس از آن* اجرا خواهند شد.
+
+///
+
+## ساخت یک میان افزار
+
+برای ایجاد یک میانافزار، از دکوریتور `@app.middleware("http")` در بالای یک تابع استفاده میشود.
+
+تابع میان افزار دریافت می کند:
+* `درخواست`
+* تابع `call_next` که `درخواست` را به عنوان پارامتر دریافت می کند
+ * این تابع `درخواست` را به *path operation* مربوطه ارسال می کند.
+ * سپس `پاسخ` تولید شده توسط *path operation* مربوطه را برمیگرداند.
+* شما میتوانید سپس `پاسخ` را تغییر داده و پس از آن را برگردانید.
+
+{* ../../docs_src/middleware/tutorial001.py hl[8:9,11,14] *}
+
+/// نکته | به خاطر داشته باشید که هدرهای اختصاصی سفارشی را می توان با استفاده از پیشوند "X-" اضافه کرد.
+
+اما اگر هدرهای سفارشی دارید که میخواهید مرورگر کاربر بتواند آنها را ببیند، باید آنها را با استفاده از پارامتر `expose_headers` که در مستندات CORS از Starlette توضیح داده شده است، به پیکربندی CORS خود اضافه کنید.
+
+///
+
+/// توجه | جزئیات فنی
+
+شما همچنین میتوانید از `from starlette.requests import Request` استفاده کنید.
+
+**FastAPI** این را به عنوان یک سهولت برای شما به عنوان برنامهنویس فراهم میکند. اما این مستقیما از Starlette به دست میآید.
+
+///
+
+### قبل و بعد از `پاسخ`
+
+شما میتوانید کدی را برای اجرا با `درخواست`، قبل از اینکه هر *path operation* آن را دریافت کند، اضافه کنید.
+
+همچنین پس از تولید `پاسخ`، قبل از بازگشت آن، میتوانید کدی را اضافه کنید.
+
+به عنوان مثال، میتوانید یک هدر سفارشی به نام `X-Process-Time` که شامل زمان پردازش درخواست و تولید پاسخ به صورت ثانیه است، اضافه کنید.
+
+{* ../../docs_src/middleware/tutorial001.py hl[10,12:13] *}
+
+ ## سایر میان افزار
+
+شما میتوانید بعداً در مورد میانافزارهای دیگر در [راهنمای کاربر پیشرفته: میانافزار پیشرفته](../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 000000000..c0827a8b3
--- /dev/null
+++ b/docs/fa/docs/tutorial/security/index.md
@@ -0,0 +1,106 @@
+# امنیت
+
+روشهای مختلفی برای مدیریت امنیت، تأیید هویت و اعتبارسنجی وجود دارد.
+
+عموماً این یک موضوع پیچیده و "سخت" است.
+
+در بسیاری از فریم ورک ها و سیستمها، فقط مدیریت امنیت و تأیید هویت نیاز به تلاش و کد نویسی زیادی دارد (در بسیاری از موارد میتواند 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/fa/mkdocs.yml b/docs/fa/mkdocs.yml
index 5bb1a2ff5..de18856f4 100644
--- a/docs/fa/mkdocs.yml
+++ b/docs/fa/mkdocs.yml
@@ -1,157 +1 @@
-site_name: FastAPI
-site_description: FastAPI framework, high performance, easy to learn, fast to code, ready for production
-site_url: https://fastapi.tiangolo.com/fa/
-theme:
- name: material
- custom_dir: overrides
- palette:
- - media: '(prefers-color-scheme: light)'
- scheme: default
- primary: teal
- accent: amber
- toggle:
- icon: material/lightbulb
- name: Switch to light mode
- - media: '(prefers-color-scheme: dark)'
- scheme: slate
- primary: teal
- accent: amber
- toggle:
- icon: material/lightbulb-outline
- name: Switch to dark mode
- features:
- - search.suggest
- - search.highlight
- - content.tabs.link
- icon:
- repo: fontawesome/brands/github-alt
- logo: https://fastapi.tiangolo.com/img/icon-white.svg
- favicon: https://fastapi.tiangolo.com/img/favicon.png
- language: fa
-repo_name: tiangolo/fastapi
-repo_url: https://github.com/tiangolo/fastapi
-edit_uri: ''
-plugins:
-- search
-- markdownextradata:
- data: data
-nav:
-- FastAPI: index.md
-- Languages:
- - en: /
- - az: /az/
- - cs: /cs/
- - de: /de/
- - em: /em/
- - es: /es/
- - fa: /fa/
- - fr: /fr/
- - he: /he/
- - hy: /hy/
- - id: /id/
- - it: /it/
- - ja: /ja/
- - ko: /ko/
- - nl: /nl/
- - pl: /pl/
- - pt: /pt/
- - ru: /ru/
- - sq: /sq/
- - sv: /sv/
- - ta: /ta/
- - tr: /tr/
- - uk: /uk/
- - zh: /zh/
-markdown_extensions:
-- toc:
- permalink: true
-- markdown.extensions.codehilite:
- guess_lang: false
-- mdx_include:
- base_path: docs
-- admonition
-- codehilite
-- extra
-- pymdownx.superfences:
- custom_fences:
- - name: mermaid
- class: mermaid
- format: !!python/name:pymdownx.superfences.fence_code_format ''
-- pymdownx.tabbed:
- alternate_style: true
-- attr_list
-- md_in_html
-extra:
- analytics:
- provider: google
- property: G-YNEVN69SC3
- social:
- - icon: fontawesome/brands/github-alt
- link: https://github.com/tiangolo/fastapi
- - icon: fontawesome/brands/discord
- link: https://discord.gg/VQjSZaeJmf
- - icon: fontawesome/brands/twitter
- link: https://twitter.com/fastapi
- - icon: fontawesome/brands/linkedin
- link: https://www.linkedin.com/in/tiangolo
- - icon: fontawesome/brands/dev
- link: https://dev.to/tiangolo
- - icon: fontawesome/brands/medium
- link: https://medium.com/@tiangolo
- - icon: fontawesome/solid/globe
- link: https://tiangolo.com
- alternate:
- - link: /
- name: en - English
- - link: /az/
- name: az
- - link: /cs/
- name: cs
- - link: /de/
- name: de
- - link: /em/
- name: 😉
- - link: /es/
- name: es - español
- - link: /fa/
- name: fa
- - link: /fr/
- name: fr - français
- - link: /he/
- name: he
- - link: /hy/
- name: hy
- - link: /id/
- name: id
- - link: /it/
- name: it - italiano
- - link: /ja/
- name: ja - 日本語
- - link: /ko/
- name: ko - 한국어
- - link: /nl/
- name: nl
- - link: /pl/
- name: pl
- - link: /pt/
- name: pt - português
- - link: /ru/
- name: ru - русский язык
- - link: /sq/
- name: sq - shqip
- - link: /sv/
- name: sv - svenska
- - link: /ta/
- name: ta - தமிழ்
- - link: /tr/
- name: tr - Türkçe
- - link: /uk/
- name: uk - українська мова
- - link: /zh/
- name: zh - 汉语
-extra_css:
-- https://fastapi.tiangolo.com/css/termynal.css
-- https://fastapi.tiangolo.com/css/custom.css
-extra_javascript:
-- https://fastapi.tiangolo.com/js/termynal.js
-- https://fastapi.tiangolo.com/js/custom.js
+INHERIT: ../en/mkdocs.yml
diff --git a/docs/fa/overrides/.gitignore b/docs/fa/overrides/.gitignore
deleted file mode 100644
index e69de29bb..000000000
diff --git a/docs/fr/docs/advanced/additional-responses.md b/docs/fr/docs/advanced/additional-responses.md
index 35b57594d..38527aad3 100644
--- a/docs/fr/docs/advanced/additional-responses.md
+++ b/docs/fr/docs/advanced/additional-responses.md
@@ -1,9 +1,12 @@
# Réponses supplémentaires dans OpenAPI
-!!! Attention
- Ceci concerne un sujet plutôt avancé.
+/// warning | Attention
- Si vous débutez avec **FastAPI**, vous n'en aurez peut-être pas besoin.
+Ceci concerne un sujet plutôt avancé.
+
+Si vous débutez avec **FastAPI**, vous n'en aurez peut-être pas besoin.
+
+///
Vous pouvez déclarer des réponses supplémentaires, avec des codes HTTP, des types de médias, des descriptions, etc.
@@ -23,24 +26,28 @@ Chacun de ces `dict` de réponse peut avoir une clé `model`, contenant un modè
Par exemple, pour déclarer une autre réponse avec un code HTTP `404` et un modèle Pydantic `Message`, vous pouvez écrire :
-```Python hl_lines="18 22"
-{!../../../docs_src/additional_responses/tutorial001.py!}
-```
+{* ../../docs_src/additional_responses/tutorial001.py hl[18,22] *}
+
+/// note | Remarque
+
+Gardez à l'esprit que vous devez renvoyer directement `JSONResponse`.
+
+///
+
+/// info
-!!! Remarque
- Gardez à l'esprit que vous devez renvoyer directement `JSONResponse`.
+La clé `model` ne fait pas partie d'OpenAPI.
-!!! Info
- La clé `model` ne fait pas partie d'OpenAPI.
+**FastAPI** prendra le modèle Pydantic à partir de là, générera le `JSON Schema` et le placera au bon endroit.
- **FastAPI** prendra le modèle Pydantic à partir de là, générera le `JSON Schema` et le placera au bon endroit.
+Le bon endroit est :
- Le bon endroit est :
+* Dans la clé `content`, qui a pour valeur un autre objet JSON (`dict`) qui contient :
+ * Une clé avec le type de support, par ex. `application/json`, qui contient comme valeur un autre objet JSON, qui contient :
+ * Une clé `schema`, qui a pour valeur le schéma JSON du modèle, voici le bon endroit.
+ * **FastAPI** ajoute ici une référence aux schémas JSON globaux à un autre endroit de votre OpenAPI au lieu de l'inclure directement. De cette façon, d'autres applications et clients peuvent utiliser ces schémas JSON directement, fournir de meilleurs outils de génération de code, etc.
- * Dans la clé `content`, qui a pour valeur un autre objet JSON (`dict`) qui contient :
- * Une clé avec le type de support, par ex. `application/json`, qui contient comme valeur un autre objet JSON, qui contient :
- * Une clé `schema`, qui a pour valeur le schéma JSON du modèle, voici le bon endroit.
- * **FastAPI** ajoute ici une référence aux schémas JSON globaux à un autre endroit de votre OpenAPI au lieu de l'inclure directement. De cette façon, d'autres applications et clients peuvent utiliser ces schémas JSON directement, fournir de meilleurs outils de génération de code, etc.
+///
Les réponses générées au format OpenAPI pour cette *opération de chemin* seront :
@@ -168,17 +175,21 @@ Vous pouvez utiliser ce même paramètre `responses` pour ajouter différents ty
Par exemple, vous pouvez ajouter un type de média supplémentaire `image/png`, en déclarant que votre *opération de chemin* peut renvoyer un objet JSON (avec le type de média `application/json`) ou une image PNG :
-```Python hl_lines="19-24 28"
-{!../../../docs_src/additional_responses/tutorial002.py!}
-```
+{* ../../docs_src/additional_responses/tutorial002.py hl[19:24,28] *}
+
+/// note | Remarque
+
+Notez que vous devez retourner l'image en utilisant directement un `FileResponse`.
+
+///
-!!! Remarque
- Notez que vous devez retourner l'image en utilisant directement un `FileResponse`.
+/// info
-!!! Info
- À moins que vous ne spécifiiez explicitement un type de média différent dans votre paramètre `responses`, FastAPI supposera que la réponse a le même type de média que la classe de réponse principale (par défaut `application/json`).
+À moins que vous ne spécifiiez explicitement un type de média différent dans votre paramètre `responses`, FastAPI supposera que la réponse a le même type de média que la classe de réponse principale (par défaut `application/json`).
- Mais si vous avez spécifié une classe de réponse personnalisée avec `None` comme type de média, FastAPI utilisera `application/json` pour toute réponse supplémentaire associée à un modèle.
+Mais si vous avez spécifié une classe de réponse personnalisée avec `None` comme type de média, FastAPI utilisera `application/json` pour toute réponse supplémentaire associée à un modèle.
+
+///
## Combinaison d'informations
@@ -192,9 +203,7 @@ Par exemple, vous pouvez déclarer une réponse avec un code HTTP `404` qui util
Et une réponse avec un code HTTP `200` qui utilise votre `response_model`, mais inclut un `example` personnalisé :
-```Python hl_lines="20-31"
-{!../../../docs_src/additional_responses/tutorial003.py!}
-```
+{* ../../docs_src/additional_responses/tutorial003.py hl[20:31] *}
Tout sera combiné et inclus dans votre OpenAPI, et affiché dans la documentation de l'API :
@@ -206,7 +215,7 @@ Vous voulez peut-être avoir des réponses prédéfinies qui s'appliquent à de
Dans ces cas, vous pouvez utiliser la technique Python "d'affection par décomposition" (appelé _unpacking_ en anglais) d'un `dict` avec `**dict_to_unpack` :
-``` Python
+```Python
old_dict = {
"old key": "old value",
"second old key": "second old value",
@@ -216,7 +225,7 @@ new_dict = {**old_dict, "new key": "new value"}
Ici, `new_dict` contiendra toutes les paires clé-valeur de `old_dict` plus la nouvelle paire clé-valeur :
-``` Python
+```Python
{
"old key": "old value",
"second old key": "second old value",
@@ -228,9 +237,7 @@ Vous pouvez utiliser cette technique pour réutiliser certaines réponses préd
Par exemple:
-```Python hl_lines="13-17 26"
-{!../../../docs_src/additional_responses/tutorial004.py!}
-```
+{* ../../docs_src/additional_responses/tutorial004.py hl[13:17,26] *}
## Plus d'informations sur les réponses OpenAPI
diff --git a/docs/fr/docs/advanced/additional-status-codes.md b/docs/fr/docs/advanced/additional-status-codes.md
index e7b003707..dde6b9a63 100644
--- a/docs/fr/docs/advanced/additional-status-codes.md
+++ b/docs/fr/docs/advanced/additional-status-codes.md
@@ -14,21 +14,25 @@ Mais vous voulez aussi qu'il accepte de nouveaux éléments. Et lorsque les él
Pour y parvenir, importez `JSONResponse` et renvoyez-y directement votre contenu, en définissant le `status_code` que vous souhaitez :
-```Python hl_lines="4 25"
-{!../../../docs_src/additional_status_codes/tutorial001.py!}
-```
+{* ../../docs_src/additional_status_codes/tutorial001.py hl[4,25] *}
-!!! Attention
- Lorsque vous renvoyez une `Response` directement, comme dans l'exemple ci-dessus, elle sera renvoyée directement.
+/// warning | Attention
- Elle ne sera pas sérialisée avec un modèle.
+Lorsque vous renvoyez une `Response` directement, comme dans l'exemple ci-dessus, elle sera renvoyée directement.
- Assurez-vous qu'il contient les données souhaitées et que les valeurs soient dans un format JSON valides (si vous utilisez une `JSONResponse`).
+Elle ne sera pas sérialisée avec un modèle.
-!!! note "Détails techniques"
- Vous pouvez également utiliser `from starlette.responses import JSONResponse`.
+Assurez-vous qu'il contient les données souhaitées et que les valeurs soient dans un format JSON valides (si vous utilisez une `JSONResponse`).
- Pour plus de commodités, **FastAPI** fournit les objets `starlette.responses` sous forme d'un alias accessible par `fastapi.responses`. Mais la plupart des réponses disponibles proviennent directement de Starlette. Il en est de même avec l'objet `statut`.
+///
+
+/// note | Détails techniques
+
+Vous pouvez également utiliser `from starlette.responses import JSONResponse`.
+
+Pour plus de commodités, **FastAPI** fournit les objets `starlette.responses` sous forme d'un alias accessible par `fastapi.responses`. Mais la plupart des réponses disponibles proviennent directement de Starlette. Il en est de même avec l'objet `statut`.
+
+///
## Documents OpenAPI et API
diff --git a/docs/fr/docs/advanced/index.md b/docs/fr/docs/advanced/index.md
index 41737889a..d9d8ad8e6 100644
--- a/docs/fr/docs/advanced/index.md
+++ b/docs/fr/docs/advanced/index.md
@@ -1,19 +1,22 @@
-# Guide de l'utilisateur avancé - Introduction
+# Guide de l'utilisateur avancé
## Caractéristiques supplémentaires
-Le [Tutoriel - Guide de l'utilisateur](../tutorial/){.internal-link target=_blank} devrait suffire à vous faire découvrir toutes les fonctionnalités principales de **FastAPI**.
+Le [Tutoriel - Guide de l'utilisateur](../tutorial/index.md){.internal-link target=_blank} devrait suffire à vous faire découvrir toutes les fonctionnalités principales de **FastAPI**.
Dans les sections suivantes, vous verrez des options, configurations et fonctionnalités supplémentaires.
-!!! Note
- Les sections de ce chapitre ne sont **pas nécessairement "avancées"**.
+/// note | Remarque
- Et il est possible que pour votre cas d'utilisation, la solution se trouve dans l'un d'entre eux.
+Les sections de ce chapitre ne sont **pas nécessairement "avancées"**.
+
+Et il est possible que pour votre cas d'utilisation, la solution se trouve dans l'un d'entre eux.
+
+///
## Lisez d'abord le didacticiel
-Vous pouvez utiliser la plupart des fonctionnalités de **FastAPI** grâce aux connaissances du [Tutoriel - Guide de l'utilisateur](../tutorial/){.internal-link target=_blank}.
+Vous pouvez utiliser la plupart des fonctionnalités de **FastAPI** grâce aux connaissances du [Tutoriel - Guide de l'utilisateur](../tutorial/index.md){.internal-link target=_blank}.
Et les sections suivantes supposent que vous l'avez lu et que vous en connaissez les idées principales.
diff --git a/docs/fr/docs/advanced/path-operation-advanced-configuration.md b/docs/fr/docs/advanced/path-operation-advanced-configuration.md
index ace9f19f9..7daf0fc65 100644
--- a/docs/fr/docs/advanced/path-operation-advanced-configuration.md
+++ b/docs/fr/docs/advanced/path-operation-advanced-configuration.md
@@ -2,16 +2,17 @@
## ID d'opération OpenAPI
-!!! Attention
- Si vous n'êtes pas un "expert" en OpenAPI, vous n'en avez probablement pas besoin.
+/// warning | Attention
+
+Si vous n'êtes pas un "expert" en OpenAPI, vous n'en avez probablement pas besoin.
+
+///
Dans OpenAPI, les chemins sont des ressources, tels que /users/ ou /items/, exposées par votre API, et les opérations sont les méthodes HTTP utilisées pour manipuler ces chemins, telles que GET, POST ou DELETE. Les operationId sont des chaînes uniques facultatives utilisées pour identifier une opération d'un chemin. Vous pouvez définir l'OpenAPI `operationId` à utiliser dans votre *opération de chemin* avec le paramètre `operation_id`.
Vous devez vous assurer qu'il est unique pour chaque opération.
-```Python hl_lines="6"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial001.py!}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial001.py hl[6] *}
### Utilisation du nom *path operation function* comme operationId
@@ -19,25 +20,27 @@ Si vous souhaitez utiliser les noms de fonction de vos API comme `operationId`,
Vous devriez le faire après avoir ajouté toutes vos *paramètres de chemin*.
-```Python hl_lines="2 12-21 24"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial002.py hl[2,12:21,24] *}
+
+/// tip | Astuce
-!!! Astuce
- Si vous appelez manuellement `app.openapi()`, vous devez mettre à jour les `operationId` avant.
+Si vous appelez manuellement `app.openapi()`, vous devez mettre à jour les `operationId` avant.
-!!! Attention
- Pour faire cela, vous devez vous assurer que chacun de vos *chemin* ait un nom unique.
+///
- Même s'ils se trouvent dans des modules différents (fichiers Python).
+/// warning | Attention
+
+Pour faire cela, vous devez vous assurer que chacun de vos *chemin* ait un nom unique.
+
+Même s'ils se trouvent dans des modules différents (fichiers Python).
+
+///
## Exclusion d'OpenAPI
Pour exclure un *chemin* du schéma OpenAPI généré (et donc des systèmes de documentation automatiques), utilisez le paramètre `include_in_schema` et assignez-lui la valeur `False` :
-```Python hl_lines="6"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial003.py!}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial003.py hl[6] *}
## Description avancée de docstring
@@ -47,9 +50,7 @@ L'ajout d'un `\f` (un caractère d'échappement "form feed") va permettre à **F
Il n'apparaîtra pas dans la documentation, mais d'autres outils (tel que Sphinx) pourront utiliser le reste.
-```Python hl_lines="19-29"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial004.py!}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial004.py hl[19:29] *}
## Réponses supplémentaires
@@ -59,14 +60,17 @@ Cela définit les métadonnées sur la réponse principale d'une *opération de
Vous pouvez également déclarer des réponses supplémentaires avec leurs modèles, codes de statut, etc.
-Il y a un chapitre entier ici dans la documentation à ce sujet, vous pouvez le lire sur [Réponses supplémentaires dans OpenAPI](./additional-responses.md){.internal-link target=_blank}.
+Il y a un chapitre entier ici dans la documentation à ce sujet, vous pouvez le lire sur [Réponses supplémentaires dans OpenAPI](additional-responses.md){.internal-link target=_blank}.
## OpenAPI supplémentaire
Lorsque vous déclarez un *chemin* dans votre application, **FastAPI** génère automatiquement les métadonnées concernant ce *chemin* à inclure dans le schéma OpenAPI.
-!!! note "Détails techniques"
- La spécification OpenAPI appelle ces métaonnées des Objets d'opération.
+/// note | Détails techniques
+
+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.
@@ -74,8 +78,11 @@ Il inclut les `tags`, `parameters`, `requestBody`, `responses`, etc.
Ce schéma OpenAPI spécifique aux *operations* est normalement généré automatiquement par **FastAPI**, mais vous pouvez également l'étendre.
-!!! Astuce
- Si vous avez seulement besoin de déclarer des réponses supplémentaires, un moyen plus pratique de le faire est d'utiliser les [réponses supplémentaires dans OpenAPI](./additional-responses.md){.internal-link target=_blank}.
+/// tip | Astuce
+
+Si vous avez seulement besoin de déclarer des réponses supplémentaires, un moyen plus pratique de le faire est d'utiliser les [réponses supplémentaires dans OpenAPI](additional-responses.md){.internal-link target=_blank}.
+
+///
Vous pouvez étendre le schéma OpenAPI pour une *opération de chemin* en utilisant le paramètre `openapi_extra`.
@@ -83,9 +90,7 @@ Vous pouvez étendre le schéma OpenAPI pour une *opération de chemin* en utili
Cet `openapi_extra` peut être utile, par exemple, pour déclarer [OpenAPI Extensions](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions) :
-```Python hl_lines="6"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial005.py!}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial005.py hl[6] *}
Si vous ouvrez la documentation automatique de l'API, votre extension apparaîtra au bas du *chemin* spécifique.
@@ -132,9 +137,7 @@ Par exemple, vous pouvez décider de lire et de valider la requête avec votre p
Vous pouvez le faire avec `openapi_extra` :
-```Python hl_lines="20-37 39-40"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial006.py !}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial006.py hl[20:37,39:40] *}
Dans cet exemple, nous n'avons déclaré aucun modèle Pydantic. En fait, le corps de la requête n'est même pas parsé en tant que JSON, il est lu directement en tant que `bytes`, et la fonction `magic_data_reader()` serait chargé de l'analyser d'une manière ou d'une autre.
@@ -148,9 +151,7 @@ Et vous pouvez le faire même si le type de données dans la requête n'est pas
Dans cet exemple, nous n'utilisons pas les fonctionnalités de FastAPI pour extraire le schéma JSON des modèles Pydantic ni la validation automatique pour JSON. En fait, nous déclarons le type de contenu de la requête en tant que YAML, et non JSON :
-```Python hl_lines="17-22 24"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial007.py!}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[17:22,24] *}
Néanmoins, bien que nous n'utilisions pas la fonctionnalité par défaut, nous utilisons toujours un modèle Pydantic pour générer manuellement le schéma JSON pour les données que nous souhaitons recevoir en YAML.
@@ -158,11 +159,12 @@ Ensuite, nous utilisons directement la requête et extrayons son contenu en tant
Et nous analysons directement ce contenu YAML, puis nous utilisons à nouveau le même modèle Pydantic pour valider le contenu YAML :
-```Python hl_lines="26-33"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial007.py!}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[26:33] *}
+
+/// tip | Astuce
+
+Ici, nous réutilisons le même modèle Pydantic.
-!!! Astuce
- Ici, nous réutilisons le même modèle Pydantic.
+Mais nous aurions pu tout aussi bien pu le valider d'une autre manière.
- Mais nous aurions pu tout aussi bien pu le valider d'une autre manière.
+///
diff --git a/docs/fr/docs/advanced/response-directly.md b/docs/fr/docs/advanced/response-directly.md
index 1c923fb82..4ff883c77 100644
--- a/docs/fr/docs/advanced/response-directly.md
+++ b/docs/fr/docs/advanced/response-directly.md
@@ -14,8 +14,11 @@ Cela peut être utile, par exemple, pour retourner des en-têtes personnalisés
En fait, vous pouvez retourner n'importe quelle `Response` ou n'importe quelle sous-classe de celle-ci.
-!!! Note
- `JSONResponse` est elle-même une sous-classe de `Response`.
+/// note | Remarque
+
+`JSONResponse` est elle-même une sous-classe de `Response`.
+
+///
Et quand vous retournez une `Response`, **FastAPI** la transmet directement.
@@ -31,14 +34,15 @@ Par exemple, vous ne pouvez pas mettre un modèle Pydantic dans une `JSONRespons
Pour ces cas, vous pouvez spécifier un appel à `jsonable_encoder` pour convertir vos données avant de les passer à une réponse :
-```Python hl_lines="6-7 21-22"
-{!../../../docs_src/response_directly/tutorial001.py!}
-```
+{* ../../docs_src/response_directly/tutorial001.py hl[6:7,21:22] *}
+
+/// note | Détails techniques
+
+Vous pouvez aussi utiliser `from starlette.responses import JSONResponse`.
-!!! note "Détails techniques"
- Vous pouvez aussi utiliser `from starlette.responses import JSONResponse`.
+**FastAPI** fournit le même objet `starlette.responses` que `fastapi.responses` juste par commodité pour le développeur. Mais la plupart des réponses disponibles proviennent directement de Starlette.
- **FastAPI** fournit le même objet `starlette.responses` que `fastapi.responses` juste par commodité pour le développeur. Mais la plupart des réponses disponibles proviennent directement de Starlette.
+///
## Renvoyer une `Response` personnalisée
@@ -50,9 +54,7 @@ Disons que vous voulez retourner une réponse Flask
Flask est un "micro-framework", il ne comprend pas d'intégrations de bases de données ni beaucoup de choses qui sont fournies par défaut dans Django.
@@ -59,11 +65,14 @@ qui est nécessaire, était une caractéristique clé que je voulais conserver.
Compte tenu de la simplicité de Flask, il semblait bien adapté à la création d'API. La prochaine chose à trouver était un "Django REST Framework" pour Flask.
-!!! check "A inspiré **FastAPI** à"
+/// check | A inspiré **FastAPI** à
+
Être un micro-framework. Il est donc facile de combiner les outils et les pièces nécessaires.
Proposer un système de routage simple et facile à utiliser.
+///
+
### Requests
**FastAPI** n'est pas réellement une alternative à **Requests**. Leur cadre est très différent.
@@ -98,9 +107,13 @@ def read_url():
Notez les similitudes entre `requests.get(...)` et `@app.get(...)`.
-!!! check "A inspiré **FastAPI** à"
-_ Avoir une API simple et intuitive.
-_ Utiliser les noms de méthodes HTTP (opérations) directement, de manière simple et intuitive. \* Avoir des valeurs par défaut raisonnables, mais des personnalisations puissantes.
+/// check | A inspiré **FastAPI** à
+
+Avoir une API simple et intuitive.
+
+Utiliser les noms de méthodes HTTP (opérations) directement, de manière simple et intuitive. \* Avoir des valeurs par défaut raisonnables, mais des personnalisations puissantes.
+
+///
### Swagger / OpenAPI
@@ -115,15 +128,18 @@ Swagger pour une API permettrait d'utiliser cette interface utilisateur web auto
C'est pourquoi, lorsqu'on parle de la version 2.0, il est courant de dire "Swagger", et pour la version 3+ "OpenAPI".
-!!! check "A inspiré **FastAPI** à"
+/// check | A inspiré **FastAPI** à
+
Adopter et utiliser une norme ouverte pour les spécifications des API, au lieu d'un schéma personnalisé.
- Intégrer des outils d'interface utilisateur basés sur des normes :
+Intégrer des outils d'interface utilisateur basés sur des normes :
- * Swagger UI
- * ReDoc
+* Swagger UI
+* ReDoc
- Ces deux-là ont été choisis parce qu'ils sont populaires et stables, mais en faisant une recherche rapide, vous pourriez trouver des dizaines d'alternatives supplémentaires pour OpenAPI (que vous pouvez utiliser avec **FastAPI**).
+Ces deux-là ont été choisis parce qu'ils sont populaires et stables, mais en faisant une recherche rapide, vous pourriez trouver des dizaines d'alternatives supplémentaires pour OpenAPI (que vous pouvez utiliser avec **FastAPI**).
+
+///
### Frameworks REST pour Flask
@@ -150,9 +166,12 @@ Ces fonctionnalités sont ce pourquoi Marshmallow a été construit. C'est une e
Mais elle a été créée avant que les type hints n'existent en Python. Ainsi, pour définir chaque schéma, vous devez utiliser des utilitaires et des classes spécifiques fournies par Marshmallow.
-!!! check "A inspiré **FastAPI** à"
+/// check | A inspiré **FastAPI** à
+
Utilisez du code pour définir des "schémas" qui fournissent automatiquement les types de données et la validation.
+///
+
### Webargs
Une autre grande fonctionnalité requise par les API est le APISpec
Marshmallow et Webargs fournissent la validation, l'analyse et la sérialisation en tant que plug-ins.
@@ -188,12 +213,18 @@ Mais alors, nous avons à nouveau le problème d'avoir une micro-syntaxe, dans u
L'éditeur ne peut guère aider en la matière. Et si nous modifions les paramètres ou les schémas Marshmallow et que nous oublions de modifier également cette docstring YAML, le schéma généré deviendrait obsolète.
-!!! info
+/// info
+
APISpec a été créé par les développeurs de Marshmallow.
-!!! check "A inspiré **FastAPI** à"
+///
+
+/// check | A inspiré **FastAPI** à
+
Supporter la norme ouverte pour les API, OpenAPI.
+///
+
### Flask-apispec
C'est un plug-in pour Flask, qui relie Webargs, Marshmallow et APISpec.
@@ -215,12 +246,18 @@ j'ai (ainsi que plusieurs équipes externes) utilisées jusqu'à présent :
Ces mêmes générateurs full-stack ont servi de base aux [Générateurs de projets pour **FastAPI**](project-generation.md){.internal-link target=\_blank}.
-!!! info
+/// info
+
Flask-apispec a été créé par les développeurs de Marshmallow.
-!!! check "A inspiré **FastAPI** à"
+///
+
+/// check | A inspiré **FastAPI** à
+
Générer le schéma OpenAPI automatiquement, à partir du même code qui définit la sérialisation et la validation.
+///
+
### NestJS (et Angular)
Ce n'est même pas du Python, NestJS est un framework JavaScript (TypeScript) NodeJS inspiré d'Angular.
@@ -236,24 +273,33 @@ Mais comme les données TypeScript ne sont pas préservées après la compilatio
Il ne peut pas très bien gérer les modèles imbriqués. Ainsi, si le corps JSON de la requête est un objet JSON comportant des champs internes qui sont à leur tour des objets JSON imbriqués, il ne peut pas être correctement documenté et validé.
-!!! check "A inspiré **FastAPI** à"
+/// check | A inspiré **FastAPI** à
+
Utiliser les types Python pour bénéficier d'un excellent support de l'éditeur.
- Disposer d'un puissant système d'injection de dépendances. Trouver un moyen de minimiser la répétition du code.
+Disposer d'un puissant système d'injection de dépendances. Trouver un moyen de minimiser la répétition du code.
+
+///
### Sanic
C'était l'un des premiers frameworks Python extrêmement rapides basés sur `asyncio`. Il a été conçu pour être très similaire à Flask.
-!!! note "Détails techniques"
+/// note | Détails techniques
+
Il utilisait `uvloop` au lieu du système par défaut de Python `asyncio`. C'est ce qui l'a rendu si rapide.
- Il a clairement inspiré Uvicorn et Starlette, qui sont actuellement plus rapides que Sanic dans les benchmarks.
+Il a clairement inspiré Uvicorn et Starlette, qui sont actuellement plus rapides que Sanic dans les benchmarks.
+
+///
+
+/// check | A inspiré **FastAPI** à
-!!! check "A inspiré **FastAPI** à"
Trouvez un moyen d'avoir une performance folle.
- C'est pourquoi **FastAPI** est basé sur Starlette, car il s'agit du framework le plus rapide disponible (testé par des benchmarks tiers).
+C'est pourquoi **FastAPI** est basé sur Starlette, car il s'agit du framework le plus rapide disponible (testé par des benchmarks tiers).
+
+///
### Falcon
@@ -267,12 +313,15 @@ pas possible de déclarer des paramètres de requête et des corps avec des indi
Ainsi, la validation, la sérialisation et la documentation des données doivent être effectuées dans le code, et non pas automatiquement. Ou bien elles doivent être implémentées comme un framework au-dessus de Falcon, comme Hug. Cette même distinction se retrouve dans d'autres frameworks qui s'inspirent de la conception de Falcon, qui consiste à avoir un objet de requête et un objet de réponse comme paramètres.
-!!! check "A inspiré **FastAPI** à"
+/// check | A inspiré **FastAPI** à
+
Trouver des moyens d'obtenir de bonnes performances.
- Avec Hug (puisque Hug est basé sur Falcon), **FastAPI** a inspiré la déclaration d'un paramètre `response` dans les fonctions.
+Avec Hug (puisque Hug est basé sur Falcon), **FastAPI** a inspiré la déclaration d'un paramètre `response` dans les fonctions.
+
+Bien que dans FastAPI, il est facultatif, et est utilisé principalement pour définir les en-têtes, les cookies, et les codes de statut alternatifs.
- Bien que dans FastAPI, il est facultatif, et est utilisé principalement pour définir les en-têtes, les cookies, et les codes de statut alternatifs.
+///
### Molten
@@ -294,12 +343,15 @@ d'utiliser des décorateurs qui peuvent être placés juste au-dessus de la fonc
méthode est plus proche de celle de Django que de celle de Flask (et Starlette). Il sépare dans le code des choses
qui sont relativement fortement couplées.
-!!! check "A inspiré **FastAPI** à"
+/// check | A inspiré **FastAPI** à
+
Définir des validations supplémentaires pour les types de données utilisant la valeur "par défaut" des attributs du modèle. Ceci améliore le support de l'éditeur, et n'était pas disponible dans Pydantic auparavant.
- Cela a en fait inspiré la mise à jour de certaines parties de Pydantic, afin de supporter le même style de déclaration de validation (toute cette fonctionnalité est maintenant déjà disponible dans Pydantic).
+Cela a en fait inspiré la mise à jour de certaines parties de Pydantic, afin de supporter le même style de déclaration de validation (toute cette fonctionnalité est maintenant déjà disponible dans Pydantic).
+
+///
-### Hug
+### Hug
Hug a été l'un des premiers frameworks à implémenter la déclaration des types de paramètres d'API en utilisant les type hints Python. C'était une excellente idée qui a inspiré d'autres outils à faire de même.
@@ -314,16 +366,22 @@ API et des CLI.
Comme il est basé sur l'ancienne norme pour les frameworks web Python synchrones (WSGI), il ne peut pas gérer les Websockets et autres, bien qu'il soit également très performant.
-!!! info
+/// info
+
Hug a été créé par Timothy Crosley, le créateur de `isort`, un excellent outil pour trier automatiquement les imports dans les fichiers Python.
-!!! check "A inspiré **FastAPI** à"
+///
+
+/// check | A inspiré **FastAPI** à
+
Hug a inspiré certaines parties d'APIStar, et était l'un des outils que je trouvais les plus prometteurs, à côté d'APIStar.
- Hug a contribué à inspirer **FastAPI** pour utiliser les type hints Python
- pour déclarer les paramètres, et pour générer automatiquement un schéma définissant l'API.
+Hug a contribué à inspirer **FastAPI** pour utiliser les type hints Python
+pour déclarer les paramètres, et pour générer automatiquement un schéma définissant l'API.
+
+Hug a inspiré **FastAPI** pour déclarer un paramètre `response` dans les fonctions pour définir les en-têtes et les cookies.
- Hug a inspiré **FastAPI** pour déclarer un paramètre `response` dans les fonctions pour définir les en-têtes et les cookies.
+///
### APIStar (<= 0.5)
@@ -351,27 +409,33 @@ Il ne s'agissait plus d'un framework web API, le créateur devant se concentrer
Maintenant, APIStar est un ensemble d'outils pour valider les spécifications OpenAPI, et non un framework web.
-!!! info
+/// info
+
APIStar a été créé par Tom Christie. Le même gars qui a créé :
- * Django REST Framework
- * Starlette (sur lequel **FastAPI** est basé)
- * Uvicorn (utilisé par Starlette et **FastAPI**)
+* Django REST Framework
+* Starlette (sur lequel **FastAPI** est basé)
+* Uvicorn (utilisé par Starlette et **FastAPI**)
+
+///
+
+/// check | A inspiré **FastAPI** à
-!!! check "A inspiré **FastAPI** à"
Exister.
- L'idée de déclarer plusieurs choses (validation des données, sérialisation et documentation) avec les mêmes types Python, tout en offrant un excellent support pour les éditeurs, était pour moi une idée brillante.
+L'idée de déclarer plusieurs choses (validation des données, sérialisation et documentation) avec les mêmes types Python, tout en offrant un excellent support pour les éditeurs, était pour moi une idée brillante.
- Et après avoir longtemps cherché un framework similaire et testé de nombreuses alternatives, APIStar était la meilleure option disponible.
+Et après avoir longtemps cherché un framework similaire et testé de nombreuses alternatives, APIStar était la meilleure option disponible.
- Puis APIStar a cessé d'exister en tant que serveur et Starlette a été créé, et a constitué une meilleure base pour un tel système. Ce fut l'inspiration finale pour construire **FastAPI**.
+Puis APIStar a cessé d'exister en tant que serveur et Starlette a été créé, et a constitué une meilleure base pour un tel système. Ce fut l'inspiration finale pour construire **FastAPI**.
- Je considère **FastAPI** comme un "successeur spirituel" d'APIStar, tout en améliorant et en augmentant les fonctionnalités, le système de typage et d'autres parties, sur la base des enseignements tirés de tous ces outils précédents.
+Je considère **FastAPI** comme un "successeur spirituel" d'APIStar, tout en améliorant et en augmentant les fonctionnalités, le système de typage et d'autres parties, sur la base des enseignements tirés de tous ces outils précédents.
+
+///
## Utilisés par **FastAPI**
-### Pydantic
+### 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.
@@ -380,14 +444,17 @@ Cela le rend extrêmement intuitif.
Il est comparable à Marshmallow. Bien qu'il soit plus rapide que Marshmallow dans les benchmarks. Et comme il est
basé sur les mêmes type hints Python, le support de l'éditeur est grand.
-!!! check "**FastAPI** l'utilise pour"
+/// check | **FastAPI** l'utilise pour
+
Gérer toute la validation des données, leur sérialisation et la documentation automatique du modèle (basée sur le schéma JSON).
- **FastAPI** prend ensuite ces données JSON Schema et les place dans OpenAPI, en plus de toutes les autres choses qu'il fait.
+**FastAPI** prend ensuite ces données JSON Schema et les place dans OpenAPI, en plus de toutes les autres choses qu'il fait.
+
+///
### Starlette
-Starlette 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.
@@ -413,17 +480,23 @@ Mais il ne fournit pas de validation automatique des données, de sérialisation
C'est l'une des principales choses que **FastAPI** ajoute par-dessus, le tout basé sur les type hints Python (en utilisant Pydantic). Cela, plus le système d'injection de dépendances, les utilitaires de sécurité, la génération de schémas OpenAPI, etc.
-!!! note "Détails techniques"
+/// note | Détails techniques
+
ASGI est une nouvelle "norme" développée par les membres de l'équipe principale de Django. Il ne s'agit pas encore d'une "norme Python" (un PEP), bien qu'ils soient en train de le faire.
- Néanmoins, il est déjà utilisé comme "standard" par plusieurs outils. Cela améliore grandement l'interopérabilité, puisque vous pouvez remplacer Uvicorn par n'importe quel autre serveur ASGI (comme Daphne ou Hypercorn), ou vous pouvez ajouter des outils compatibles ASGI, comme `python-socketio`.
+Néanmoins, il est déjà utilisé comme "standard" par plusieurs outils. Cela améliore grandement l'interopérabilité, puisque vous pouvez remplacer Uvicorn par n'importe quel autre serveur ASGI (comme Daphne ou Hypercorn), ou vous pouvez ajouter des outils compatibles ASGI, comme `python-socketio`.
+
+///
+
+/// check | **FastAPI** l'utilise pour
-!!! check "**FastAPI** l'utilise pour"
Gérer toutes les parties web de base. Ajouter des fonctionnalités par-dessus.
- La classe `FastAPI` elle-même hérite directement de la classe `Starlette`.
+La classe `FastAPI` elle-même hérite directement de la classe `Starlette`.
- Ainsi, tout ce que vous pouvez faire avec Starlette, vous pouvez le faire directement avec **FastAPI**, car il s'agit en fait de Starlette sous stéroïdes.
+Ainsi, tout ce que vous pouvez faire avec Starlette, vous pouvez le faire directement avec **FastAPI**, car il s'agit en fait de Starlette sous stéroïdes.
+
+///
### Uvicorn
@@ -434,12 +507,15 @@ quelque chose qu'un framework comme Starlette (ou **FastAPI**) fournirait par-de
C'est le serveur recommandé pour Starlette et **FastAPI**.
-!!! check "**FastAPI** le recommande comme"
+/// check | **FastAPI** le recommande comme
+
Le serveur web principal pour exécuter les applications **FastAPI**.
- Vous pouvez le combiner avec Gunicorn, pour avoir un serveur multi-processus asynchrone.
+Vous pouvez le combiner avec Gunicorn, pour avoir un serveur multi-processus asynchrone.
+
+Pour plus de détails, consultez la section [Déploiement](deployment/index.md){.internal-link target=_blank}.
- Pour plus de détails, consultez la section [Déploiement](deployment/index.md){.internal-link target=_blank}.
+///
## Benchmarks et vitesse
diff --git a/docs/fr/docs/async.md b/docs/fr/docs/async.md
index db88c4663..0ff5fa5d1 100644
--- a/docs/fr/docs/async.md
+++ b/docs/fr/docs/async.md
@@ -20,8 +20,11 @@ async def read_results():
return results
```
-!!! note
- Vous pouvez uniquement utiliser `await` dans les fonctions créées avec `async def`.
+/// note
+
+Vous pouvez uniquement utiliser `await` dans les fonctions créées avec `async def`.
+
+///
---
@@ -103,24 +106,44 @@ Pour expliquer la différence, voici une histoire de burgers :
Vous amenez votre crush 😍 dans votre fast food 🍔 favori, et faites la queue pendant que le serveur 💁 prend les commandes des personnes devant vous.
+
-
-
+
+
-
-
+
+
@@ -23,11 +29,11 @@
**Documentation** : https://fastapi.tiangolo.com
-**Code Source** : https://github.com/tiangolo/fastapi
+**Code Source** : https://github.com/fastapi/fastapi
---
-FastAPI est un framework web moderne et rapide (haute performance) pour la création d'API avec Python 3.7+, basé sur les annotations de type standard de Python.
+FastAPI est un framework web moderne et rapide (haute performance) pour la création d'API avec Python, basé sur les annotations de type standard de Python.
Les principales fonctionnalités sont :
@@ -63,7 +69,7 @@ Les principales fonctionnalités sont :
"_[...] J'utilise beaucoup **FastAPI** ces derniers temps. [...] Je prévois de l'utiliser dans mon équipe pour tous les **services de ML chez Microsoft**. Certains d'entre eux seront intégrés dans le coeur de **Windows** et dans certains produits **Office**._"
-
ujson
- pour un "décodage" JSON plus rapide.
-* email_validator
- pour la validation des adresses email.
+* email-validator
- pour la validation des adresses email.
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`.
Utilisées par FastAPI / Starlette :
* uvicorn
- Pour le serveur qui charge et sert votre application.
* orjson
- Obligatoire si vous voulez utiliser `ORJSONResponse`.
+* ujson
- Obligatoire si vous souhaitez utiliser `UJSONResponse`.
Vous pouvez tout installer avec `pip install fastapi[all]`.
diff --git a/docs/fr/docs/learn/index.md b/docs/fr/docs/learn/index.md
new file mode 100644
index 000000000..46fc095dc
--- /dev/null
+++ b/docs/fr/docs/learn/index.md
@@ -0,0 +1,5 @@
+# Apprendre
+
+Voici les sections introductives et les tutoriels pour apprendre **FastAPI**.
+
+Vous pouvez considérer ceci comme un **manuel**, un **cours**, la **méthode officielle** et recommandée pour appréhender FastAPI. 😎
diff --git a/docs/fr/docs/project-generation.md b/docs/fr/docs/project-generation.md
index c58d2cd2b..4c04dc167 100644
--- a/docs/fr/docs/project-generation.md
+++ b/docs/fr/docs/project-generation.md
@@ -14,7 +14,7 @@ GitHub : Swarm
* Intégration **Docker Compose** et optimisation pour développement local.
* Serveur web Python **prêt au déploiement** utilisant Uvicorn et Gunicorn.
-* Backend Python **FastAPI** :
+* Backend Python **FastAPI** :
* **Rapide** : Très hautes performances, comparables à **NodeJS** ou **Go** (grâce à Starlette et Pydantic).
* **Intuitif** : Excellent support des éditeurs. Complétion partout. Moins de temps passé à déboguer.
* **Facile** : Fait pour être facile à utiliser et apprendre. Moins de temps passé à lire de la documentation.
diff --git a/docs/fr/docs/python-types.md b/docs/fr/docs/python-types.md
index 4008ed96f..99ca90827 100644
--- a/docs/fr/docs/python-types.md
+++ b/docs/fr/docs/python-types.md
@@ -13,16 +13,17 @@ Seulement le minimum nécessaire pour les utiliser avec **FastAPI** sera couvert
Mais même si vous n'utilisez pas ou n'utiliserez jamais **FastAPI**, vous pourriez bénéficier d'apprendre quelques choses sur ces dernières.
-!!! note
- Si vous êtes un expert Python, et que vous savez déjà **tout** sur les annotations de type, passez au chapitre suivant.
+/// note
+
+Si vous êtes un expert Python, et que vous savez déjà **tout** sur les annotations de type, passez au chapitre suivant.
+
+///
## Motivations
Prenons un exemple simple :
-```Python
-{!../../../docs_src/python_types/tutorial001.py!}
-```
+{*../../docs_src/python_types/tutorial001.py*}
Exécuter ce programe affiche :
@@ -36,9 +37,7 @@ La fonction :
* Convertit la première lettre de chaque paramètre en majuscules grâce à `title()`.
* Concatène les résultats avec un espace entre les deux.
-```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial001.py!}
-```
+{*../../docs_src/python_types/tutorial001.py hl[2] *}
### Limitations
@@ -81,9 +80,7 @@ C'est tout.
Ce sont des annotations de types :
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial002.py!}
-```
+{*../../docs_src/python_types/tutorial002.py hl[1] *}
À ne pas confondre avec la déclaration de valeurs par défaut comme ici :
@@ -111,19 +108,15 @@ Vous pouvez donc dérouler les options jusqu'à trouver la méthode à laquelle
Cette fonction possède déjà des annotations de type :
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial003.py!}
-```
+{*../../docs_src/python_types/tutorial003.py hl[1] *}
Comme l'éditeur connaît le type des variables, vous n'avez pas seulement l'auto-complétion, mais aussi de la détection d'erreurs :
get
-!!! info "`@décorateur` Info"
- Cette syntaxe `@something` en Python est appelée un "décorateur".
+/// info | `@décorateur` Info
- Vous la mettez au dessus d'une fonction. Comme un joli chapeau décoratif (j'imagine que ce terme vient de là 🤷🏻♂).
+Cette syntaxe `@something` en Python est appelée un "décorateur".
- Un "décorateur" prend la fonction en dessous et en fait quelque chose.
+Vous la mettez au dessus d'une fonction. Comme un joli chapeau décoratif (j'imagine que ce terme vient de là 🤷🏻♂).
- Dans notre cas, ce décorateur dit à **FastAPI** que la fonction en dessous correspond au **chemin** `/` avec l'**opération** `get`.
+Un "décorateur" prend la fonction en dessous et en fait quelque chose.
- C'est le "**décorateur d'opération de chemin**".
+Dans notre cas, ce décorateur dit à **FastAPI** que la fonction en dessous correspond au **chemin** `/` avec l'**opération** `get`.
+
+C'est le "**décorateur d'opération de chemin**".
+
+///
Vous pouvez aussi utiliser les autres opérations :
@@ -275,14 +276,17 @@ Tout comme celles les plus exotiques :
* `@app.patch()`
* `@app.trace()`
-!!! tip "Astuce"
- Vous êtes libres d'utiliser chaque opération (méthode HTTP) comme vous le désirez.
+/// tip | Astuce
+
+Vous êtes libres d'utiliser chaque opération (méthode HTTP) comme vous le désirez.
- **FastAPI** n'impose pas de sens spécifique à chacune d'elle.
+**FastAPI** n'impose pas de sens spécifique à chacune d'elle.
- Les informations qui sont présentées ici forment une directive générale, pas des obligations.
+Les informations qui sont présentées ici forment une directive générale, pas des obligations.
- Par exemple, quand l'on utilise **GraphQL**, toutes les actions sont effectuées en utilisant uniquement des opérations `POST`.
+Par exemple, quand l'on utilise **GraphQL**, toutes les actions sont effectuées en utilisant uniquement des opérations `POST`.
+
+///
### Étape 4 : définir la **fonction de chemin**.
@@ -292,9 +296,7 @@ Voici notre "**fonction de chemin**" (ou fonction d'opération de chemin) :
* **opération** : `get`.
* **fonction** : la fonction sous le "décorateur" (sous `@app.get("/")`).
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[7] *}
C'est une fonction Python.
@@ -306,18 +308,17 @@ Ici, c'est une fonction asynchrone (définie avec `async def`).
Vous pourriez aussi la définir comme une fonction classique plutôt qu'avec `async def` :
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial003.py!}
-```
+{* ../../docs_src/first_steps/tutorial003.py hl[7] *}
+
+/// note
-!!! note
- Si vous ne connaissez pas la différence, allez voir la section [Concurrence : *"Vous êtes pressés ?"*](../async.md#vous-etes-presses){.internal-link target=_blank}.
+Si vous ne connaissez pas la différence, allez voir la section [Concurrence : *"Vous êtes pressés ?"*](../async.md#vous-etes-presses){.internal-link target=_blank}.
+
+///
### Étape 5 : retourner le contenu
-```Python hl_lines="8"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[8] *}
Vous pouvez retourner un dictionnaire (`dict`), une liste (`list`), des valeurs seules comme des chaines de caractères (`str`) et des entiers (`int`), etc.
diff --git a/docs/fr/docs/tutorial/index.md b/docs/fr/docs/tutorial/index.md
new file mode 100644
index 000000000..83cc5f9e8
--- /dev/null
+++ b/docs/fr/docs/tutorial/index.md
@@ -0,0 +1,83 @@
+# 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 :
+
+kwargs
. Même s'ils n'ont pas de valeur par défaut.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *}
+
+# Avec `Annotated`
+
+Gardez à l'esprit que si vous utilisez `Annotated`, comme vous n'utilisez pas les valeurs par défaut des paramètres de fonction, vous n'aurez pas ce problème, et vous n'aurez probablement pas besoin d'utiliser `*`.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py hl[10] *}
+
+## Validations numériques : supérieur ou égal
+
+Avec `Query` et `Path` (et d'autres que vous verrez plus tard) vous pouvez déclarer des contraintes numériques.
+
+Ici, avec `ge=1`, `item_id` devra être un nombre entier "`g`reater than or `e`qual" à `1`.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py hl[10] *}
+
+## Validations numériques : supérieur ou égal et inférieur ou égal
+
+La même chose s'applique pour :
+
+* `gt` : `g`reater `t`han
+* `le` : `l`ess than or `e`qual
+
+{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py hl[10] *}
+
+## Validations numériques : supérieur et inférieur ou égal
+
+La même chose s'applique pour :
+
+* `gt` : `g`reater `t`han
+* `le` : `l`ess than or `e`qual
+
+{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py hl[10] *}
+
+## Validations numériques : flottants, supérieur et inférieur
+
+Les validations numériques fonctionnent également pour les valeurs `float`.
+
+C'est ici qu'il devient important de pouvoir déclarer gt
et pas seulement ge
. Avec cela, vous pouvez exiger, par exemple, qu'une valeur doit être supérieure à `0`, même si elle est inférieure à `1`.
+
+Ainsi, `0.5` serait une valeur valide. Mais `0.0` ou `0` ne le serait pas.
+
+Et la même chose pour lt
.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py hl[13] *}
+
+## Pour résumer
+
+Avec `Query`, `Path` (et d'autres que vous verrez plus tard) vous pouvez déclarer des métadonnées et des validations de chaînes de la même manière qu'avec les [Paramètres de requête et validations de chaînes](query-params-str-validations.md){.internal-link target=_blank}.
+
+Et vous pouvez également déclarer des validations numériques :
+
+* `gt` : `g`reater `t`han
+* `ge` : `g`reater than or `e`qual
+* `lt` : `l`ess `t`han
+* `le` : `l`ess than or `e`qual
+
+/// info
+
+`Query`, `Path`, et d'autres classes que vous verrez plus tard sont des sous-classes d'une classe commune `Param`.
+
+Tous partagent les mêmes paramètres pour des validations supplémentaires et des métadonnées que vous avez vu précédemment.
+
+///
+
+/// note | Détails techniques
+
+Lorsque vous importez `Query`, `Path` et d'autres de `fastapi`, ce sont en fait des fonctions.
+
+Ces dernières, lorsqu'elles sont appelées, renvoient des instances de classes du même nom.
+
+Ainsi, vous importez `Query`, qui est une fonction. Et lorsque vous l'appelez, elle renvoie une instance d'une classe également nommée `Query`.
+
+Ces fonctions sont là (au lieu d'utiliser simplement les classes directement) pour que votre éditeur ne marque pas d'erreurs sur leurs types.
+
+De cette façon, vous pouvez utiliser votre éditeur et vos outils de codage habituels sans avoir à ajouter des configurations personnalisées pour ignorer ces erreurs.
+
+///
diff --git a/docs/fr/docs/tutorial/path-params.md b/docs/fr/docs/tutorial/path-params.md
index 894d62dd4..71c96b18e 100644
--- a/docs/fr/docs/tutorial/path-params.md
+++ b/docs/fr/docs/tutorial/path-params.md
@@ -4,9 +4,7 @@ Vous pouvez déclarer des "paramètres" ou "variables" de chemin avec la même s
formatage de chaîne Python :
-```Python hl_lines="6-7"
-{!../../../docs_src/path_params/tutorial001.py!}
-```
+{* ../../docs_src/path_params/tutorial001.py hl[6:7] *}
La valeur du paramètre `item_id` sera transmise à la fonction dans l'argument `item_id`.
@@ -22,15 +20,16 @@ vous verrez comme réponse :
Vous pouvez déclarer le type d'un paramètre de chemin dans la fonction, en utilisant les annotations de type Python :
-```Python hl_lines="7"
-{!../../../docs_src/path_params/tutorial002.py!}
-```
+{* ../../docs_src/path_params/tutorial002.py hl[7] *}
Ici, `item_id` est déclaré comme `int`.
-!!! hint "Astuce"
- Ceci vous permettra d'obtenir des fonctionnalités de l'éditeur dans votre fonction, telles
- que des vérifications d'erreur, de l'auto-complétion, etc.
+/// check | vérifier
+
+Ceci vous permettra d'obtenir des fonctionnalités de l'éditeur dans votre fonction, telles
+que des vérifications d'erreur, de l'auto-complétion, etc.
+
+///
## Conversion de données
@@ -40,12 +39,15 @@ Si vous exécutez cet exemple et allez sur "parsing" automatique.
+Comme vous l'avez remarqué, la valeur reçue par la fonction (et renvoyée ensuite) est `3`,
+en tant qu'entier (`int`) Python, pas la chaîne de caractères (`string`) `"3"`.
+
+Grâce aux déclarations de types, **FastAPI** fournit du
+"parsing" automatique.
+
+///
## Validation de données
@@ -72,12 +74,15 @@ La même erreur se produira si vous passez un nombre flottant (`float`) et non u
http://127.0.0.1:8000/items/4.2.
-!!! hint "Astuce"
- Donc, avec ces mêmes déclarations de type Python, **FastAPI** vous fournit de la validation de données.
+/// check | vérifier
+
+Donc, avec ces mêmes déclarations de type Python, **FastAPI** vous fournit de la validation de données.
- Notez que l'erreur mentionne le point exact où la validation n'a pas réussi.
+Notez que l'erreur mentionne le point exact où la validation n'a pas réussi.
- Ce qui est incroyablement utile au moment de développer et débugger du code qui interagit avec votre API.
+Ce qui est incroyablement utile au moment de développer et débugger du code qui interagit avec votre API.
+
+///
## Documentation
@@ -86,10 +91,13 @@ documentation générée automatiquement et interactive :
-
-
+
+
-
-
+
+
@@ -23,7 +29,7 @@
**תיעוד**: https://fastapi.tiangolo.com
-**קוד**: https://github.com/tiangolo/fastapi
+**קוד**: https://github.com/fastapi/fastapi
---
@@ -31,7 +37,7 @@ FastAPI היא תשתית רשת מודרנית ומהירה (ביצועים ג
תכונות המפתח הן:
-- **מהירה**: ביצועים גבוהים מאוד, בקנה אחד עם NodeJS ו - Go (תודות ל - Starlette ו - Pydantic). [אחת מתשתיות הפייתון המהירות ביותר](#performance).
+- **מהירה**: ביצועים גבוהים מאוד, בקנה אחד עם NodeJS ו - Go (תודות ל - Starlette ו - Pydantic). [אחת מתשתיות הפייתון המהירות ביותר](#_14).
- **מהירה לתכנות**: הגבירו את מהירות פיתוח התכונות החדשות בכ - %200 עד %300. \*
- **פחות שגיאות**: מנעו כ - %40 משגיאות אנוש (מפתחים). \*
@@ -64,7 +70,7 @@ FastAPI היא תשתית רשת מודרנית ומהירה (ביצועים ג
"_[...] I'm using **FastAPI** a ton these days. [...] I'm actually planning to use it for all of my team's **ML services at Microsoft**. Some of them are getting integrated into the core **Windows** product and some **Office** products._"
-
ujson
- "פרסור" JSON.
-- email_validator
- לאימות כתובות אימייל.
+- email-validator
- לאימות כתובות אימייל.
בשימוש Starlette:
- httpx
- דרוש אם ברצונכם להשתמש ב - `TestClient`.
- jinja2
- דרוש אם ברצונכם להשתמש בברירת המחדל של תצורת הטמפלייטים.
-- python-multipart
- דרוש אם ברצונכם לתמוך ב "פרסור" טפסים, באצמעות request.form()
.
+- python-multipart
- דרוש אם ברצונכם לתמוך ב "פרסור" טפסים, באצמעות request.form()
.
- itsdangerous
- דרוש אם ברצונכם להשתמש ב - `SessionMiddleware`.
- pyyaml
- דרוש אם ברצונכם להשתמש ב - `SchemaGenerator` של Starlette (כנראה שאתם לא צריכים את זה עם FastAPI).
-- ujson
- דרוש אם ברצונכם להשתמש ב - `UJSONResponse`.
בשימוש FastAPI / Starlette:
- uvicorn
- לשרת שטוען ומגיש את האפליקציה שלכם.
- orjson
- דרוש אם ברצונכם להשתמש ב - `ORJSONResponse`.
+- ujson
- דרוש אם ברצונכם להשתמש ב - `UJSONResponse`.
תוכלו להתקין את כל אלו באמצעות pip install "fastapi[all]"
.
diff --git a/docs/he/mkdocs.yml b/docs/he/mkdocs.yml
index acf7ea8fd..de18856f4 100644
--- a/docs/he/mkdocs.yml
+++ b/docs/he/mkdocs.yml
@@ -1,157 +1 @@
-site_name: FastAPI
-site_description: FastAPI framework, high performance, easy to learn, fast to code, ready for production
-site_url: https://fastapi.tiangolo.com/he/
-theme:
- name: material
- custom_dir: overrides
- palette:
- - media: '(prefers-color-scheme: light)'
- scheme: default
- primary: teal
- accent: amber
- toggle:
- icon: material/lightbulb
- name: Switch to light mode
- - media: '(prefers-color-scheme: dark)'
- scheme: slate
- primary: teal
- accent: amber
- toggle:
- icon: material/lightbulb-outline
- name: Switch to dark mode
- features:
- - search.suggest
- - search.highlight
- - content.tabs.link
- icon:
- repo: fontawesome/brands/github-alt
- logo: https://fastapi.tiangolo.com/img/icon-white.svg
- favicon: https://fastapi.tiangolo.com/img/favicon.png
- language: he
-repo_name: tiangolo/fastapi
-repo_url: https://github.com/tiangolo/fastapi
-edit_uri: ''
-plugins:
-- search
-- markdownextradata:
- data: data
-nav:
-- FastAPI: index.md
-- Languages:
- - en: /
- - az: /az/
- - cs: /cs/
- - de: /de/
- - em: /em/
- - es: /es/
- - fa: /fa/
- - fr: /fr/
- - he: /he/
- - hy: /hy/
- - id: /id/
- - it: /it/
- - ja: /ja/
- - ko: /ko/
- - nl: /nl/
- - pl: /pl/
- - pt: /pt/
- - ru: /ru/
- - sq: /sq/
- - sv: /sv/
- - ta: /ta/
- - tr: /tr/
- - uk: /uk/
- - zh: /zh/
-markdown_extensions:
-- toc:
- permalink: true
-- markdown.extensions.codehilite:
- guess_lang: false
-- mdx_include:
- base_path: docs
-- admonition
-- codehilite
-- extra
-- pymdownx.superfences:
- custom_fences:
- - name: mermaid
- class: mermaid
- format: !!python/name:pymdownx.superfences.fence_code_format ''
-- pymdownx.tabbed:
- alternate_style: true
-- attr_list
-- md_in_html
-extra:
- analytics:
- provider: google
- property: G-YNEVN69SC3
- social:
- - icon: fontawesome/brands/github-alt
- link: https://github.com/tiangolo/fastapi
- - icon: fontawesome/brands/discord
- link: https://discord.gg/VQjSZaeJmf
- - icon: fontawesome/brands/twitter
- link: https://twitter.com/fastapi
- - icon: fontawesome/brands/linkedin
- link: https://www.linkedin.com/in/tiangolo
- - icon: fontawesome/brands/dev
- link: https://dev.to/tiangolo
- - icon: fontawesome/brands/medium
- link: https://medium.com/@tiangolo
- - icon: fontawesome/solid/globe
- link: https://tiangolo.com
- alternate:
- - link: /
- name: en - English
- - link: /az/
- name: az
- - link: /cs/
- name: cs
- - link: /de/
- name: de
- - link: /em/
- name: 😉
- - link: /es/
- name: es - español
- - link: /fa/
- name: fa
- - link: /fr/
- name: fr - français
- - link: /he/
- name: he
- - link: /hy/
- name: hy
- - link: /id/
- name: id
- - link: /it/
- name: it - italiano
- - link: /ja/
- name: ja - 日本語
- - link: /ko/
- name: ko - 한국어
- - link: /nl/
- name: nl
- - link: /pl/
- name: pl
- - link: /pt/
- name: pt - português
- - link: /ru/
- name: ru - русский язык
- - link: /sq/
- name: sq - shqip
- - link: /sv/
- name: sv - svenska
- - link: /ta/
- name: ta - தமிழ்
- - link: /tr/
- name: tr - Türkçe
- - link: /uk/
- name: uk - українська мова
- - link: /zh/
- name: zh - 汉语
-extra_css:
-- https://fastapi.tiangolo.com/css/termynal.css
-- https://fastapi.tiangolo.com/css/custom.css
-extra_javascript:
-- https://fastapi.tiangolo.com/js/termynal.js
-- https://fastapi.tiangolo.com/js/custom.js
+INHERIT: ../en/mkdocs.yml
diff --git a/docs/he/overrides/.gitignore b/docs/he/overrides/.gitignore
deleted file mode 100644
index e69de29bb..000000000
diff --git a/docs/hu/docs/index.md b/docs/hu/docs/index.md
new file mode 100644
index 000000000..45ff49c3b
--- /dev/null
+++ b/docs/hu/docs/index.md
@@ -0,0 +1,467 @@
+
++ FastAPI keretrendszer, nagy teljesítmény, könnyen tanulható, gyorsan kódolható, productionre kész +
+ + +--- + +**Dokumentáció**: https://fastapi.tiangolo.com + +**Forrás kód**: https://github.com/fastapi/fastapi + +--- +A FastAPI egy modern, gyors (nagy teljesítményű), webes keretrendszer API-ok építéséhez Python -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 -%} +async def
-et...uvicorn main:app --reload
...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).
+
+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.
+* ujson
- Követelmény ha `UJSONResponse`-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 000000000..de18856f4
--- /dev/null
+++ b/docs/hu/mkdocs.yml
@@ -0,0 +1 @@
+INHERIT: ../en/mkdocs.yml
diff --git a/docs/hy/docs/index.md b/docs/hy/docs/index.md
deleted file mode 100644
index cc82b33cf..000000000
--- a/docs/hy/docs/index.md
+++ /dev/null
@@ -1,467 +0,0 @@
-
-{!../../../docs/missing-translation.md!}
-
-
-
-- FastAPI framework, high performance, easy to learn, fast to code, ready for production -
- - ---- - -**Documentation**: https://fastapi.tiangolo.com - -**Source Code**: https://github.com/tiangolo/fastapi - ---- - -FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints. - -The key features are: - -* **Fast**: Very high performance, on par with **NodeJS** and **Go** (thanks to Starlette and Pydantic). [One of the fastest Python frameworks available](#performance). -* **Fast to code**: Increase the speed to develop features by about 200% to 300%. * -* **Fewer bugs**: Reduce about 40% of human (developer) induced errors. * -* **Intuitive**: Great editor support. Completion everywhere. Less time debugging. -* **Easy**: Designed to be easy to use and learn. Less time reading docs. -* **Short**: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs. -* **Robust**: Get production-ready code. With automatic interactive documentation. -* **Standards-based**: Based on (and fully compatible with) the open standards for APIs: OpenAPI (previously known as Swagger) and JSON Schema. - -* estimation based on tests on an internal development team, building production applications. - -## Sponsors - - - -{% if sponsors %} -{% for sponsor in sponsors.gold -%} -async def
...uvicorn main:app --reload
...ujson
- for faster JSON "parsing".
-* email_validator
- for email validation.
-
-Used by Starlette:
-
-* httpx
- Required if you want to use the `TestClient`.
-* jinja2
- Required if you want to use the default template configuration.
-* python-multipart
- Required if you want to support form "parsing", with `request.form()`.
-* itsdangerous
- Required for `SessionMiddleware` support.
-* pyyaml
- Required for Starlette's `SchemaGenerator` support (you probably don't need it with FastAPI).
-* ujson
- Required if you want to use `UJSONResponse`.
-
-Used by FastAPI / Starlette:
-
-* uvicorn
- for the server that loads and serves your application.
-* orjson
- Required if you want to use `ORJSONResponse`.
-
-You can install all of these with `pip install "fastapi[all]"`.
-
-## License
-
-This project is licensed under the terms of the MIT license.
diff --git a/docs/hy/mkdocs.yml b/docs/hy/mkdocs.yml
deleted file mode 100644
index 5d251ff69..000000000
--- a/docs/hy/mkdocs.yml
+++ /dev/null
@@ -1,157 +0,0 @@
-site_name: FastAPI
-site_description: FastAPI framework, high performance, easy to learn, fast to code, ready for production
-site_url: https://fastapi.tiangolo.com/hy/
-theme:
- name: material
- custom_dir: overrides
- palette:
- - media: '(prefers-color-scheme: light)'
- scheme: default
- primary: teal
- accent: amber
- toggle:
- icon: material/lightbulb
- name: Switch to light mode
- - media: '(prefers-color-scheme: dark)'
- scheme: slate
- primary: teal
- accent: amber
- toggle:
- icon: material/lightbulb-outline
- name: Switch to dark mode
- features:
- - search.suggest
- - search.highlight
- - content.tabs.link
- icon:
- repo: fontawesome/brands/github-alt
- logo: https://fastapi.tiangolo.com/img/icon-white.svg
- favicon: https://fastapi.tiangolo.com/img/favicon.png
- language: hy
-repo_name: tiangolo/fastapi
-repo_url: https://github.com/tiangolo/fastapi
-edit_uri: ''
-plugins:
-- search
-- markdownextradata:
- data: data
-nav:
-- FastAPI: index.md
-- Languages:
- - en: /
- - az: /az/
- - cs: /cs/
- - de: /de/
- - em: /em/
- - es: /es/
- - fa: /fa/
- - fr: /fr/
- - he: /he/
- - hy: /hy/
- - id: /id/
- - it: /it/
- - ja: /ja/
- - ko: /ko/
- - nl: /nl/
- - pl: /pl/
- - pt: /pt/
- - ru: /ru/
- - sq: /sq/
- - sv: /sv/
- - ta: /ta/
- - tr: /tr/
- - uk: /uk/
- - zh: /zh/
-markdown_extensions:
-- toc:
- permalink: true
-- markdown.extensions.codehilite:
- guess_lang: false
-- mdx_include:
- base_path: docs
-- admonition
-- codehilite
-- extra
-- pymdownx.superfences:
- custom_fences:
- - name: mermaid
- class: mermaid
- format: !!python/name:pymdownx.superfences.fence_code_format ''
-- pymdownx.tabbed:
- alternate_style: true
-- attr_list
-- md_in_html
-extra:
- analytics:
- provider: google
- property: G-YNEVN69SC3
- social:
- - icon: fontawesome/brands/github-alt
- link: https://github.com/tiangolo/fastapi
- - icon: fontawesome/brands/discord
- link: https://discord.gg/VQjSZaeJmf
- - icon: fontawesome/brands/twitter
- link: https://twitter.com/fastapi
- - icon: fontawesome/brands/linkedin
- link: https://www.linkedin.com/in/tiangolo
- - icon: fontawesome/brands/dev
- link: https://dev.to/tiangolo
- - icon: fontawesome/brands/medium
- link: https://medium.com/@tiangolo
- - icon: fontawesome/solid/globe
- link: https://tiangolo.com
- alternate:
- - link: /
- name: en - English
- - link: /az/
- name: az
- - link: /cs/
- name: cs
- - link: /de/
- name: de
- - link: /em/
- name: 😉
- - link: /es/
- name: es - español
- - link: /fa/
- name: fa
- - link: /fr/
- name: fr - français
- - link: /he/
- name: he
- - link: /hy/
- name: hy
- - link: /id/
- name: id
- - link: /it/
- name: it - italiano
- - link: /ja/
- name: ja - 日本語
- - link: /ko/
- name: ko - 한국어
- - link: /nl/
- name: nl
- - link: /pl/
- name: pl
- - link: /pt/
- name: pt - português
- - link: /ru/
- name: ru - русский язык
- - link: /sq/
- name: sq - shqip
- - link: /sv/
- name: sv - svenska
- - link: /ta/
- name: ta - தமிழ்
- - link: /tr/
- name: tr - Türkçe
- - link: /uk/
- name: uk - українська мова
- - link: /zh/
- name: zh - 汉语
-extra_css:
-- https://fastapi.tiangolo.com/css/termynal.css
-- https://fastapi.tiangolo.com/css/custom.css
-extra_javascript:
-- https://fastapi.tiangolo.com/js/termynal.js
-- https://fastapi.tiangolo.com/js/custom.js
diff --git a/docs/hy/overrides/.gitignore b/docs/hy/overrides/.gitignore
deleted file mode 100644
index e69de29bb..000000000
diff --git a/docs/id/docs/index.md b/docs/id/docs/index.md
index 66fc2859e..5fb0c4c9c 100644
--- a/docs/id/docs/index.md
+++ b/docs/id/docs/index.md
@@ -1,50 +1,54 @@
+# FastAPI
-{!../../../docs/missing-translation.md!}
-
+
- FastAPI framework, high performance, easy to learn, fast to code, ready for production + FastAPI, framework performa tinggi, mudah dipelajari, cepat untuk coding, siap untuk pengembangan
--- -**Documentation**: https://fastapi.tiangolo.com +**Dokumentasi**: https://fastapi.tiangolo.com -**Source Code**: https://github.com/tiangolo/fastapi +**Kode Sumber**: https://github.com/fastapi/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: +FastAPI adalah *framework* *web* moderen, cepat (performa-tinggi) untuk membangun API dengan Python berdasarkan tipe petunjuk Python. -* **Fast**: Very high performance, on par with **NodeJS** and **Go** (thanks to Starlette and Pydantic). [One of the fastest Python frameworks available](#performance). +Fitur utama FastAPI: -* **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. +* **Cepat**: Performa sangat tinggi, setara **NodeJS** dan **Go** (berkat Starlette dan Pydantic). [Salah satu *framework* Python tercepat yang ada](#performa). +* **Cepat untuk coding**: Meningkatkan kecepatan pengembangan fitur dari 200% sampai 300%. * +* **Sedikit bug**: Mengurangi hingga 40% kesalahan dari manusia (pemrogram). * +* **Intuitif**: Dukungan editor hebat. Penyelesaian di mana pun. Lebih sedikit *debugging*. +* **Mudah**: Dibuat mudah digunakan dan dipelajari. Sedikit waktu membaca dokumentasi. +* **Ringkas**: Mengurasi duplikasi kode. Beragam fitur dari setiap deklarasi parameter. Lebih sedikit *bug*. +* **Handal**: Dapatkan kode siap-digunakan. Dengan dokumentasi otomatis interaktif. +* **Standar-resmi**: Berdasarkan (kompatibel dengan ) standar umum untuk API: OpenAPI (sebelumnya disebut Swagger) dan JSON Schema. -* estimation based on tests on an internal development team, building production applications. +* estimasi berdasarkan pengujian tim internal pengembangan applikasi siap pakai. -## Sponsors +## Sponsor @@ -59,97 +63,92 @@ The key features are: -Other sponsors +Sponsor lainnya -## Opinions +## Opini -"_[...] 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._" +"_[...] Saya banyak menggunakan **FastAPI** sekarang ini. [...] Saya berencana menggunakannya di semua tim servis ML Microsoft. Beberapa dari mereka sudah mengintegrasikan dengan produk inti *Windows** dan sebagian produk **Office**._" -async def
...async def
...uvicorn main:app --reload
...fastapi dev main.py
...email-validator
- untuk validasi email.
+
+Digunakan oleh Starlette:
-## Performance
+* httpx
- Dibutuhkan jika anda menggunakan `TestClient`.
+* jinja2
- Dibutuhkan jika anda menggunakan konfigurasi template bawaan.
+* python-multipart
- Dibutuhkan jika anda menggunakan form dukungan "parsing", dengan `request.form()`.
-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). (*)
+Digunakan oleh FastAPI / Starlette:
-To understand more about it, see the section Benchmarks.
+* uvicorn
- untuk server yang memuat dan melayani aplikasi anda. Termasuk `uvicorn[standard]`, yang memasukan sejumlah dependensi (misal `uvloop`) untuk needed melayani dengan performa tinggi.
+* `fastapi-cli` - untuk menyediakan perintah `fastapi`.
-## Optional Dependencies
+### Tanpda dependensi `standard`
-Used by Pydantic:
+Jika anda tidak ingin menambahkan dependensi opsional `standard`, anda dapat menggunakan `pip install fastapi` daripada `pip install "fastapi[standard]"`.
-* ujson
- for faster JSON "parsing".
-* email_validator
- for email validation.
+### Dependensi Opsional Tambahan
-Used by Starlette:
+Ada beberapa dependensi opsional yang bisa anda install.
-* 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`.
+Dependensi opsional tambahan Pydantic:
-Used by FastAPI / Starlette:
+* pydantic-settings
- untuk manajemen setting.
+* pydantic-extra-types
- untuk tipe tambahan yang digunakan dengan Pydantic.
-* uvicorn
- for the server that loads and serves your application.
-* orjson
- Required if you want to use `ORJSONResponse`.
+Dependensi tambahan opsional FastAPI:
-You can install all of these with `pip install fastapi[all]`.
+* orjson
- Diperlukan jika anda akan menggunakan`ORJSONResponse`.
+* ujson
- Diperlukan jika anda akan menggunakan `UJSONResponse`.
-## License
+## Lisensi
-This project is licensed under the terms of the MIT license.
+Project terlisensi dengan lisensi MIT.
diff --git a/docs/id/docs/tutorial/first-steps.md b/docs/id/docs/tutorial/first-steps.md
new file mode 100644
index 000000000..9b461507d
--- /dev/null
+++ b/docs/id/docs/tutorial/first-steps.md
@@ -0,0 +1,332 @@
+# Langkah Pertama
+
+File FastAPI yang paling sederhana bisa seperti berikut:
+
+{* ../../docs_src/first_steps/tutorial001.py *}
+
+Salin file tersebut ke `main.py`.
+
+Jalankan di server:
+
+get
+
+/// info | `@decorator` Info
+
+Sintaksis `@sesuatu` di Python disebut "dekorator".
+
+Dekorator ditempatkan di atas fungsi. Seperti sebuah topi cantik (Saya pikir istilah ini berasal dari situ).
+
+"dekorator" memanggil dan bekerja dengan fungsi yang ada di bawahnya
+
+Pada kondisi ini, dekorator ini memberi tahu **FastAPI** bahwa fungsi di bawah nya berhubungan dengan **path** `/` dengan **operasi** `get`.
+
+Sehingga disebut **dekorator operasi path**.
+
+///
+
+Operasi lainnya yang bisa digunakan:
+
+* `@app.post()`
+* `@app.put()`
+* `@app.delete()`
+
+Dan operasi unik lainnya:
+
+* `@app.options()`
+* `@app.head()`
+* `@app.patch()`
+* `@app.trace()`
+
+/// tip | Tips
+
+Jika anda bisa menggunakan operasi apa saja (metode HTTP).
+
+**FastAPI** tidak mengharuskan anda menggunakan operasi tertentu.
+
+Informasi di sini hanyalah sebagai panduan, bukan keharusan.
+
+Sebagai contoh, ketika menggunakan GraphQL, semua operasi umumnya hanya menggunakan `POST`.
+
+///
+
+### Langkah 4: mendefinisikan **fungsi operasi path**
+
+Ini "**fungsi operasi path**" kita:
+
+* **path**: adalah `/`.
+* **operasi**: adalah `get`.
+* **fungsi**: adalah fungsi yang ada di bawah dekorator (di bawah `@app.get("/")`).
+
+{* ../../docs_src/first_steps/tutorial001.py hl[7] *}
+
+Ini adalah fungsi Python.
+
+Fungsi ini dipanggil **FastAPI** setiap kali menerima request ke URL "`/`" dengan operasi `GET`.
+
+Di kondisi ini, ini adalah sebuah fungsi `async`.
+
+---
+
+Anda bisa mendefinisikan fungsi ini sebagai fungsi normal daripada `async def`:
+
+{* ../../docs_src/first_steps/tutorial003.py hl[7] *}
+
+/// note | Catatan
+
+Jika anda tidak tahu perbedaannya, kunjungi [Async: *"Panduan cepat"*](../async.md#in-a-hurry){.internal-link target=_blank}.
+
+///
+
+### Langkah 5: hasilkan konten
+
+{* ../../docs_src/first_steps/tutorial001.py hl[8] *}
+
+Anda bisa menghasilkan `dict`, `list`, nilai singular seperti `str`, `int`, dll.
+
+Anda juga bisa menghasilkan model Pydantic (anda akan belajar mengenai ini nanti).
+
+Ada banyak objek dan model yang secara otomatis dikonversi ke JSON (termasuk ORM, dll). Anda bisa menggunakan yang anda suka, kemungkinan sudah didukung.
+
+## Ringkasan
+
+* Impor `FastAPI`.
+* Buat sebuah instance `app`.
+* Tulis **dekorator operasi path** menggunakan dekorator seperti `@app.get("/")`.
+* Definisikan **fungsi operasi path**; sebagai contoh, `def root(): ...`.
+* Jalankan server development dengan perintah `fastapi dev`.
diff --git a/docs/id/docs/tutorial/index.md b/docs/id/docs/tutorial/index.md
index 8fec3c087..c01ec9a89 100644
--- a/docs/id/docs/tutorial/index.md
+++ b/docs/id/docs/tutorial/index.md
@@ -10,9 +10,9 @@ Sehingga kamu dapat kembali lagi dan mencari apa yang kamu butuhkan dengan tepat
## Jalankan kode
-Semua blok-blok kode dapat dicopy dan digunakan langsung (Mereka semua sebenarnya adalah file python yang sudah teruji).
+Semua blok-blok kode dapat disalin dan digunakan langsung (Mereka semua sebenarnya adalah file python yang sudah teruji).
-Untuk menjalankan setiap contoh, copy kode ke file `main.py`, dan jalankan `uvicorn` dengan:
+Untuk menjalankan setiap contoh, salin kode ke file `main.py`, dan jalankan `uvicorn` dengan:
- FastAPI framework, high performance, easy to learn, fast to code, ready for production + FastAPI framework, alte prestazioni, facile da imparare, rapido da implementare, pronto per il rilascio in produzione
+ --- -**Documentation**: https://fastapi.tiangolo.com +**Documentazione**: https://fastapi.tiangolo.com -**Source Code**: https://github.com/tiangolo/fastapi +**Codice Sorgente**: https://github.com/fastapi/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: +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. -* **Fast**: Very high performance, on par with **NodeJS** and **Go** (thanks to Starlette and Pydantic). [One of the fastest Python frameworks available](#performance). +Le sue caratteristiche principali sono: -* **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. +* **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. -* estimation based on tests on an internal development team, building production applications. +* Stima basata sull'esito di test eseguiti su codice sorgente di applicazioni rilasciate in produzione da un team interno di sviluppatori. -## Sponsors +## Sponsor @@ -59,19 +58,19 @@ The key features are: -Other sponsors +Altri sponsor -## Opinions +## 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._" -async def
...async def
...uvicorn main:app --reload
...uvicorn main:app --reload
...ujson
- for faster JSON "parsing".
-* email_validator
- for email validation.
+* email-validator
- per la validazione di email.
-Used by Starlette:
+Usate da Starlette:
-* httpx
- Required if you want to use the `TestClient`.
-* jinja2
- Required if you want to use the default template configuration.
-* python-multipart
- Required if you want to support form "parsing", with `request.form()`.
-* itsdangerous
- Required for `SessionMiddleware` support.
-* pyyaml
- Required for Starlette's `SchemaGenerator` support (you probably don't need it with FastAPI).
-* graphene
- Required for `GraphQLApp` support.
-* ujson
- Required if you want to use `UJSONResponse`.
+* requests
- 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`.
-Used by FastAPI / Starlette:
+Usate da FastAPI / Starlette:
-* uvicorn
- for the server that loads and serves your application.
-* orjson
- Required if you want to use `ORJSONResponse`.
+* uvicorn
- per il server che carica e serve la tua applicazione.
+* orjson
- ichiesto se vuoi usare `ORJSONResponse`.
+* ujson
- Richiesto se vuoi usare `UJSONResponse`.
-You can install all of these with `pip install fastapi[all]`.
+Puoi installarle tutte con `pip install fastapi[all]`.
-## License
+## Licenza
-This project is licensed under the terms of the MIT license.
+Questo progetto è concesso in licenza in base ai termini della licenza MIT.
diff --git a/docs/it/mkdocs.yml b/docs/it/mkdocs.yml
index 251d86681..de18856f4 100644
--- a/docs/it/mkdocs.yml
+++ b/docs/it/mkdocs.yml
@@ -1,157 +1 @@
-site_name: FastAPI
-site_description: FastAPI framework, high performance, easy to learn, fast to code, ready for production
-site_url: https://fastapi.tiangolo.com/it/
-theme:
- name: material
- custom_dir: overrides
- palette:
- - media: '(prefers-color-scheme: light)'
- scheme: default
- primary: teal
- accent: amber
- toggle:
- icon: material/lightbulb
- name: Switch to light mode
- - media: '(prefers-color-scheme: dark)'
- scheme: slate
- primary: teal
- accent: amber
- toggle:
- icon: material/lightbulb-outline
- name: Switch to dark mode
- features:
- - search.suggest
- - search.highlight
- - content.tabs.link
- icon:
- repo: fontawesome/brands/github-alt
- logo: https://fastapi.tiangolo.com/img/icon-white.svg
- favicon: https://fastapi.tiangolo.com/img/favicon.png
- language: it
-repo_name: tiangolo/fastapi
-repo_url: https://github.com/tiangolo/fastapi
-edit_uri: ''
-plugins:
-- search
-- markdownextradata:
- data: data
-nav:
-- FastAPI: index.md
-- Languages:
- - en: /
- - az: /az/
- - cs: /cs/
- - de: /de/
- - em: /em/
- - es: /es/
- - fa: /fa/
- - fr: /fr/
- - he: /he/
- - hy: /hy/
- - id: /id/
- - it: /it/
- - ja: /ja/
- - ko: /ko/
- - nl: /nl/
- - pl: /pl/
- - pt: /pt/
- - ru: /ru/
- - sq: /sq/
- - sv: /sv/
- - ta: /ta/
- - tr: /tr/
- - uk: /uk/
- - zh: /zh/
-markdown_extensions:
-- toc:
- permalink: true
-- markdown.extensions.codehilite:
- guess_lang: false
-- mdx_include:
- base_path: docs
-- admonition
-- codehilite
-- extra
-- pymdownx.superfences:
- custom_fences:
- - name: mermaid
- class: mermaid
- format: !!python/name:pymdownx.superfences.fence_code_format ''
-- pymdownx.tabbed:
- alternate_style: true
-- attr_list
-- md_in_html
-extra:
- analytics:
- provider: google
- property: G-YNEVN69SC3
- social:
- - icon: fontawesome/brands/github-alt
- link: https://github.com/tiangolo/fastapi
- - icon: fontawesome/brands/discord
- link: https://discord.gg/VQjSZaeJmf
- - icon: fontawesome/brands/twitter
- link: https://twitter.com/fastapi
- - icon: fontawesome/brands/linkedin
- link: https://www.linkedin.com/in/tiangolo
- - icon: fontawesome/brands/dev
- link: https://dev.to/tiangolo
- - icon: fontawesome/brands/medium
- link: https://medium.com/@tiangolo
- - icon: fontawesome/solid/globe
- link: https://tiangolo.com
- alternate:
- - link: /
- name: en - English
- - link: /az/
- name: az
- - link: /cs/
- name: cs
- - link: /de/
- name: de
- - link: /em/
- name: 😉
- - link: /es/
- name: es - español
- - link: /fa/
- name: fa
- - link: /fr/
- name: fr - français
- - link: /he/
- name: he
- - link: /hy/
- name: hy
- - link: /id/
- name: id
- - link: /it/
- name: it - italiano
- - link: /ja/
- name: ja - 日本語
- - link: /ko/
- name: ko - 한국어
- - link: /nl/
- name: nl
- - link: /pl/
- name: pl
- - link: /pt/
- name: pt - português
- - link: /ru/
- name: ru - русский язык
- - link: /sq/
- name: sq - shqip
- - link: /sv/
- name: sv - svenska
- - link: /ta/
- name: ta - தமிழ்
- - link: /tr/
- name: tr - Türkçe
- - link: /uk/
- name: uk - українська мова
- - link: /zh/
- name: zh - 汉语
-extra_css:
-- https://fastapi.tiangolo.com/css/termynal.css
-- https://fastapi.tiangolo.com/css/custom.css
-extra_javascript:
-- https://fastapi.tiangolo.com/js/termynal.js
-- https://fastapi.tiangolo.com/js/custom.js
+INHERIT: ../en/mkdocs.yml
diff --git a/docs/it/overrides/.gitignore b/docs/it/overrides/.gitignore
deleted file mode 100644
index e69de29bb..000000000
diff --git a/docs/ja/docs/advanced/additional-status-codes.md b/docs/ja/docs/advanced/additional-status-codes.md
index d1f8e6451..33457f591 100644
--- a/docs/ja/docs/advanced/additional-status-codes.md
+++ b/docs/ja/docs/advanced/additional-status-codes.md
@@ -14,21 +14,25 @@
これを達成するには、 `JSONResponse` をインポートし、 `status_code` を設定して直接内容を返します。
-```Python hl_lines="4 25"
-{!../../../docs_src/additional_status_codes/tutorial001.py!}
-```
+{* ../../docs_src/additional_status_codes/tutorial001.py hl[4,25] *}
-!!! warning "注意"
- 上記の例のように `Response` を明示的に返す場合、それは直接返されます。
+/// warning | 注意
- モデルなどはシリアライズされません。
+上記の例のように `Response` を明示的に返す場合、それは直接返されます。
- 必要なデータが含まれていることや、値が有効なJSONであること (`JSONResponse` を使う場合) を確認してください。
+モデルなどはシリアライズされません。
-!!! note "技術詳細"
- `from starlette.responses import JSONResponse` を利用することもできます。
+必要なデータが含まれていることや、値が有効なJSONであること (`JSONResponse` を使う場合) を確認してください。
- **FastAPI** は `fastapi.responses` と同じ `starlette.responses` を、開発者の利便性のために提供しています。しかし有効なレスポンスはほとんどStarletteから来ています。 `status` についても同じです。
+///
+
+/// note | 技術詳細
+
+`from starlette.responses import JSONResponse` を利用することもできます。
+
+**FastAPI** は `fastapi.responses` と同じ `starlette.responses` を、開発者の利便性のために提供しています。しかし有効なレスポンスはほとんどStarletteから来ています。 `status` についても同じです。
+
+///
## OpenAPIとAPIドキュメント
diff --git a/docs/ja/docs/advanced/conditional-openapi.md b/docs/ja/docs/advanced/conditional-openapi.md
deleted file mode 100644
index b892ed6c6..000000000
--- a/docs/ja/docs/advanced/conditional-openapi.md
+++ /dev/null
@@ -1,58 +0,0 @@
-# 条件付き OpenAPI
-
-必要であれば、設定と環境変数を利用して、環境に応じて条件付きでOpenAPIを構成することが可能です。また、完全にOpenAPIを無効にすることもできます。
-
-## セキュリティとAPI、およびドキュメントについて
-
-本番環境においてドキュメントのUIを非表示にすることによって、APIを保護しようと *すべきではありません*。
-
-それは、APIのセキュリティの強化にはならず、*path operations* は依然として利用可能です。
-
-もしセキュリティ上の欠陥がソースコードにあるならば、それは存在したままです。
-
-ドキュメンテーションを非表示にするのは、単にあなたのAPIへのアクセス方法を難解にするだけでなく、同時にあなた自身の本番環境でのAPIのデバッグを困難にしてしまう可能性があります。単純に、 Security through obscurity の一つの形態として考えられるでしょう。
-
-もしあなたのAPIのセキュリティを強化したいなら、いくつかのよりよい方法があります。例を示すと、
-
-* リクエストボディとレスポンスのためのPydanticモデルの定義を見直す。
-* 依存関係に基づきすべての必要なパーミッションとロールを設定する。
-* パスワードを絶対に平文で保存しない。パスワードハッシュのみを保存する。
-* PasslibやJWTトークンに代表される、よく知られた暗号化ツールを使って実装する。
-* そして必要なところでは、もっと細かいパーミッション制御をOAuth2スコープを使って行う。
-* など
-
-それでも、例えば本番環境のような特定の環境のみで、あるいは環境変数の設定によってAPIドキュメントをどうしても無効にしたいという、非常に特殊なユースケースがあるかもしれません。
-
-## 設定と環境変数による条件付き OpenAPI
-
-生成するOpenAPIとドキュメントUIの構成は、共通のPydanticの設定を使用して簡単に切り替えられます。
-
-例えば、
-
-```Python hl_lines="6 11"
-{!../../../docs_src/conditional_openapi/tutorial001.py!}
-```
-
-ここでは `openapi_url` の設定を、デフォルトの `"/openapi.json"` のまま宣言しています。
-
-そして、これを `FastAPI` appを作る際に使います。
-
-それから、以下のように `OPENAPI_URL` という環境変数を空文字列に設定することによってOpenAPI (UIドキュメントを含む) を無効化することができます。
-
-await
を使用していないので、私たちは`async def`ではなく通常の`def`で関数を宣言する必要があります。
-
-また、Couchbaseは単一の`Bucket`オブジェクトを複数のスレッドで使用しないことを推奨していますので、単に直接Bucketを取得して関数に渡すことが出来ます。
-
-```Python hl_lines="49-53"
-{!../../../docs_src/nosql_databases/tutorial001.py!}
-```
-
-## まとめ
-
-他のサードパーティ製のNoSQLデータベースを利用する場合でも、そのデータベースの標準ライブラリを利用するだけで利用できます。
-
-他の外部ツール、システム、APIについても同じことが言えます。
diff --git a/docs/ja/docs/advanced/path-operation-advanced-configuration.md b/docs/ja/docs/advanced/path-operation-advanced-configuration.md
index 35b381cae..05188d5b2 100644
--- a/docs/ja/docs/advanced/path-operation-advanced-configuration.md
+++ b/docs/ja/docs/advanced/path-operation-advanced-configuration.md
@@ -2,16 +2,17 @@
## OpenAPI operationId
-!!! warning "注意"
- あなたがOpenAPIの「エキスパート」でなければ、これは必要ないかもしれません。
+/// warning | 注意
+
+あなたがOpenAPIの「エキスパート」でなければ、これは必要ないかもしれません。
+
+///
*path operation* で `operation_id` パラメータを利用することで、OpenAPIの `operationId` を設定できます。
`operation_id` は各オペレーションで一意にする必要があります。
-```Python hl_lines="6"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial001.py!}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial001.py hl[6] *}
### *path operation関数* の名前をoperationIdとして使用する
@@ -19,25 +20,27 @@ APIの関数名を `operationId` として利用したい場合、すべてのAP
そうする場合は、すべての *path operation* を追加した後に行う必要があります。
-```Python hl_lines="2 12-21 24"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial002.py hl[2,12:21,24] *}
+
+/// tip | 豆知識
+
+`app.openapi()` を手動でコールする場合、その前に`operationId`を更新する必要があります。
+
+///
+
+/// warning | 注意
-!!! tip "豆知識"
- `app.openapi()` を手動でコールする場合、その前に`operationId`を更新する必要があります。
+この方法をとる場合、各 *path operation関数* が一意な名前である必要があります。
-!!! warning "注意"
- この方法をとる場合、各 *path operation関数* が一意な名前である必要があります。
+それらが異なるモジュール (Pythonファイル) にあるとしてもです。
- それらが異なるモジュール (Pythonファイル) にあるとしてもです。
+///
## OpenAPIから除外する
生成されるOpenAPIスキーマ (つまり、自動ドキュメント生成の仕組み) から *path operation* を除外するには、 `include_in_schema` パラメータを `False` にします。
-```Python hl_lines="6"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial003.py!}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial003.py hl[6] *}
## docstringによる説明の高度な設定
@@ -47,6 +50,4 @@ APIの関数名を `operationId` として利用したい場合、すべてのAP
ドキュメントには表示されませんが、他のツール (例えばSphinx) では残りの部分を利用できるでしょう。
-```Python hl_lines="19-29"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial004.py!}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial004.py hl[19:29] *}
diff --git a/docs/ja/docs/advanced/response-directly.md b/docs/ja/docs/advanced/response-directly.md
index 10ec88548..42412d507 100644
--- a/docs/ja/docs/advanced/response-directly.md
+++ b/docs/ja/docs/advanced/response-directly.md
@@ -14,8 +14,11 @@
実際は、`Response` やそのサブクラスを返すことができます。
-!!! tip "豆知識"
- `JSONResponse` それ自体は、 `Response` のサブクラスです。
+/// tip | 豆知識
+
+`JSONResponse` それ自体は、 `Response` のサブクラスです。
+
+///
`Response` を返した場合は、**FastAPI** は直接それを返します。
@@ -31,14 +34,15 @@
このようなケースでは、レスポンスにデータを含める前に `jsonable_encoder` を使ってデータを変換できます。
-```Python hl_lines="6-7 21-22"
-{!../../../docs_src/response_directly/tutorial001.py!}
-```
+{* ../../docs_src/response_directly/tutorial001.py hl[6:7,21:22] *}
+
+/// note | 技術詳細
+
+また、`from starlette.responses import JSONResponse` も利用できます。
-!!! note "技術詳細"
- また、`from starlette.responses import JSONResponse` も利用できます。
+**FastAPI** は開発者の利便性のために `fastapi.responses` という `starlette.responses` と同じものを提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。
- **FastAPI** は開発者の利便性のために `fastapi.responses` という `starlette.responses` と同じものを提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。
+///
## カスタム `Response` を返す
@@ -50,9 +54,7 @@
XMLを文字列にし、`Response` に含め、それを返します。
-```Python hl_lines="1 18"
-{!../../../docs_src/response_directly/tutorial002.py!}
-```
+{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *}
## 備考
diff --git a/docs/ja/docs/advanced/websockets.md b/docs/ja/docs/advanced/websockets.md
index 65e4112a6..43009eba8 100644
--- a/docs/ja/docs/advanced/websockets.md
+++ b/docs/ja/docs/advanced/websockets.md
@@ -38,30 +38,27 @@ $ pip install websockets
しかし、これはWebSocketのサーバーサイドに焦点を当て、実用的な例を示す最も簡単な方法です。
-```Python hl_lines="2 6-38 41-43"
-{!../../../docs_src/websockets/tutorial001.py!}
-```
+{* ../../docs_src/websockets/tutorial001.py hl[2,6:38,41:43] *}
## `websocket` を作成する
**FastAPI** アプリケーションで、`websocket` を作成します。
-```Python hl_lines="1 46-47"
-{!../../../docs_src/websockets/tutorial001.py!}
-```
+{* ../../docs_src/websockets/tutorial001.py hl[1,46:47] *}
+
+/// note | 技術詳細
+
+`from starlette.websockets import WebSocket` を使用しても構いません.
-!!! note "技術詳細"
- `from starlette.websockets import WebSocket` を使用しても構いません.
+**FastAPI** は開発者の利便性のために、同じ `WebSocket` を提供します。しかし、こちらはStarletteから直接提供されるものです。
- **FastAPI** は開発者の利便性のために、同じ `WebSocket` を提供します。しかし、こちらはStarletteから直接提供されるものです。
+///
## メッセージの送受信
WebSocketルートでは、 `await` を使ってメッセージの送受信ができます。
-```Python hl_lines="48-52"
-{!../../../docs_src/websockets/tutorial001.py!}
-```
+{* ../../docs_src/websockets/tutorial001.py hl[48:52] *}
バイナリやテキストデータ、JSONデータを送受信できます。
@@ -112,16 +109,17 @@ WebSocketエンドポイントでは、`fastapi` から以下をインポート
これらは、他のFastAPI エンドポイント/*path operation* の場合と同じように機能します。
-```Python hl_lines="58-65 68-83"
-{!../../../docs_src/websockets/tutorial002.py!}
-```
+{* ../../docs_src/websockets/tutorial002.py hl[58:65,68:83] *}
+
+/// info | 情報
-!!! info "情報"
- WebSocket で `HTTPException` を発生させることはあまり意味がありません。したがって、WebSocketの接続を直接閉じる方がよいでしょう。
+WebSocket で `HTTPException` を発生させることはあまり意味がありません。したがって、WebSocketの接続を直接閉じる方がよいでしょう。
- クロージングコードは、仕様で定義された有効なコードの中から使用することができます。
+クロージングコードは、仕様で定義された有効なコードの中から使用することができます。
- 将来的には、どこからでも `raise` できる `WebSocketException` が用意され、専用の例外ハンドラを追加できるようになる予定です。これは、Starlette の PR #527 に依存するものです。
+将来的には、どこからでも `raise` できる `WebSocketException` が用意され、専用の例外ハンドラを追加できるようになる予定です。これは、Starlette の PR #527 に依存するものです。
+
+///
### 依存関係を用いてWebSocketsを試してみる
@@ -144,8 +142,11 @@ $ uvicorn main:app --reload
* パスで使用される「Item ID」
* クエリパラメータとして使用される「Token」
-!!! tip "豆知識"
- クエリ `token` は依存パッケージによって処理されることに注意してください。
+/// tip | 豆知識
+
+クエリ `token` は依存パッケージによって処理されることに注意してください。
+
+///
これにより、WebSocketに接続してメッセージを送受信できます。
@@ -155,9 +156,7 @@ $ uvicorn main:app --reload
WebSocket接続が閉じられると、 `await websocket.receive_text()` は例外 `WebSocketDisconnect` を発生させ、この例のようにキャッチして処理することができます。
-```Python hl_lines="81-83"
-{!../../../docs_src/websockets/tutorial003.py!}
-```
+{* ../../docs_src/websockets/tutorial003.py hl[81:83] *}
試してみるには、
@@ -171,12 +170,15 @@ WebSocket接続が閉じられると、 `await websocket.receive_text()` は例
Client #1596980209979 left the chat
```
-!!! tip "豆知識"
- 上記のアプリは、複数の WebSocket 接続に対してメッセージを処理し、ブロードキャストする方法を示すための最小限のシンプルな例です。
+/// tip | 豆知識
+
+上記のアプリは、複数の WebSocket 接続に対してメッセージを処理し、ブロードキャストする方法を示すための最小限のシンプルな例です。
+
+しかし、すべての接続がメモリ内の単一のリストで処理されるため、プロセスの実行中にのみ機能し、単一のプロセスでのみ機能することに注意してください。
- しかし、すべての接続がメモリ内の単一のリストで処理されるため、プロセスの実行中にのみ機能し、単一のプロセスでのみ機能することに注意してください。
+もしFastAPIと簡単に統合できて、RedisやPostgreSQLなどでサポートされている、より堅牢なものが必要なら、encode/broadcaster を確認してください。
- もしFastAPIと簡単に統合できて、RedisやPostgreSQLなどでサポートされている、より堅牢なものが必要なら、encode/broadcaster を確認してください。
+///
## その他のドキュメント
diff --git a/docs/ja/docs/alternatives.md b/docs/ja/docs/alternatives.md
index ca6b29a07..8129a7002 100644
--- a/docs/ja/docs/alternatives.md
+++ b/docs/ja/docs/alternatives.md
@@ -30,11 +30,17 @@ Mozilla、Red Hat、Eventbrite など多くの企業で利用されています
これは**自動的なAPIドキュメント生成**の最初の例であり、これは**FastAPI**に向けた「調査」を触発した最初のアイデアの一つでした。
-!!! note "備考"
- Django REST Framework は Tom Christie によって作成されました。StarletteとUvicornの生みの親であり、**FastAPI**のベースとなっています。
+/// note | 備考
-!!! check "**FastAPI**へ与えたインスピレーション"
- 自動でAPIドキュメントを生成するWebユーザーインターフェースを持っている点。
+Django REST Framework は Tom Christie によって作成されました。StarletteとUvicornの生みの親であり、**FastAPI**のベースとなっています。
+
+///
+
+/// check | **FastAPI**へ与えたインスピレーション
+
+自動でAPIドキュメントを生成するWebユーザーインターフェースを持っている点。
+
+///
### Flask
@@ -50,11 +56,13 @@ Flask は「マイクロフレームワーク」であり、データベース
Flaskのシンプルさを考えると、APIを構築するのに適しているように思えました。次に見つけるべきは、Flask 用の「Django REST Framework」でした。
-!!! check "**FastAPI**へ与えたインスピレーション"
- マイクロフレームワークであること。ツールやパーツを目的に合うように簡単に組み合わせられる点。
+/// check | **FastAPI**へ与えたインスピレーション
+
+マイクロフレームワークであること。ツールやパーツを目的に合うように簡単に組み合わせられる点。
- シンプルで簡単なルーティングの仕組みを持っている点。
+シンプルで簡単なルーティングの仕組みを持っている点。
+///
### Requests
@@ -90,11 +98,13 @@ def read_url():
`requests.get(...)` と`@app.get(...)` には類似点が見受けられます。
-!!! check "**FastAPI**へ与えたインスピレーション"
- * シンプルで直感的なAPIを持っている点。
- * HTTPメソッド名を直接利用し、単純で直感的である。
- * 適切なデフォルト値を持ちつつ、強力なカスタマイズ性を持っている。
+/// check | **FastAPI**へ与えたインスピレーション
+
+* シンプルで直感的なAPIを持っている点。
+* HTTPメソッド名を直接利用し、単純で直感的である。
+* 適切なデフォルト値を持ちつつ、強力なカスタマイズ性を持っている。
+///
### Swagger / OpenAPI
@@ -108,15 +118,18 @@ def read_url():
そのため、バージョン2.0では「Swagger」、バージョン3以上では「OpenAPI」と表記するのが一般的です。
-!!! check "**FastAPI**へ与えたインスピレーション"
- 独自のスキーマの代わりに、API仕様のオープンな標準を採用しました。
+/// check | **FastAPI**へ与えたインスピレーション
- そして、標準に基づくユーザーインターフェースツールを統合しています。
+独自のスキーマの代わりに、API仕様のオープンな標準を採用しました。
- * Swagger UI
- * ReDoc
+そして、標準に基づくユーザーインターフェースツールを統合しています。
- この二つは人気で安定したものとして選択されましたが、少し検索してみると、 (**FastAPI**と同時に使用できる) OpenAPIのための多くの代替となるツールを見つけることができます。
+* Swagger UI
+* ReDoc
+
+この二つは人気で安定したものとして選択されましたが、少し検索してみると、 (**FastAPI**と同時に使用できる) OpenAPIのための多くの代替となるツールを見つけることができます。
+
+///
### Flask REST フレームワーク
@@ -134,8 +147,11 @@ APIが必要とするもう一つの大きな機能はデータのバリデー
しかし、それはPythonの型ヒントが存在する前に作られたものです。そのため、すべてのスキーマを定義するためには、Marshmallowが提供する特定のユーティリティやクラスを使用する必要があります。
-!!! check "**FastAPI**へ与えたインスピレーション"
- コードで「スキーマ」を定義し、データの型やバリデーションを自動で提供する点。
+/// check | **FastAPI**へ与えたインスピレーション
+
+コードで「スキーマ」を定義し、データの型やバリデーションを自動で提供する点。
+
+///
### Webargs
@@ -147,11 +163,17 @@ WebargsはFlaskをはじめとするいくつかのフレームワークの上
素晴らしいツールで、私も**FastAPI**を持つ前はよく使っていました。
-!!! info "情報"
- Webargsは、Marshmallowと同じ開発者により作られました。
+/// info | 情報
+
+Webargsは、Marshmallowと同じ開発者により作られました。
+
+///
-!!! check "**FastAPI**へ与えたインスピレーション"
- 受信したデータに対する自動的なバリデーションを持っている点。
+/// check | **FastAPI**へ与えたインスピレーション
+
+受信したデータに対する自動的なバリデーションを持っている点。
+
+///
### APISpec
@@ -171,11 +193,17 @@ Flask, Starlette, Responderなどにおいてはそのように動作します
エディタでは、この問題を解決することはできません。また、パラメータやMarshmallowスキーマを変更したときに、YAMLのdocstringを変更するのを忘れてしまうと、生成されたスキーマが古くなってしまいます。
-!!! info "情報"
- APISpecは、Marshmallowと同じ開発者により作成されました。
+/// info | 情報
+
+APISpecは、Marshmallowと同じ開発者により作成されました。
+
+///
+
+/// check | **FastAPI**へ与えたインスピレーション
+
+OpenAPIという、APIについてのオープンな標準をサポートしている点。
-!!! check "**FastAPI**へ与えたインスピレーション"
- OpenAPIという、APIについてのオープンな標準をサポートしている点。
+///
### Flask-apispec
@@ -197,11 +225,17 @@ Flask、Flask-apispec、Marshmallow、Webargsの組み合わせは、**FastAPI**
そして、これらのフルスタックジェネレーターは、[**FastAPI** Project Generators](project-generation.md){.internal-link target=_blank}の元となっていました。
-!!! info "情報"
- Flask-apispecはMarshmallowと同じ開発者により作成されました。
+/// info | 情報
-!!! check "**FastAPI**へ与えたインスピレーション"
- シリアライゼーションとバリデーションを定義したコードから、OpenAPIスキーマを自動的に生成する点。
+Flask-apispecはMarshmallowと同じ開発者により作成されました。
+
+///
+
+/// check | **FastAPI**へ与えたインスピレーション
+
+シリアライゼーションとバリデーションを定義したコードから、OpenAPIスキーマを自動的に生成する点。
+
+///
### NestJS (とAngular)
@@ -217,24 +251,33 @@ Angular 2にインスピレーションを受けた、統合された依存性
入れ子になったモデルをうまく扱えません。そのため、リクエストのJSONボディが内部フィールドを持つJSONオブジェクトで、それが順番にネストされたJSONオブジェクトになっている場合、適切にドキュメント化やバリデーションをすることができません。
-!!! check "**FastAPI**へ与えたインスピレーション"
- 素晴らしいエディターの補助を得るために、Pythonの型ヒントを利用している点。
+/// check | **FastAPI**へ与えたインスピレーション
+
+素晴らしいエディターの補助を得るために、Pythonの型ヒントを利用している点。
+
+強力な依存性注入の仕組みを持ち、コードの繰り返しを最小化する方法を見つけた点。
- 強力な依存性注入の仕組みを持ち、コードの繰り返しを最小化する方法を見つけた点。
+///
### Sanic
`asyncio`に基づいた、Pythonのフレームワークの中でも非常に高速なものの一つです。Flaskと非常に似た作りになっています。
-!!! note "技術詳細"
- Pythonの`asyncio`ループの代わりに、`uvloop`が利用されています。それにより、非常に高速です。
+/// note | 技術詳細
- `Uvicorn`と`Starlette`に明らかなインスピレーションを与えており、それらは現在オープンなベンチマークにおいてSanicより高速です。
+Pythonの`asyncio`ループの代わりに、`uvloop`が利用されています。それにより、非常に高速です。
-!!! check "**FastAPI**へ与えたインスピレーション"
- 物凄い性能を出す方法を見つけた点。
+`Uvicorn`と`Starlette`に明らかなインスピレーションを与えており、それらは現在オープンなベンチマークにおいてSanicより高速です。
- **FastAPI**が、(サードパーティのベンチマークによりテストされた) 最も高速なフレームワークであるStarletteに基づいている理由です。
+///
+
+/// check | **FastAPI**へ与えたインスピレーション
+
+物凄い性能を出す方法を見つけた点。
+
+**FastAPI**が、(サードパーティのベンチマークによりテストされた) 最も高速なフレームワークであるStarletteに基づいている理由です。
+
+///
### Falcon
@@ -246,12 +289,15 @@ Pythonのウェブフレームワーク標準規格 (WSGI) を使用していま
そのため、データのバリデーション、シリアライゼーション、ドキュメント化は、自動的にできずコードの中で行わなければなりません。あるいは、HugのようにFalconの上にフレームワークとして実装されなければなりません。このような分断は、パラメータとして1つのリクエストオブジェクトと1つのレスポンスオブジェクトを持つというFalconのデザインにインスピレーションを受けた他のフレームワークでも起こります。
-!!! check "**FastAPI**へ与えたインスピレーション"
- 素晴らしい性能を得るための方法を見つけた点。
+/// check | **FastAPI**へ与えたインスピレーション
+
+素晴らしい性能を得るための方法を見つけた点。
+
+Hug (HugはFalconをベースにしています) と一緒に、**FastAPI**が`response`引数を関数に持つことにインスピレーションを与えました。
- Hug (HugはFalconをベースにしています) と一緒に、**FastAPI**が`response`引数を関数に持つことにインスピレーションを与えました。
+**FastAPI**では任意ですが、ヘッダーやCookieやステータスコードを設定するために利用されています。
- **FastAPI**では任意ですが、ヘッダーやCookieやステータスコードを設定するために利用されています。
+///
### Molten
@@ -269,10 +315,13 @@ Pydanticのようなデータのバリデーション、シリアライゼーシ
ルーティングは一つの場所で宣言され、他の場所で宣言された関数を使用します (エンドポイントを扱う関数のすぐ上に配置できるデコレータを使用するのではなく) 。これはFlask (やStarlette) よりも、Djangoに近いです。これは、比較的緊密に結合されているものをコードの中で分離しています。
-!!! check "**FastAPI**へ与えたインスピレーション"
- モデルの属性の「デフォルト」値を使用したデータ型の追加バリデーションを定義します。これはエディタの補助を改善するもので、以前はPydanticでは利用できませんでした。
+/// check | **FastAPI**へ与えたインスピレーション
- 同様の方法でのバリデーションの宣言をサポートするよう、Pydanticを部分的にアップデートするインスピーレションを与えました。(現在はこれらの機能は全てPydanticで可能となっています。)
+モデルの属性の「デフォルト」値を使用したデータ型の追加バリデーションを定義します。これはエディタの補助を改善するもので、以前はPydanticでは利用できませんでした。
+
+同様の方法でのバリデーションの宣言をサポートするよう、Pydanticを部分的にアップデートするインスピーレションを与えました。(現在はこれらの機能は全てPydanticで可能となっています。)
+
+///
### Hug
@@ -288,15 +337,21 @@ OpenAPIやJSON Schemaのような標準に基づいたものではありませ
以前のPythonの同期型Webフレームワーク標準 (WSGI) をベースにしているため、Websocketなどは扱えませんが、それでも高性能です。
-!!! info "情報"
- HugはTimothy Crosleyにより作成されました。彼は`isort`など、Pythonのファイル内のインポートの並び替えを自動的におこうなう素晴らしいツールの開発者です。
+/// info | 情報
+
+HugはTimothy Crosleyにより作成されました。彼は`isort`など、Pythonのファイル内のインポートの並び替えを自動的におこうなう素晴らしいツールの開発者です。
+
+///
+
+/// check | **FastAPI**へ与えたインスピレーション
+
+HugはAPIStarに部分的なインスピレーションを与えており、私が発見した中ではAPIStarと同様に最も期待の持てるツールの一つでした。
-!!! check "**FastAPI**へ与えたインスピレーション"
- HugはAPIStarに部分的なインスピレーションを与えており、私が発見した中ではAPIStarと同様に最も期待の持てるツールの一つでした。
+Hugは、**FastAPI**がPythonの型ヒントを用いてパラメータを宣言し自動的にAPIを定義するスキーマを生成することを触発しました。
- Hugは、**FastAPI**がPythonの型ヒントを用いてパラメータを宣言し自動的にAPIを定義するスキーマを生成することを触発しました。
+Hugは、**FastAPI**がヘッダーやクッキーを設定するために関数に `response`引数を宣言することにインスピレーションを与えました。
- Hugは、**FastAPI**がヘッダーやクッキーを設定するために関数に `response`引数を宣言することにインスピレーションを与えました。
+///
### APIStar (<= 0.5)
@@ -322,27 +377,33 @@ OpenAPIやJSON Schemaのような標準に基づいたものではありませ
今ではAPIStarはOpenAPI仕様を検証するためのツールセットであり、ウェブフレームワークではありません。
-!!! info "情報"
- APIStarはTom Christieにより開発されました。以下の開発者でもあります:
+/// info | 情報
- * Django REST Framework
- * Starlette (**FastAPI**のベースになっています)
- * Uvicorn (Starletteや**FastAPI**で利用されています)
+APIStarはTom Christieにより開発されました。以下の開発者でもあります:
-!!! check "**FastAPI**へ与えたインスピレーション"
- 存在そのもの。
+* Django REST Framework
+* Starlette (**FastAPI**のベースになっています)
+* Uvicorn (Starletteや**FastAPI**で利用されています)
- 複数の機能 (データのバリデーション、シリアライゼーション、ドキュメント化) を同じPython型で宣言し、同時に優れたエディタの補助を提供するというアイデアは、私にとって素晴らしいアイデアでした。
+///
- そして、長い間同じようなフレームワークを探し、多くの異なる代替ツールをテストした結果、APIStarが最良の選択肢となりました。
+/// check | **FastAPI**へ与えたインスピレーション
- その後、APIStarはサーバーとして存在しなくなり、Starletteが作られ、そのようなシステムのための新しくより良い基盤となりました。これが**FastAPI**を構築するための最終的なインスピレーションでした。
+存在そのもの。
- 私は、これまでのツールから学んだことをもとに、機能や型システムなどの部分を改善・拡充しながら、**FastAPI**をAPIStarの「精神的な後継者」と考えています。
+複数の機能 (データのバリデーション、シリアライゼーション、ドキュメント化) を同じPython型で宣言し、同時に優れたエディタの補助を提供するというアイデアは、私にとって素晴らしいアイデアでした。
+
+そして、長い間同じようなフレームワークを探し、多くの異なる代替ツールをテストした結果、APIStarが最良の選択肢となりました。
+
+その後、APIStarはサーバーとして存在しなくなり、Starletteが作られ、そのようなシステムのための新しくより良い基盤となりました。これが**FastAPI**を構築するための最終的なインスピレーションでした。
+
+私は、これまでのツールから学んだことをもとに、機能や型システムなどの部分を改善・拡充しながら、**FastAPI**をAPIStarの「精神的な後継者」と考えています。
+
+///
## **FastAPI**が利用しているもの
-### Pydantic
+### Pydantic
Pydanticは、Pythonの型ヒントを元にデータのバリデーション、シリアライゼーション、 (JSON Schemaを使用した) ドキュメントを定義するライブラリです。
@@ -350,10 +411,13 @@ Pydanticは、Pythonの型ヒントを元にデータのバリデーション、
Marshmallowに匹敵しますが、ベンチマークではMarshmallowよりも高速です。また、Pythonの型ヒントを元にしているので、エディタの補助が素晴らしいです。
-!!! check "**FastAPI**での使用用途"
- データのバリデーション、データのシリアライゼーション、自動的なモデルの (JSON Schemaに基づいた) ドキュメント化の全てを扱えます。
+/// check | **FastAPI**での使用用途
+
+データのバリデーション、データのシリアライゼーション、自動的なモデルの (JSON Schemaに基づいた) ドキュメント化の全てを扱えます。
+
+**FastAPI**はJSON SchemaのデータをOpenAPIに利用します。
- **FastAPI**はJSON SchemaのデータをOpenAPIに利用します。
+///
### Starlette
@@ -383,17 +447,23 @@ Starletteは基本的なWebマイクロフレームワークの機能をすべ
これは **FastAPI** が追加する主な機能の一つで、すべての機能は Pythonの型ヒントに基づいています (Pydanticを使用しています) 。これに加えて、依存性注入の仕組み、セキュリティユーティリティ、OpenAPIスキーマ生成などがあります。
-!!! note "技術詳細"
- ASGIはDjangoのコアチームメンバーにより開発された新しい「標準」です。まだ「Pythonの標準 (PEP) 」ではありませんが、現在そうなるように進めています。
+/// note | 技術詳細
- しかしながら、いくつかのツールにおいてすでに「標準」として利用されています。このことは互換性を大きく改善するもので、Uvicornから他のASGIサーバー (DaphneやHypercorn) に乗り換えることができたり、あなたが`python-socketio`のようなASGI互換のツールを追加することもできます。
+ASGIはDjangoのコアチームメンバーにより開発された新しい「標準」です。まだ「Pythonの標準 (PEP) 」ではありませんが、現在そうなるように進めています。
-!!! check "**FastAPI**での使用用途"
- webに関するコアな部分を全て扱います。その上に機能を追加します。
+しかしながら、いくつかのツールにおいてすでに「標準」として利用されています。このことは互換性を大きく改善するもので、Uvicornから他のASGIサーバー (DaphneやHypercorn) に乗り換えることができたり、あなたが`python-socketio`のようなASGI互換のツールを追加することもできます。
- `FastAPI`クラスそのものは、`Starlette`クラスを直接継承しています。
+///
- 基本的にはStarletteの強化版であるため、Starletteで可能なことは**FastAPI**で直接可能です。
+/// check | **FastAPI**での使用用途
+
+webに関するコアな部分を全て扱います。その上に機能を追加します。
+
+`FastAPI`クラスそのものは、`Starlette`クラスを直接継承しています。
+
+基本的にはStarletteの強化版であるため、Starletteで可能なことは**FastAPI**で直接可能です。
+
+///
### Uvicorn
@@ -403,12 +473,15 @@ Uvicornは非常に高速なASGIサーバーで、uvloopとhttptoolsにより構
Starletteや**FastAPI**のサーバーとして推奨されています。
-!!! check "**FastAPI**が推奨する理由"
- **FastAPI**アプリケーションを実行するメインのウェブサーバーである点。
+/// check | **FastAPI**が推奨する理由
+
+**FastAPI**アプリケーションを実行するメインのウェブサーバーである点。
+
+Gunicornと組み合わせることで、非同期でマルチプロセスなサーバーを持つことがきます。
- Gunicornと組み合わせることで、非同期でマルチプロセスなサーバーを持つことがきます。
+詳細は[デプロイ](deployment/index.md){.internal-link target=_blank}の項目で確認してください。
- 詳細は[デプロイ](deployment/index.md){.internal-link target=_blank}の項目で確認してください。
+///
## ベンチマーク と スピード
diff --git a/docs/ja/docs/async.md b/docs/ja/docs/async.md
index 8fac2cb38..d1da1f82d 100644
--- a/docs/ja/docs/async.md
+++ b/docs/ja/docs/async.md
@@ -21,8 +21,11 @@ async def read_results():
return results
```
-!!! note "備考"
- `async def` を使用して作成された関数の内部でしか `await` は使用できません。
+/// note | 備考
+
+`async def` を使用して作成された関数の内部でしか `await` は使用できません。
+
+///
---
@@ -355,12 +358,15 @@ async def read_burgers():
## 非常に発展的な技術的詳細
-!!! warning "注意"
- 恐らくスキップしても良いでしょう。
+/// warning | 注意
+
+恐らくスキップしても良いでしょう。
+
+この部分は**FastAPI**の仕組みに関する非常に技術的な詳細です。
- この部分は**FastAPI**の仕組みに関する非常に技術的な詳細です。
+かなりの技術知識 (コルーチン、スレッド、ブロッキングなど) があり、FastAPIが `async def` と通常の `def` をどのように処理するか知りたい場合は、先に進んでください。
- かなりの技術知識 (コルーチン、スレッド、ブロッキングなど) があり、FastAPIが `async def` と通常の `def` をどのように処理するか知りたい場合は、先に進んでください。
+///
### Path operation 関数
@@ -368,7 +374,7 @@ async def read_burgers():
上記の方法と違った方法の別の非同期フレームワークから来ており、小さなパフォーマンス向上 (約100ナノ秒) のために通常の `def` を使用して些細な演算のみ行う *path operation 関数* を定義するのに慣れている場合は、**FastAPI**ではまったく逆の効果になることに注意してください。このような場合、*path operation 関数* がブロッキングI/Oを実行しないのであれば、`async def` の使用をお勧めします。
-それでも、どちらの状況でも、**FastAPI**が過去のフレームワークよりも (またはそれに匹敵するほど) [高速になる](/#performance){.internal-link target=_blank}可能性があります。
+それでも、どちらの状況でも、**FastAPI**が過去のフレームワークよりも (またはそれに匹敵するほど) [高速になる](index.md#_10){.internal-link target=_blank}可能性があります。
### 依存関係
@@ -390,4 +396,4 @@ async def read_burgers():
繰り返しになりますが、これらは非常に技術的な詳細であり、検索して辿り着いた場合は役立つでしょう。
-それ以外の場合は、上記のセクションのガイドラインで問題ないはずです: 急いでいますか?。
+それ以外の場合は、上記のセクションのガイドラインで問題ないはずです: 急いでいますか?。
diff --git a/docs/ja/docs/contributing.md b/docs/ja/docs/contributing.md
deleted file mode 100644
index 9affea443..000000000
--- a/docs/ja/docs/contributing.md
+++ /dev/null
@@ -1,470 +0,0 @@
-# 開発 - 貢献
-
-まず、[FastAPIを応援 - ヘルプの入手](help-fastapi.md){.internal-link target=_blank}の基本的な方法を見て、ヘルプを得た方がいいかもしれません。
-
-## 開発
-
-すでにリポジトリをクローンし、コードを詳しく調べる必要があるとわかっている場合に、環境構築のためのガイドラインをいくつか紹介します。
-
-### `venv`を使用した仮想環境
-
-Pythonの`venv`モジュールを使用して、ディレクトリに仮想環境を作成します:
-
-ujson
- より速い JSON への"変換".
-- email_validator
- E メールの検証
+- email-validator
- E メールの検証
Starlette によって使用されるもの:
- httpx
- `TestClient`を使用するために必要です。
- jinja2
- デフォルトのテンプレート設定を使用する場合は必要です。
-- python-multipart
- "parsing"`request.form()`からの変換をサポートしたい場合は必要です。
+- python-multipart
- "parsing"`request.form()`からの変換をサポートしたい場合は必要です。
- itsdangerous
- `SessionMiddleware` サポートのためには必要です。
- pyyaml
- Starlette の `SchemaGenerator` サポートのために必要です。 (FastAPI では必要ないでしょう。)
- graphene
- `GraphQLApp` サポートのためには必要です。
-- ujson
- `UJSONResponse`を使用する場合は必須です。
FastAPI / Starlette に使用されるもの:
- uvicorn
- アプリケーションをロードしてサーブするサーバーのため。
- orjson
- `ORJSONResponse`を使用したい場合は必要です。
+- ujson
- `UJSONResponse`を使用する場合は必須です。
これらは全て `pip install fastapi[all]`でインストールできます。
diff --git a/docs/ja/docs/learn/index.md b/docs/ja/docs/learn/index.md
new file mode 100644
index 000000000..2f24c670a
--- /dev/null
+++ b/docs/ja/docs/learn/index.md
@@ -0,0 +1,5 @@
+# 学習
+
+ここでは、**FastAPI** を学習するための入門セクションとチュートリアルを紹介します。
+
+これは、FastAPIを学習するにあたっての**書籍**や**コース**であり、**公式**かつ推奨される方法とみなすことができます 😎
diff --git a/docs/ja/docs/project-generation.md b/docs/ja/docs/project-generation.md
index 4b6f0f9fd..daef52efa 100644
--- a/docs/ja/docs/project-generation.md
+++ b/docs/ja/docs/project-generation.md
@@ -14,7 +14,7 @@ GitHub: **FastAPI** バックエンド:
+* Python **FastAPI** バックエンド:
* **高速**: **NodeJS** や **Go** 並みのとても高いパフォーマンス (Starlette と Pydantic のおかげ)。
* **直感的**: 素晴らしいエディタのサポートや 補完。 デバッグ時間の短縮。
* **簡単**: 簡単に利用、習得できるようなデザイン。ドキュメントを読む時間を削減。
diff --git a/docs/ja/docs/python-types.md b/docs/ja/docs/python-types.md
new file mode 100644
index 000000000..a847ce5d5
--- /dev/null
+++ b/docs/ja/docs/python-types.md
@@ -0,0 +1,314 @@
+# Pythonの型の紹介
+
+**Python 3.6以降** では「型ヒント」オプションがサポートされています。
+
+これらの **"型ヒント"** は変数の型を宣言することができる新しい構文です。(Python 3.6以降)
+
+変数に型を宣言することでエディターやツールがより良いサポートを提供することができます。
+
+ここではPythonの型ヒントについての **クイックチュートリアル/リフレッシュ** で、**FastAPI**でそれらを使用するために必要な最低限のことだけをカバーしています。...実際には本当に少ないです。
+
+**FastAPI** はすべてこれらの型ヒントに基づいており、多くの強みと利点を与えてくれます。
+
+しかしたとえまったく **FastAPI** を使用しない場合でも、それらについて少し学ぶことで利点を得ることができるでしょう。
+
+/// note | 備考
+
+もしあなたがPythonの専門家で、すでに型ヒントについてすべて知っているのであれば、次の章まで読み飛ばしてください。
+
+///
+
+## 動機
+
+簡単な例から始めてみましょう:
+
+{* ../../docs_src/python_types/tutorial001.py *}
+
+
+このプログラムを実行すると以下が出力されます:
+
+```
+John Doe
+```
+
+この関数は以下のようなことを行います:
+
+* `first_name`と`last_name`を取得します。
+* `title()`を用いて、それぞれの最初の文字を大文字に変換します。
+* 真ん中にスペースを入れて連結します。
+
+{* ../../docs_src/python_types/tutorial001.py hl[2] *}
+
+
+### 編集
+
+これはとても簡単なプログラムです。
+
+しかし、今、あなたがそれを一から書いていたと想像してみてください。
+
+パラメータの準備ができていたら、そのとき、関数の定義を始めていたことでしょう...
+
+しかし、そうすると「最初の文字を大文字に変換するあのメソッド」を呼び出す必要があります。
+
+それは`upper`でしたか?`uppercase`でしたか?それとも`first_uppercase`?または`capitalize`?
+
+そして、古くからプログラマーの友人であるエディタで自動補完を試してみます。
+
+関数の最初のパラメータ`first_name`を入力し、ドット(`.`)を入力してから、`Ctrl+Space`を押すと補完が実行されます。
+
+しかし、悲しいことに、これはなんの役にも立ちません:
+
+get
オペレーション
-!!! info "`@decorator` について"
- Pythonにおける`@something`シンタックスはデコレータと呼ばれます。
+/// info | `@decorator` について
+
+Pythonにおける`@something`シンタックスはデコレータと呼ばれます。
+
+「デコレータ」は関数の上に置きます。かわいらしい装飾的な帽子のようです(この用語の由来はそこにあると思います)。
- 「デコレータ」は関数の上に置きます。かわいらしい装飾的な帽子のようです(この用語の由来はそこにあると思います)。
+「デコレータ」は直下の関数を受け取り、それを使って何かを行います。
- 「デコレータ」は直下の関数を受け取り、それを使って何かを行います。
+私たちの場合、このデコレーターは直下の関数が**オペレーション** `get`を使用した**パス**` / `に対応することを**FastAPI** に通知します。
- 私たちの場合、このデコレーターは直下の関数が**オペレーション** `get`を使用した**パス**` / `に対応することを**FastAPI** に通知します。
+これが「*パスオペレーションデコレータ*」です。
- これが「*パスオペレーションデコレータ*」です。
+///
他のオペレーションも使用できます:
@@ -272,14 +274,17 @@ APIを構築するときは、通常、これらの特定のHTTPメソッドを
* `@app.patch()`
* `@app.trace()`
-!!! tip "豆知識"
- 各オペレーション (HTTPメソッド)は自由に使用できます。
+/// tip | 豆知識
+
+各オペレーション (HTTPメソッド)は自由に使用できます。
+
+**FastAPI**は特定の意味づけを強制しません。
- **FastAPI**は特定の意味づけを強制しません。
+ここでの情報は、要件ではなくガイドラインとして提示されます。
- ここでの情報は、要件ではなくガイドラインとして提示されます。
+例えば、GraphQLを使用する場合、通常は`POST`オペレーションのみを使用してすべてのアクションを実行します。
- 例えば、GraphQLを使用する場合、通常は`POST`オペレーションのみを使用してすべてのアクションを実行します。
+///
### Step 4: **パスオペレーション**を定義
@@ -289,9 +294,7 @@ APIを構築するときは、通常、これらの特定のHTTPメソッドを
* **オペレーション**: は`get`です。
* **関数**: 「デコレータ」の直下にある関数 (`@app.get("/")`の直下) です。
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[7] *}
これは、Pythonの関数です。
@@ -303,18 +306,17 @@ APIを構築するときは、通常、これらの特定のHTTPメソッドを
`async def`の代わりに通常の関数として定義することもできます:
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial003.py!}
-```
+{* ../../docs_src/first_steps/tutorial003.py hl[7] *}
+
+/// note | 備考
-!!! note "備考"
- 違いが分からない場合は、[Async: *"In a hurry?"*](../async.md#in-a-hurry){.internal-link target=_blank}を確認してください。
+違いが分からない場合は、[Async: *"急いでいますか?"*](../async.md#_1){.internal-link target=_blank}を確認してください。
+
+///
### Step 5: コンテンツの返信
-```Python hl_lines="8"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[8] *}
`dict`、`list`、`str`、`int`などを返すことができます。
diff --git a/docs/ja/docs/tutorial/handling-errors.md b/docs/ja/docs/tutorial/handling-errors.md
new file mode 100644
index 000000000..9a46cc738
--- /dev/null
+++ b/docs/ja/docs/tutorial/handling-errors.md
@@ -0,0 +1,261 @@
+# エラーハンドリング
+
+APIを使用しているクライアントにエラーを通知する必要がある状況はたくさんあります。
+
+このクライアントは、フロントエンドを持つブラウザ、誰かのコード、IoTデバイスなどが考えられます。
+
+クライアントに以下のようなことを伝える必要があるかもしれません:
+
+* クライアントにはその操作のための十分な権限がありません。
+* クライアントはそのリソースにアクセスできません。
+* クライアントがアクセスしようとしていた項目が存在しません。
+* など
+
+これらの場合、通常は **400**(400から499)の範囲内の **HTTPステータスコード** を返すことになります。
+
+これは200のHTTPステータスコード(200から299)に似ています。これらの「200」ステータスコードは、何らかの形でリクエスト「成功」であったことを意味します。
+
+400の範囲にあるステータスコードは、クライアントからのエラーがあったことを意味します。
+
+**"404 Not Found"** のエラー(およびジョーク)を覚えていますか?
+
+## `HTTPException`の使用
+
+HTTPレスポンスをエラーでクライアントに返すには、`HTTPException`を使用します。
+
+### `HTTPException`のインポート
+
+{* ../../docs_src/handling_errors/tutorial001.py hl[1] *}
+
+### コード内での`HTTPException`の発生
+
+`HTTPException`は通常のPythonの例外であり、APIに関連するデータを追加したものです。
+
+Pythonの例外なので、`return`ではなく、`raise`です。
+
+これはまた、*path operation関数*の内部で呼び出しているユーティリティ関数の内部から`HTTPException`を発生させた場合、*path operation関数*の残りのコードは実行されず、そのリクエストを直ちに終了させ、`HTTPException`からのHTTPエラーをクライアントに送信することを意味します。
+
+値を返す`return`よりも例外を発生させることの利点は、「依存関係とセキュリティ」のセクションでより明確になります。
+
+この例では、クライアントが存在しないIDでアイテムを要求した場合、`404`のステータスコードを持つ例外を発生させます:
+
+{* ../../docs_src/handling_errors/tutorial001.py hl[11] *}
+
+### レスポンス結果
+
+クライアントが`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エラーにカスタムヘッダを追加できると便利な状況がいくつかあります。
+
+おそらくコードの中で直接使用する必要はないでしょう。
+
+しかし、高度なシナリオのために必要な場合には、カスタムヘッダーを追加することができます:
+
+{* ../../docs_src/handling_errors/tutorial002.py hl[14] *}
+
+## カスタム例外ハンドラのインストール
+
+カスタム例外ハンドラはStarletteと同じ例外ユーティリティを使用して追加することができます。
+
+あなた(または使用しているライブラリ)が`raise`するかもしれないカスタム例外`UnicornException`があるとしましょう。
+
+そして、この例外をFastAPIでグローバルに処理したいと思います。
+
+カスタム例外ハンドラを`@app.exception_handler()`で追加することができます:
+
+{* ../../docs_src/handling_errors/tutorial003.py hl[5,6,7,13,14,15,16,17,18,24] *}
+
+ここで、`/unicorns/yolo`をリクエストすると、*path operation*は`UnicornException`を`raise`します。
+
+しかし、これは`unicorn_exception_handler`で処理されます。
+
+そのため、HTTPステータスコードが`418`で、JSONの内容が以下のような明確なエラーを受け取ることになります:
+
+```JSON
+{"message": "Oops! yolo did something. There goes a rainbow..."}
+```
+
+/// note | 技術詳細
+
+また、`from starlette.requests import Request`と`from starlette.responses import JSONResponse`を使用することもできます。
+
+**FastAPI** は開発者の利便性を考慮して、`fastapi.responses`と同じ`starlette.responses`を提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。これは`Request`と同じです。
+
+///
+
+## デフォルトの例外ハンドラのオーバーライド
+
+**FastAPI** にはいくつかのデフォルトの例外ハンドラがあります。
+
+これらのハンドラは、`HTTPException`を`raise`させた場合や、リクエストに無効なデータが含まれている場合にデフォルトのJSONレスポンスを返す役割を担っています。
+
+これらの例外ハンドラを独自のものでオーバーライドすることができます。
+
+### リクエスト検証の例外のオーバーライド
+
+リクエストに無効なデータが含まれている場合、**FastAPI** は内部的に`RequestValidationError`を発生させます。
+
+また、そのためのデフォルトの例外ハンドラも含まれています。
+
+これをオーバーライドするには`RequestValidationError`をインポートして`@app.exception_handler(RequestValidationError)`と一緒に使用して例外ハンドラをデコレートします。
+
+この例外ハンドラは`Requset`と例外を受け取ります。
+
+{* ../../docs_src/handling_errors/tutorial004.py hl[2,14,15,16] *}
+
+これで、`/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ではなくプレーンテキストを返すようにすることができます:
+
+{* ../../docs_src/handling_errors/tutorial004.py hl[3,4,9,10,11,22] *}
+
+/// note | 技術詳細
+
+また、`from starlette.responses import PlainTextResponse`を使用することもできます。
+
+**FastAPI** は開発者の利便性を考慮して、`fastapi.responses`と同じ`starlette.responses`を提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。
+
+///
+
+### `RequestValidationError`のボディの使用
+
+`RequestValidationError`には無効なデータを含む`body`が含まれています。
+
+アプリ開発中に本体のログを取ってデバッグしたり、ユーザーに返したりなどに使用することができます。
+
+{* ../../docs_src/handling_errors/tutorial005.py hl[14] *}
+
+ここで、以下のような無効な項目を送信してみてください:
+
+```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`からインポートして再利用することができます:
+
+{* ../../docs_src/handling_errors/tutorial006.py hl[2,3,4,5,15,21] *}
+
+この例では、非常に表現力のあるメッセージでエラーを`print`しています。
+
+しかし、例外を使用して、デフォルトの例外ハンドラを再利用することができるということが理解できます。
diff --git a/docs/ja/docs/tutorial/header-params.md b/docs/ja/docs/tutorial/header-params.md
index 1bf8440bb..ac89afbdb 100644
--- a/docs/ja/docs/tutorial/header-params.md
+++ b/docs/ja/docs/tutorial/header-params.md
@@ -6,9 +6,7 @@
まず、`Header`をインポートします:
-```Python hl_lines="3"
-{!../../../docs_src/header_params/tutorial001.py!}
-```
+{* ../../docs_src/header_params/tutorial001.py hl[3] *}
## `Header`のパラメータの宣言
@@ -16,17 +14,21 @@
最初の値がデフォルト値で、追加の検証パラメータや注釈パラメータをすべて渡すことができます。
-```Python hl_lines="9"
-{!../../../docs_src/header_params/tutorial001.py!}
-```
+{* ../../docs_src/header_params/tutorial001.py hl[9] *}
+
+/// note | 技術詳細
+
+`Header`は`Path`や`Query`、`Cookie`の「姉妹」クラスです。また、同じ共通の`Param`クラスを継承しています。
+
+しかし、`fastapi`から`Query`や`Path`、`Header`などをインポートする場合、それらは実際には特殊なクラスを返す関数であることを覚えておいてください。
-!!! note "技術詳細"
- `Header`は`Path`や`Query`、`Cookie`の「姉妹」クラスです。また、同じ共通の`Param`クラスを継承しています。
+///
- しかし、`fastapi`から`Query`や`Path`、`Header`などをインポートする場合、それらは実際には特殊なクラスを返す関数であることを覚えておいてください。
+/// info | 情報
-!!! info "情報"
- ヘッダーを宣言するには、`Header`を使う必要があります。なぜなら、そうしないと、パラメータがクエリのパラメータとして解釈されてしまうからです。
+ヘッダーを宣言するには、`Header`を使う必要があります。なぜなら、そうしないと、パラメータがクエリのパラメータとして解釈されてしまうからです。
+
+///
## 自動変換
@@ -44,13 +46,13 @@
もしなんらかの理由でアンダースコアからハイフンへの自動変換を無効にする必要がある場合は、`Header`の`convert_underscores`に`False`を設定してください:
-```Python hl_lines="9"
-{!../../../docs_src/header_params/tutorial002.py!}
-```
+{* ../../docs_src/header_params/tutorial002.py hl[9] *}
-!!! warning "注意"
- `convert_underscores`を`False`に設定する前に、HTTPプロキシやサーバの中にはアンダースコアを含むヘッダーの使用を許可していないものがあることに注意してください。
+/// warning | 注意
+`convert_underscores`を`False`に設定する前に、HTTPプロキシやサーバの中にはアンダースコアを含むヘッダーの使用を許可していないものがあることに注意してください。
+
+///
## ヘッダーの重複
@@ -62,9 +64,7 @@
例えば、複数回出現する可能性のある`X-Token`のヘッダを定義するには、以下のように書くことができます:
-```Python hl_lines="9"
-{!../../../docs_src/header_params/tutorial003.py!}
-```
+{* ../../docs_src/header_params/tutorial003.py hl[9] *}
もし、その*path operation*で通信する場合は、次のように2つのHTTPヘッダーを送信します:
diff --git a/docs/ja/docs/tutorial/index.md b/docs/ja/docs/tutorial/index.md
index a2dd59c9b..87d3751fd 100644
--- a/docs/ja/docs/tutorial/index.md
+++ b/docs/ja/docs/tutorial/index.md
@@ -1,4 +1,4 @@
-# チュートリアル - ユーザーガイド - はじめに
+# チュートリアル - ユーザーガイド
このチュートリアルは**FastAPI**のほぼすべての機能の使い方を段階的に紹介します。
@@ -52,22 +52,25 @@ $ pip install "fastapi[all]"
...これには、コードを実行するサーバーとして使用できる `uvicorn`も含まれます。
-!!! note "備考"
- パーツ毎にインストールすることも可能です。
+/// note | 備考
- 以下は、アプリケーションを本番環境にデプロイする際に行うであろうものです:
+パーツ毎にインストールすることも可能です。
- ```
- pip install fastapi
- ```
+以下は、アプリケーションを本番環境にデプロイする際に行うであろうものです:
- また、サーバーとして動作するように`uvicorn` をインストールします:
+```
+pip install fastapi
+```
+
+また、サーバーとして動作するように`uvicorn` をインストールします:
+
+```
+pip install "uvicorn[standard]"
+```
- ```
- pip install "uvicorn[standard]"
- ```
+そして、使用したい依存関係をそれぞれ同様にインストールします。
- そして、使用したい依存関係をそれぞれ同様にインストールします。
+///
## 高度なユーザーガイド
diff --git a/docs/ja/docs/tutorial/metadata.md b/docs/ja/docs/tutorial/metadata.md
new file mode 100644
index 000000000..b93dedcb9
--- /dev/null
+++ b/docs/ja/docs/tutorial/metadata.md
@@ -0,0 +1,101 @@
+# メタデータとドキュメントのURL
+
+**FastAPI** アプリケーションのいくつかのメタデータの設定をカスタマイズできます。
+
+## タイトル、説明文、バージョン
+
+以下を設定できます:
+
+* **タイトル**: OpenAPIおよび自動APIドキュメントUIでAPIのタイトル/名前として使用される。
+* **説明文**: OpenAPIおよび自動APIドキュメントUIでのAPIの説明文。
+* **バージョン**: APIのバージョン。例: `v2` または `2.5.0`。
+ *たとえば、以前のバージョンのアプリケーションがあり、OpenAPIも使用している場合に便利です。
+
+これらを設定するには、パラメータ `title`、`description`、`version` を使用します:
+
+{* ../../docs_src/metadata/tutorial001.py hl[4:6] *}
+
+この設定では、自動APIドキュメントは以下の様になります:
+
+kwargs
としても知られています。たとえデフォルト値がなくても。
+
+{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[8] *}
+
+## 数値の検証: 以上
+
+`Query`と`Path`(、そして後述する他のもの)を用いて、文字列の制約を宣言することができますが、数値の制約も同様に宣言できます。
+
+ここで、`ge=1`の場合、`item_id`は`1`「より大きい`g`か、同じ`e`」整数でなれけばなりません。
+
+{* ../../docs_src/path_params_numeric_validations/tutorial004.py hl[8] *}
+
+## 数値の検証: より大きいと小なりイコール
+
+以下も同様です:
+
+* `gt`: より大きい(`g`reater `t`han)
+* `le`: 小なりイコール(`l`ess than or `e`qual)
+
+{* ../../docs_src/path_params_numeric_validations/tutorial005.py hl[9] *}
+
+## 数値の検証: 浮動小数点、 大なり小なり
+
+数値のバリデーションは`float`の値に対しても有効です。
+
+ここで重要になってくるのはgt
だけでなくge
も宣言できることです。これと同様に、例えば、値が`1`より小さくても`0`より大きくなければならないことを要求することができます。
+
+したがって、`0.5`は有効な値ですが、`0.0`や`0`はそうではありません。
+
+これはlt
も同じです。
+
+{* ../../docs_src/path_params_numeric_validations/tutorial006.py hl[11] *}
+
+## まとめ
+
+`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 66de05afb..1893ec12f 100644
--- a/docs/ja/docs/tutorial/path-params.md
+++ b/docs/ja/docs/tutorial/path-params.md
@@ -2,9 +2,7 @@
Pythonのformat文字列と同様のシンタックスで「パスパラメータ」や「パス変数」を宣言できます:
-```Python hl_lines="6 7"
-{!../../../docs_src/path_params/tutorial001.py!}
-```
+{* ../../docs_src/path_params/tutorial001.py hl[6,7] *}
パスパラメータ `item_id` の値は、引数 `item_id` として関数に渡されます。
@@ -18,14 +16,15 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー
標準のPythonの型アノテーションを使用して、関数内のパスパラメータの型を宣言できます:
-```Python hl_lines="7"
-{!../../../docs_src/path_params/tutorial002.py!}
-```
+{* ../../docs_src/path_params/tutorial002.py hl[7] *}
ここでは、 `item_id` は `int` として宣言されています。
-!!! check "確認"
- これにより、関数内でのエディターサポート (エラーチェックや補完など) が提供されます。
+/// check | 確認
+
+これにより、関数内でのエディターサポート (エラーチェックや補完など) が提供されます。
+
+///
## データ変換
@@ -35,10 +34,13 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー
{"item_id":3}
```
-!!! check "確認"
- 関数が受け取った(および返した)値は、文字列の `"3"` ではなく、Pythonの `int` としての `3` であることに注意してください。
+/// check | 確認
- したがって、型宣言を使用すると、**FastAPI**は自動リクエスト "解析" を行います。
+関数が受け取った(および返した)値は、文字列の `"3"` ではなく、Pythonの `int` としての `3` であることに注意してください。
+
+したがって、型宣言を使用すると、**FastAPI**は自動リクエスト "解析" を行います。
+
+///
## データバリデーション
@@ -63,12 +65,15 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー
http://127.0.0.1:8000/items/4.2 で見られるように、intのかわりに `float` が与えられた場合にも同様なエラーが表示されます。
-!!! check "確認"
- したがって、Pythonの型宣言を使用することで、**FastAPI**はデータのバリデーションを行います。
+/// check | 確認
+
+したがって、Pythonの型宣言を使用することで、**FastAPI**はデータのバリデーションを行います。
- 表示されたエラーには問題のある箇所が明確に指摘されていることに注意してください。
+表示されたエラーには問題のある箇所が明確に指摘されていることに注意してください。
- これは、APIに関連するコードの開発およびデバッグに非常に役立ちます。
+これは、APIに関連するコードの開発およびデバッグに非常に役立ちます。
+
+///
## ドキュメント
@@ -76,10 +81,13 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー
POST
のウェブドキュメントを参照してください。
+
+///
- しかし、フォームがファイルを含む場合は、`multipart/form-data`としてエンコードされます。ファイルの扱いについては次の章で説明します。
+/// warning | 注意
- これらのエンコーディングやフォームフィールドの詳細については、MDNのPOST
のウェブドキュメントを参照してください。
+*path operation*で複数の`Form`パラメータを宣言することができますが、JSONとして受け取ることを期待している`Body`フィールドを宣言することはできません。なぜなら、リクエストは`application/json`の代わりに`application/x-www-form-urlencoded`を使ってボディをエンコードするからです。
-!!! warning "注意"
- *path operation*で複数の`Form`パラメータを宣言することができますが、JSONとして受け取ることを期待している`Body`フィールドを宣言することはできません。なぜなら、リクエストは`application/json`の代わりに`application/x-www-form-urlencoded`を使ってボディをエンコードするからです。
+これは **FastAPI**の制限ではなく、HTTPプロトコルの一部です。
- これは **FastAPI**の制限ではなく、HTTPプロトコルの一部です。
+///
## まとめ
diff --git a/docs/ja/docs/tutorial/response-model.md b/docs/ja/docs/tutorial/response-model.md
new file mode 100644
index 000000000..b8464a4c7
--- /dev/null
+++ b/docs/ja/docs/tutorial/response-model.md
@@ -0,0 +1,212 @@
+# レスポンスモデル
+
+*path operations* のいずれにおいても、`response_model`パラメータを使用して、レスポンスのモデルを宣言することができます:
+
+* `@app.get()`
+* `@app.post()`
+* `@app.put()`
+* `@app.delete()`
+* など。
+
+{* ../../docs_src/response_model/tutorial001.py hl[17] *}
+
+/// 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`モデルを宣言しています。それには平文のパスワードが含まれています:
+
+{* ../../docs_src/response_model/tutorial002.py hl[9,11] *}
+
+そして、このモデルを使用して入力を宣言し、同じモデルを使って出力を宣言しています:
+
+{* ../../docs_src/response_model/tutorial002.py hl[17,18] *}
+
+これで、ブラウザがパスワードを使ってユーザーを作成する際に、APIがレスポンスで同じパスワードを返すようになりました。
+
+この場合、ユーザー自身がパスワードを送信しているので問題ないかもしれません。
+
+しかし、同じモデルを別の*path operation*に使用すると、すべてのクライアントにユーザーのパスワードを送信してしまうことになります。
+
+/// danger | 危険
+
+ユーザーの平文のパスワードを保存したり、レスポンスで送信したりすることは絶対にしないでください。
+
+///
+
+## 出力モデルの追加
+
+代わりに、平文のパスワードを持つ入力モデルと、パスワードを持たない出力モデルを作成することができます:
+
+{* ../../docs_src/response_model/tutorial003.py hl[9,11,16] *}
+
+ここでは、*path operation関数*がパスワードを含む同じ入力ユーザーを返しているにもかかわらず:
+
+{* ../../docs_src/response_model/tutorial003.py hl[24] *}
+
+...`response_model`を`UserOut`と宣言したことで、パスワードが含まれていません:
+
+{* ../../docs_src/response_model/tutorial003.py hl[22] *}
+
+そのため、**FastAPI** は出力モデルで宣言されていない全てのデータをフィルタリングしてくれます(Pydanticを使用)。
+
+## ドキュメントを見る
+
+自動ドキュメントを見ると、入力モデルと出力モデルがそれぞれ独自のJSON Schemaを持っていることが確認できます。
+
+ujson
- 더 빠른 JSON "파싱".
-* email_validator
- 이메일 유효성 검사.
+* email-validator
- 이메일 유효성 검사.
Starlette이 사용하는:
* HTTPX
- `TestClient`를 사용하려면 필요.
* jinja2
- 기본 템플릿 설정을 사용하려면 필요.
-* python-multipart
- `request.form()`과 함께 "parsing"의 지원을 원하면 필요.
+* python-multipart
- `request.form()`과 함께 "parsing"의 지원을 원하면 필요.
* itsdangerous
- `SessionMiddleware` 지원을 위해 필요.
* pyyaml
- Starlette의 `SchemaGenerator` 지원을 위해 필요 (FastAPI와 쓸때는 필요 없을 것입니다).
* graphene
- `GraphQLApp` 지원을 위해 필요.
-* ujson
- `UJSONResponse`를 사용하려면 필요.
FastAPI / Starlette이 사용하는:
* uvicorn
- 애플리케이션을 로드하고 제공하는 서버.
* orjson
- `ORJSONResponse`을 사용하려면 필요.
+* ujson
- `UJSONResponse`를 사용하려면 필요.
`pip install fastapi[all]`를 통해 이 모두를 설치 할 수 있습니다.
diff --git a/docs/ko/docs/learn/index.md b/docs/ko/docs/learn/index.md
new file mode 100644
index 000000000..7ac3a99b6
--- /dev/null
+++ b/docs/ko/docs/learn/index.md
@@ -0,0 +1,5 @@
+# 배우기
+
+여기 **FastAPI**를 배우기 위한 입문 자료와 자습서가 있습니다.
+
+여러분은 FastAPI를 배우기 위해 **책**, **강의**, **공식 자료** 그리고 추천받은 방법을 고려할 수 있습니다. 😎
diff --git a/docs/ko/docs/openapi-webhooks.md b/docs/ko/docs/openapi-webhooks.md
new file mode 100644
index 000000000..96339aa96
--- /dev/null
+++ b/docs/ko/docs/openapi-webhooks.md
@@ -0,0 +1,55 @@
+# OpenAPI 웹훅(Webhooks)
+
+API **사용자**에게 특정 **이벤트**가 발생할 때 *그들*의 앱(시스템)에 요청을 보내 **알림**을 전달할 수 있다는 것을 알리고 싶은 경우가 있습니다.
+
+즉, 일반적으로 사용자가 API에 요청을 보내는 것과는 반대로, **API**(또는 앱)가 **사용자의 시스템**(그들의 API나 앱)으로 **요청을 보내는** 상황을 의미합니다.
+
+이를 흔히 **웹훅(Webhook)**이라고 부릅니다.
+
+## 웹훅 스텝
+
+**코드에서** 웹훅으로 보낼 메시지, 즉 요청의 **바디(body)**를 정의하는 것이 일반적인 프로세스입니다.
+
+앱에서 해당 요청이나 이벤트를 전송할 **시점**을 정의합니다.
+
+**사용자**는 앱이 해당 요청을 보낼 **URL**을 정의합니다. (예: 웹 대시보드에서 설정)
+
+웹훅의 URL을 등록하는 방법과 이러한 요청을 실제로 전송하는 코드에 대한 모든 로직은 여러분에게 달려 있습니다. 원하는대로 **고유의 코드**를 작성하면 됩니다.
+
+## **FastAPI**와 OpenAPI로 웹훅 문서화하기
+
+**FastAPI**를 사용하여 OpenAPI와 함께 웹훅의 이름, 앱이 보낼 수 있는 HTTP 작업 유형(예: `POST`, `PUT` 등), 그리고 보낼 요청의 **바디**를 정의할 수 있습니다.
+
+이를 통해 사용자가 **웹훅** 요청을 수신할 **API 구현**을 훨씬 쉽게 할 수 있으며, 경우에 따라 사용자 API 코드의 일부를 자동 생성할 수도 있습니다.
+
+/// info
+
+웹훅은 OpenAPI 3.1.0 이상에서 지원되며, FastAPI `0.99.0` 이상 버전에서 사용할 수 있습니다.
+
+///
+
+## 웹훅이 포함된 앱 만들기
+
+**FastAPI** 애플리케이션을 만들 때, `webhooks` 속성을 사용하여 *웹훅*을 정의할 수 있습니다. 이는 `@app.webhooks.post()`와 같은 방식으로 *경로(path) 작업*을 정의하는 것과 비슷합니다.
+
+{* ../../docs_src/openapi_webhooks/tutorial001.py hl[9:13,36:53] *}
+
+이렇게 정의한 웹훅은 **OpenAPI** 스키마와 자동 **문서화 UI**에 표시됩니다.
+
+/// info
+
+`app.webhooks` 객체는 사실 `APIRouter`일 뿐이며, 여러 파일로 앱을 구성할 때 사용하는 것과 동일한 타입입니다.
+
+///
+
+웹훅에서는 실제 **경로(path)** (예: `/items/`)를 선언하지 않는 점에 유의해야 합니다. 여기서 전달하는 텍스트는 **식별자**로, 웹훅의 이름(이벤트 이름)입니다. 예를 들어, `@app.webhooks.post("new-subscription")`에서 웹훅 이름은 `new-subscription`입니다.
+
+이는 실제 **URL 경로**는 **사용자**가 다른 방법(예: 웹 대시보드)을 통해 지정하도록 기대되기 때문입니다.
+
+### 문서 확인하기
+
+이제 앱을 시작하고 http://127.0.0.1:8000/docs로 이동해 봅시다.
+
+문서에서 기존 *경로 작업*뿐만 아니라 **웹훅**도 표시된 것을 확인할 수 있습니다:
+
+get
동작 사용
+* get
작동 사용
+
+/// info | `@decorator` 정보
+
+이 `@something` 문법은 파이썬에서 "데코레이터"라 부릅니다.
-!!! info "`@decorator` 정보"
- 이 `@something` 문법은 파이썬에서 "데코레이터"라 부릅니다.
+마치 예쁜 장식용(Decorative) 모자처럼(개인적으로 이 용어가 여기서 유래한 것 같습니다) 함수 맨 위에 놓습니다.
- 함수 맨 위에 놓습니다. 마치 예쁜 장식용(Decorative) 모자처럼(개인적으로 이 용어가 여기서 유래한거 같습니다).
+"데코레이터"는 아래 있는 함수를 받아 그것으로 무언가를 합니다.
- "데코레이터" 아래 있는 함수를 받고 그걸 이용해 무언가 합니다.
+우리의 경우, 이 데코레이터는 **FastAPI**에게 아래 함수가 **경로** `/`의 `get` **작동**에 해당한다고 알려줍니다.
- 우리의 경우, 이 데코레이터는 **FastAPI**에게 아래 함수가 **경로** `/`에 해당하는 `get` **동작**하라고 알려줍니다.
+이것이 "**경로 작동 데코레이터**"입니다.
- 이것이 "**경로 동작 데코레이터**"입니다.
+///
-다른 동작도 쓸 수 있습니다:
+다른 작동도 사용할 수 있습니다:
* `@app.post()`
* `@app.put()`
* `@app.delete()`
-이국적인 것들도 있습니다:
+흔히 사용되지 않는 것들도 있습니다:
* `@app.options()`
* `@app.head()`
* `@app.patch()`
* `@app.trace()`
-!!! tip "팁"
- 각 동작(HTTP 메소드)을 원하는 대로 사용해도 됩니다.
+/// tip | 팁
+
+각 작동(HTTP 메소드)을 원하는 대로 사용해도 됩니다.
+
+**FastAPI**는 특정 의미를 강제하지 않습니다.
- **FastAPI**는 특정 의미를 강제하지 않습니다.
+여기서 정보는 지침서일뿐 강제사항이 아닙니다.
- 여기서 정보는 지침서일뿐 요구사항이 아닙니다.
+예를 들어 GraphQL을 사용하는 경우, 일반적으로 `POST` 작동만 사용하여 모든 행동을 수행합니다.
- 예를 들어 GraphQL을 사용할때 일반적으로 `POST` 동작만 사용하여 모든 행동을 수행합니다.
+///
-### 4 단계: **경로 동작 함수** 정의
+### 4 단계: **경로 작동 함수** 정의
-다음은 우리의 "**경로 동작 함수**"입니다:
+다음은 우리의 "**경로 작동 함수**"입니다:
* **경로**: 는 `/`입니다.
-* **동작**: 은 `get`입니다.
+* **작동**: 은 `get`입니다.
* **함수**: 는 "데코레이터" 아래에 있는 함수입니다 (`@app.get("/")` 아래).
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[7] *}
이것은 파이썬 함수입니다.
-`GET` 동작을 사용하여 URL "`/`"에 대한 요청을 받을 때마다 **FastAPI**에 의해 호출됩니다.
+URL "`/`"에 대한 `GET` 작동을 사용하는 요청을 받을 때마다 **FastAPI**에 의해 호출됩니다.
-위의 경우 `async` 함수입니다.
+위의 예시에서 이 함수는 `async`(비동기) 함수입니다.
---
-`async def` 대신 일반 함수로 정의할 수 있습니다:
+`async def`을 이용하는 대신 일반 함수로 정의할 수 있습니다:
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial003.py!}
-```
+{* ../../docs_src/first_steps/tutorial003.py hl[7] *}
+
+/// note | 참고
-!!! note 참고
- 차이점을 모르겠다면 [Async: *"In a hurry?"*](../async.md#in-a-hurry){.internal-link target=_blank}을 확인하세요.
+차이점을 모르겠다면 [Async: *"바쁘신 경우"*](../async.md#_1){.internal-link target=_blank}을 확인하세요.
+
+///
### 5 단계: 콘텐츠 반환
-```Python hl_lines="8"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[8] *}
`dict`, `list`, 단일값을 가진 `str`, `int` 등을 반환할 수 있습니다.
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/header-param-models.md b/docs/ko/docs/tutorial/header-param-models.md
new file mode 100644
index 000000000..bab7291e3
--- /dev/null
+++ b/docs/ko/docs/tutorial/header-param-models.md
@@ -0,0 +1,56 @@
+# 헤더 매개변수 모델
+
+관련 있는 **헤더 매개변수** 그룹이 있는 경우, **Pydantic 모델**을 생성하여 선언할 수 있습니다.
+
+이를 통해 **여러 위치**에서 **모델을 재사용** 할 수 있고 모든 매개변수에 대한 유효성 검사 및 메타데이터를 한 번에 선언할 수도 있습니다. 😎
+
+/// note | 참고
+
+이 기능은 FastAPI 버전 `0.115.0` 이후부터 지원됩니다. 🤓
+
+///
+
+## Pydantic 모델을 사용한 헤더 매개변수
+
+**Pydantic 모델**에 필요한 **헤더 매개변수**를 선언한 다음, 해당 매개변수를 `Header`로 선언합니다:
+
+{* ../../docs_src/header_param_models/tutorial001_an_py310.py hl[9:14,18] *}
+
+**FastAPI**는 요청에서 받은 **헤더**에서 **각 필드**에 대한 데이터를 **추출**하고 정의한 Pydantic 모델을 줍니다.
+
+## 문서 확인하기
+
+문서 UI `/docs`에서 필요한 헤더를 볼 수 있습니다:
+
+contact
필드매개변수 | 타입 | 설명 |
---|---|---|
name | str | 연락처 인물/조직의 식별명입니다. |
url | str | 연락처 정보가 담긴 URL입니다. URL 형식이어야 합니다. |
email | str | 연락처 인물/조직의 이메일 주소입니다. 이메일 주소 형식이어야 합니다. |
license_info
필드매개변수 | 타입 | 설명 |
---|---|---|
name | str | 필수 (license_info 가 설정된 경우). API에 사용된 라이선스 이름입니다. |
identifier | str | API에 대한 SPDX 라이선스 표현입니다. identifier 필드는 url 필드와 상호 배타적입니다. OpenAPI 3.1.0, FastAPI 0.99.0부터 사용 가능 |
url | str | API에 사용된 라이선스의 URL입니다. URL 형식이어야 합니다. |
kwargs
로도 알려진 키워드 인자(키-값 쌍)여야 함을 인지합니다. 기본값을 가지고 있지 않더라도 그렇습니다.
-```Python hl_lines="7"
-{!../../../docs_src/path_params_numeric_validations/tutorial003.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *}
## 숫자 검증: 크거나 같음
@@ -65,9 +60,7 @@
여기서 `ge=1`인 경우, `item_id`는 `1`보다 "크거나(`g`reater) 같은(`e`qual)" 정수형 숫자여야 합니다.
-```Python hl_lines="8"
-{!../../../docs_src/path_params_numeric_validations/tutorial004.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial004.py hl[8] *}
## 숫자 검증: 크거나 같음 및 작거나 같음
@@ -76,9 +69,7 @@
* `gt`: 크거나(`g`reater `t`han)
* `le`: 작거나 같은(`l`ess than or `e`qual)
-```Python hl_lines="9"
-{!../../../docs_src/path_params_numeric_validations/tutorial005.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial005.py hl[9] *}
## 숫자 검증: 부동소수, 크거나 및 작거나
@@ -90,9 +81,7 @@
lt
역시 마찬가지입니다.
-```Python hl_lines="11"
-{!../../../docs_src/path_params_numeric_validations/tutorial006.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial006.py hl[11] *}
## 요약
@@ -105,18 +94,24 @@
* `lt`: 작거나(`l`ess `t`han)
* `le`: 작거나 같은(`l`ess than or `e`qual)
-!!! info "정보"
- `Query`, `Path`, 그리고 나중에게 보게될 것들은 (여러분이 사용할 필요가 없는) 공통 `Param` 클래스의 서브 클래스입니다.
+/// info | 정보
+
+`Query`, `Path`, 그리고 나중에게 보게될 것들은 (여러분이 사용할 필요가 없는) 공통 `Param` 클래스의 서브 클래스입니다.
+
+그리고 이들 모두는 여태까지 본 추가 검증과 메타데이터의 동일한 모든 매개변수를 공유합니다.
+
+///
+
+/// note | 기술 세부사항
- 그리고 이들 모두는 여태까지 본 추가 검증과 메타데이터의 동일한 모든 매개변수를 공유합니다.
+`fastapi`에서 `Query`, `Path` 등을 임포트 할 때, 이것들은 실제로 함수입니다.
-!!! note "기술 세부사항"
- `fastapi`에서 `Query`, `Path` 등을 임포트 할 때, 이것들은 실제로 함수입니다.
+호출되면 동일한 이름의 클래스의 인스턴스를 반환합니다.
- 호출되면 동일한 이름의 클래스의 인스턴스를 반환합니다.
+즉, 함수인 `Query`를 임포트한 겁니다. 그리고 호출하면 `Query`라는 이름을 가진 클래스의 인스턴스를 반환합니다.
- 즉, 함수인 `Query`를 임포트한 겁니다. 그리고 호출하면 `Query`라는 이름을 가진 클래스의 인스턴스를 반환합니다.
+편집기에서 타입에 대한 오류를 표시하지 않도록 하기 위해 (클래스를 직접 사용하는 대신) 이러한 함수들이 있습니다.
- 편집기에서 타입에 대한 오류를 표시하지 않도록 하기 위해 (클래스를 직접 사용하는 대신) 이러한 함수들이 있습니다.
+이렇게 하면 오류를 무시하기 위한 사용자 설정을 추가하지 않고도 일반 편집기와 코딩 도구를 사용할 수 있습니다.
- 이렇게 하면 오류를 무시하기 위한 사용자 설정을 추가하지 않고도 일반 편집기와 코딩 도구를 사용할 수 있습니다.
+///
diff --git a/docs/ko/docs/tutorial/path-params.md b/docs/ko/docs/tutorial/path-params.md
index 5cf397e7a..b72787e0b 100644
--- a/docs/ko/docs/tutorial/path-params.md
+++ b/docs/ko/docs/tutorial/path-params.md
@@ -1,10 +1,8 @@
# 경로 매개변수
-파이썬 포맷 문자열이 사용하는 동일한 문법으로 "매개변수" 또는 "변수"를 경로에 선언할 수 있습니다:
+파이썬의 포맷 문자열 리터럴에서 사용되는 문법을 이용하여 경로 "매개변수" 또는 "변수"를 선언할 수 있습니다:
-```Python hl_lines="6-7"
-{!../../../docs_src/path_params/tutorial001.py!}
-```
+{* ../../docs_src/path_params/tutorial001.py hl[6:7] *}
경로 매개변수 `item_id`의 값은 함수의 `item_id` 인자로 전달됩니다.
@@ -18,14 +16,15 @@
파이썬 표준 타입 어노테이션을 사용하여 함수에 있는 경로 매개변수의 타입을 선언할 수 있습니다:
-```Python hl_lines="7"
-{!../../../docs_src/path_params/tutorial002.py!}
-```
+{* ../../docs_src/path_params/tutorial002.py hl[7] *}
+
+위의 예시에서, `item_id`는 `int`로 선언되었습니다.
+
+/// check | 확인
-지금과 같은 경우, `item_id`는 `int`로 선언 되었습니다.
+이 기능은 함수 내에서 오류 검사, 자동완성 등의 편집기 기능을 활용할 수 있게 해줍니다.
-!!! check "확인"
- 이 기능은 함수 내에서 오류 검사, 자동완성 등을 편집기를 지원합니다
+///
## 데이터 변환
@@ -35,14 +34,17 @@
{"item_id":3}
```
-!!! check "확인"
- 함수가 받은(반환도 하는) 값은 문자열 `"3"`이 아니라 파이썬 `int` 형인 `3`입니다.
+/// check | 확인
- 즉, 타입 선언을 하면 **FastAPI**는 자동으로 요청을 "파싱"합니다.
+함수가 받은(반환도 하는) 값은 문자열 `"3"`이 아니라 파이썬 `int` 형인 `3`입니다.
+
+즉, 타입 선언을 하면 **FastAPI**는 자동으로 요청을 "파싱"합니다.
+
+///
## 데이터 검증
-하지만 브라우저에서 http://127.0.0.1:8000/items/foo로 이동하면, 멋진 HTTP 오류를 볼 수 있습니다:
+하지만 브라우저에서 http://127.0.0.1:8000/items/foo로 이동하면, HTTP 오류가 잘 뜨는 것을 확인할 수 있습니다:
```JSON
{
@@ -61,14 +63,17 @@
경로 매개변수 `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 | 확인
-!!! check "확인"
- 즉, 파이썬 타입 선언을 하면 **FastAPI**는 데이터 검증을 합니다.
+즉, 파이썬 타입 선언을 하면 **FastAPI**는 데이터 검증을 합니다.
- 오류는 검증을 통과하지 못한 지점도 정확하게 명시합니다.
+오류에는 정확히 어느 지점에서 검증을 통과하지 못했는지 명시됩니다.
- 이는 API와 상호 작용하는 코드를 개발하고 디버깅하는 데 매우 유용합니다.
+이는 API와 상호 작용하는 코드를 개발하고 디버깅하는 데 매우 유용합니다.
+
+///
## 문서화
@@ -76,12 +81,15 @@
POST
에 관한MDN웹 문서 를 참고하기 바랍니다,.
+
+///
- 하지만 파일이 포함된 경우, `multipart/form-data`로 인코딩됩니다. `File`을 사용하였다면, **FastAPI**는 본문의 적합한 부분에서 파일을 가져와야 한다는 것을 인지합니다.
+/// warning | 경고
- 인코딩과 폼 필드에 대해 더 알고싶다면, POST
에 관한MDN웹 문서 를 참고하기 바랍니다,.
+다수의 `File` 과 `Form` 매개변수를 한 *경로 작동*에 선언하는 것이 가능하지만, 요청의 본문이 `application/json` 가 아닌 `multipart/form-data` 로 인코딩 되기 때문에 JSON으로 받아야하는 `Body` 필드를 함께 선언할 수는 없습니다.
-!!! warning "주의"
- 다수의 `File` 과 `Form` 매개변수를 한 *경로 작동*에 선언하는 것이 가능하지만, 요청의 본문이 `application/json` 가 아닌 `multipart/form-data` 로 인코딩 되기 때문에 JSON으로 받아야하는 `Body` 필드를 함께 선언할 수는 없습니다.
+이는 **FastAPI**의 한계가 아니라, HTTP 프로토콜에 의한 것입니다.
- 이는 **FastAPI**의 한계가 아니라, HTTP 프로토콜에 의한 것입니다.
+///
## 다중 파일 업로드
@@ -121,23 +136,27 @@ HTML의 폼들(``)이 서버에 데이터를 전송하는 방식은
이 기능을 사용하기 위해 , `bytes` 의 `List` 또는 `UploadFile` 를 선언하기 바랍니다:
-```Python hl_lines="10 15"
-{!../../../docs_src/request_files/tutorial002.py!}
-```
+{* ../../docs_src/request_files/tutorial002.py hl[10,15] *}
선언한대로, `bytes` 의 `list` 또는 `UploadFile` 들을 전송받을 것입니다.
-!!! note "참고"
- 2019년 4월 14일부터 Swagger UI가 하나의 폼 필드로 다수의 파일을 업로드하는 것을 지원하지 않습니다. 더 많은 정보를 원하면, #4276과 #3641을 참고하세요.
+/// note | 참고
+
+2019년 4월 14일부터 Swagger UI가 하나의 폼 필드로 다수의 파일을 업로드하는 것을 지원하지 않습니다. 더 많은 정보를 원하면, #4276과 #3641을 참고하세요.
+
+그럼에도, **FastAPI**는 표준 Open API를 사용해 이미 호환이 가능합니다.
+
+따라서 Swagger UI 또는 기타 그 외의 OpenAPI를 지원하는 툴이 다중 파일 업로드를 지원하는 경우, 이들은 **FastAPI**와 호환됩니다.
+
+///
- 그럼에도, **FastAPI**는 표준 Open API를 사용해 이미 호환이 가능합니다.
+/// note | 기술적 세부사항
- 따라서 Swagger UI 또는 기타 그 외의 OpenAPI를 지원하는 툴이 다중 파일 업로드를 지원하는 경우, 이들은 **FastAPI**와 호환됩니다.
+`from starlette.responses import HTMLResponse` 역시 사용할 수 있습니다.
-!!! note "기술적 세부사항"
- `from starlette.responses import HTMLResponse` 역시 사용할 수 있습니다.
+**FastAPI**는 개발자의 편의를 위해 `fastapi.responses` 와 동일한 `starlette.responses` 도 제공합니다. 하지만 대부분의 응답들은 Starlette로부터 직접 제공됩니다.
- **FastAPI**는 개발자의 편의를 위해 `fastapi.responses` 와 동일한 `starlette.responses` 도 제공합니다. 하지만 대부분의 응답들은 Starlette로부터 직접 제공됩니다.
+///
## 요약
diff --git a/docs/ko/docs/tutorial/request-form-models.md b/docs/ko/docs/tutorial/request-form-models.md
new file mode 100644
index 000000000..3316a93d5
--- /dev/null
+++ b/docs/ko/docs/tutorial/request-form-models.md
@@ -0,0 +1,78 @@
+# 폼 모델
+
+FastAPI에서 **Pydantic 모델**을 이용하여 **폼 필드**를 선언할 수 있습니다.
+
+/// info | 정보
+
+폼(Form)을 사용하려면, 먼저 `python-multipart`를 설치하세요.
+
+[가상 환경](../virtual-environments.md){.internal-link target=_blank}을 생성하고 활성화한 다음, 아래와 같이 설치할 수 있습니다:
+
+```console
+$ pip install python-multipart
+```
+
+///
+
+/// note | 참고
+
+이 기능은 FastAPI 버전 `0.113.0` 이후부터 지원됩니다. 🤓
+
+///
+
+## Pydantic 모델을 사용한 폼
+
+**폼 필드**로 받고 싶은 필드를 **Pydantic 모델**로 선언한 다음, 매개변수를 `Form`으로 선언하면 됩니다:
+
+{* ../../docs_src/request_form_models/tutorial001_an_py39.py hl[9:11,15] *}
+
+**FastAPI**는 요청에서 받은 **폼 데이터**에서 **각 필드**에 대한 데이터를 **추출**하고 정의한 Pydantic 모델을 줍니다.
+
+## 문서 확인하기
+
+문서 UI `/docs`에서 확인할 수 있습니다:
+
+POST
에 대한 MDN 웹 문서를 참조하세요.
+
+///
+
+/// warning | 경고
+
+*경로 작업*에서 여러 `Form` 매개변수를 선언할 수 있지만, JSON으로 수신할 것으로 예상되는 `Body` 필드와 함께 선언할 수 없습니다. 요청 본문은 `application/json` 대신에 `application/x-www-form-urlencoded`를 사용하여 인코딩되기 때문입니다.
+
+이는 **FastAPI**의 제한 사항이 아니며 HTTP 프로토콜의 일부입니다.
+
+///
+
+## 요약
+
+폼 데이터 입력 매개변수를 선언하려면 `Form`을 사용하세요.
diff --git a/docs/ko/docs/tutorial/response-model.md b/docs/ko/docs/tutorial/response-model.md
new file mode 100644
index 000000000..a71d649f9
--- /dev/null
+++ b/docs/ko/docs/tutorial/response-model.md
@@ -0,0 +1,214 @@
+# 응답 모델
+
+어떤 *경로 작동*이든 매개변수 `response_model`를 사용하여 응답을 위한 모델을 선언할 수 있습니다:
+
+* `@app.get()`
+* `@app.post()`
+* `@app.put()`
+* `@app.delete()`
+* 기타.
+
+{* ../../docs_src/response_model/tutorial001.py hl[17] *}
+
+/// note | 참고
+
+`response_model`은 "데코레이터" 메소드(`get`, `post`, 등)의 매개변수입니다. 모든 매개변수들과 본문(body)처럼 *경로 작동 함수*가 아닙니다.
+
+///
+
+Pydantic 모델 어트리뷰트를 선언한 것과 동일한 타입을 수신하므로 Pydantic 모델이 될 수 있지만, `List[Item]`과 같이 Pydantic 모델들의 `list`일 수도 있습니다.
+
+FastAPI는 이 `response_model`를 사용하여:
+
+* 출력 데이터를 타입 선언으로 변환.
+* 데이터 검증.
+* OpenAPI *경로 작동*의 응답에 JSON 스키마 추가.
+* 자동 생성 문서 시스템에 사용.
+
+하지만 가장 중요한 것은:
+
+* 해당 모델의 출력 데이터 제한. 이것이 얼마나 중요한지 아래에서 볼 것입니다.
+
+/// note | 기술 세부사항
+
+응답 모델은 함수의 타입 어노테이션 대신 이 매개변수로 선언하는데, 경로 함수가 실제 응답 모델을 반환하지 않고 `dict`, 데이터베이스 객체나 기타 다른 모델을 `response_model`을 사용하여 필드 제한과 직렬화를 수행하고 반환할 수 있기 때문입니다
+
+///
+
+## 동일한 입력 데이터 반환
+
+여기서 우리는 평문 비밀번호를 포함하는 `UserIn` 모델을 선언합니다:
+
+{* ../../docs_src/response_model/tutorial002.py hl[9,11] *}
+
+그리고 이 모델을 사용하여 입력을 선언하고 같은 모델로 출력을 선언합니다:
+
+{* ../../docs_src/response_model/tutorial002.py hl[17:18] *}
+
+이제 브라우저가 비밀번호로 사용자를 만들 때마다 API는 응답으로 동일한 비밀번호를 반환합니다.
+
+이 경우, 사용자가 스스로 비밀번호를 발신했기 때문에 문제가 되지 않을 수 있습니다.
+
+그러나 동일한 모델을 다른 *경로 작동*에서 사용할 경우, 모든 클라이언트에게 사용자의 비밀번호를 발신할 수 있습니다.
+
+/// danger | 위험
+
+절대로 사용자의 평문 비밀번호를 저장하거나 응답으로 발신하지 마십시오.
+
+///
+
+## 출력 모델 추가
+
+대신 평문 비밀번호로 입력 모델을 만들고 해당 비밀번호 없이 출력 모델을 만들 수 있습니다:
+
+{* ../../docs_src/response_model/tutorial003.py hl[9,11,16] *}
+
+여기서 *경로 작동 함수*가 비밀번호를 포함하는 동일한 입력 사용자를 반환할지라도:
+
+{* ../../docs_src/response_model/tutorial003.py hl[24] *}
+
+...`response_model`을 `UserOut` 모델로 선언했기 때문에 비밀번호를 포함하지 않습니다:
+
+{* ../../docs_src/response_model/tutorial003.py hl[22] *}
+
+따라서 **FastAPI**는 출력 모델에서 선언하지 않은 모든 데이터를 (Pydantic을 사용하여) 필터링합니다.
+
+## 문서에서 보기
+
+자동 생성 문서를 보면 입력 모델과 출력 모델이 각자의 JSON 스키마를 가지고 있음을 확인할 수 있습니다:
+
+- FastAPI framework, high performance, easy to learn, fast to code, ready for production + FastAPI framework, zeer goede prestaties, eenvoudig te leren, snel te programmeren, klaar voor productie
-
-
+
+
-
-
+
+
@@ -25,27 +27,26 @@
---
-**Documentation**: https://fastapi.tiangolo.com
+**Documentatie**: https://fastapi.tiangolo.com
-**Source Code**: https://github.com/tiangolo/fastapi
+**Broncode**: 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:
+FastAPI is een modern, snel (zeer goede prestaties), web framework voor het bouwen van API's in Python, gebruikmakend van standaard Python type-hints.
-* **Fast**: Very high performance, on par with **NodeJS** and **Go** (thanks to Starlette and Pydantic). [One of the fastest Python frameworks available](#performance).
+De belangrijkste kenmerken zijn:
-* **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.
+* **Snel**: Zeer goede prestaties, vergelijkbaar met **NodeJS** en **Go** (dankzij Starlette en Pydantic). [Een van de snelste beschikbare Python frameworks](#prestaties).
+* **Snel te programmeren**: Verhoog de snelheid om functionaliteit te ontwikkelen met ongeveer 200% tot 300%. *
+* **Minder bugs**: Verminder ongeveer 40% van de door mensen (ontwikkelaars) veroorzaakte fouten. *
+* **Intuïtief**: Buitengewoon goede ondersteuning voor editors. Overal automische code aanvulling. Minder tijd kwijt aan debuggen.
+* **Eenvoudig**: Ontworpen om gemakkelijk te gebruiken en te leren. Minder tijd nodig om documentatie te lezen.
+* **Kort**: Minimaliseer codeduplicatie. Elke parameterdeclaratie ondersteunt meerdere functionaliteiten. Minder bugs.
+* **Robust**: Code gereed voor productie. Met automatische interactieve documentatie.
+* **Standards-based**: Gebaseerd op (en volledig verenigbaar met) open standaarden voor API's: OpenAPI (voorheen bekend als Swagger) en JSON Schema.
-* estimation based on tests on an internal development team, building production applications.
+* schatting op basis van testen met een intern ontwikkelteam en bouwen van productieapplicaties.
## Sponsors
@@ -62,94 +63,88 @@ The key features are:
-Other sponsors
+Overige sponsoren
-## Opinions
+## Meningen
-"_[...] 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._"
+"_[...] Ik gebruik **FastAPI** heel vaak tegenwoordig. [...] Ik ben van plan om het te gebruiken voor alle **ML-services van mijn team bij Microsoft**. Sommige van deze worden geïntegreerd in het kernproduct van **Windows** en sommige **Office**-producten._"
-
async def
...async def
...uvicorn main:app --reload
...fastapi dev main.py
...email_validator
- voor email validatie.
+
+Gebruikt door Starlette:
-## Performance
+* httpx
- Vereist indien je de `TestClient` wil gebruiken.
+* jinja2
- Vereist als je de standaard templateconfiguratie wil gebruiken.
+* python-multipart
- Vereist indien je "parsen" van formulieren wil ondersteunen met `requests.form()`.
-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). (*)
+Gebruikt door FastAPI / Starlette:
-To understand more about it, see the section Benchmarks.
+* uvicorn
- voor de server die jouw applicatie laadt en bedient.
+* `fastapi-cli` - om het `fastapi` commando te voorzien.
-## Optional Dependencies
+### Zonder `standard` Afhankelijkheden
-Used by Pydantic:
+Indien je de optionele `standard` afhankelijkheden niet wenst te installeren, kan je installeren met `pip install fastapi` in plaats van `pip install "fastapi[standard]"`.
-* ujson
- for faster JSON "parsing".
-* email_validator
- for email validation.
+### Bijkomende Optionele Afhankelijkheden
-Used by Starlette:
+Er zijn nog een aantal bijkomende afhankelijkheden die je eventueel kan installeren.
-* 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`.
+Bijkomende optionele afhankelijkheden voor Pydantic:
-Used by FastAPI / Starlette:
+* pydantic-settings
- voor het beheren van settings.
+* pydantic-extra-types
- voor extra data types die gebruikt kunnen worden met Pydantic.
-* uvicorn
- for the server that loads and serves your application.
-* orjson
- Required if you want to use `ORJSONResponse`.
+Bijkomende optionele afhankelijkheden voor FastAPI:
-You can install all of these with `pip install "fastapi[all]"`.
+* orjson
- Vereist indien je `ORJSONResponse` wil gebruiken.
+* ujson
- Vereist indien je `UJSONResponse` wil gebruiken.
-## License
+## Licentie
-This project is licensed under the terms of the MIT license.
+Dit project is gelicenseerd onder de voorwaarden van de MIT licentie.
diff --git a/docs/nl/docs/python-types.md b/docs/nl/docs/python-types.md
new file mode 100644
index 000000000..fb8b1e5fd
--- /dev/null
+++ b/docs/nl/docs/python-types.md
@@ -0,0 +1,587 @@
+# Introductie tot Python Types
+
+Python biedt ondersteuning voor optionele "type hints" (ook wel "type annotaties" genoemd).
+
+Deze **"type hints"** of annotaties zijn een speciale syntax waarmee het type van een variabele kan worden gedeclareerd.
+
+Door types voor je variabelen te declareren, kunnen editors en hulpmiddelen je beter ondersteunen.
+
+Dit is slechts een **korte tutorial/opfrisser** over Python type hints. Het behandelt enkel het minimum dat nodig is om ze te gebruiken met **FastAPI**... en dat is relatief weinig.
+
+**FastAPI** is helemaal gebaseerd op deze type hints, ze geven veel voordelen.
+
+Maar zelfs als je **FastAPI** nooit gebruikt, heb je er baat bij om er iets over te leren.
+
+/// note
+
+Als je een Python expert bent en alles al weet over type hints, sla dan dit hoofdstuk over.
+
+///
+
+## Motivatie
+
+Laten we beginnen met een eenvoudig voorbeeld:
+
+{* ../../docs_src/python_types/tutorial001.py *}
+
+
+Het aanroepen van dit programma leidt tot het volgende resultaat:
+
+```
+John Doe
+```
+
+De functie voert het volgende uit:
+
+* Neem een `first_name` en een `last_name`
+* Converteer de eerste letter van elk naar een hoofdletter met `title()`.
+``
+* Voeg samen met een spatie in het midden.
+
+{* ../../docs_src/python_types/tutorial001.py hl[2] *}
+
+
+### Bewerk het
+
+Dit is een heel eenvoudig programma.
+
+Maar stel je nu voor dat je het vanaf nul zou moeten maken.
+
+Op een gegeven moment zou je aan de definitie van de functie zijn begonnen, je had de parameters klaar...
+
+Maar dan moet je “die methode die de eerste letter naar hoofdletters converteert” aanroepen.
+
+Was het `upper`? Was het `uppercase`? `first_uppercase`? `capitalize`?
+
+Dan roep je de hulp in van je oude programmeursvriend, (automatische) code aanvulling in je editor.
+
+Je typt de eerste parameter van de functie, `first_name`, dan een punt (`.`) en drukt dan op `Ctrl+Spatie` om de aanvulling te activeren.
+
+Maar helaas krijg je niets bruikbaars:
+
+ujson
- dla szybszego "parsowania" danych JSON.
-* email_validator
- dla walidacji adresów email.
+* email-validator
- dla walidacji adresów email.
Używane przez Starlette:
* httpx
- Wymagane jeżeli chcesz korzystać z `TestClient`.
* aiofiles
- Wymagane jeżeli chcesz korzystać z `FileResponse` albo `StaticFiles`.
* jinja2
- Wymagane jeżeli chcesz używać domyślnej konfiguracji szablonów.
-* python-multipart
- Wymagane jeżelich chcesz wsparcie "parsowania" formularzy, używając `request.form()`.
+* python-multipart
- Wymagane jeżelich chcesz wsparcie "parsowania" formularzy, używając `request.form()`.
* itsdangerous
- Wymagany dla wsparcia `SessionMiddleware`.
* pyyaml
- Wymagane dla wsparcia `SchemaGenerator` z Starlette (z FastAPI prawdopodobnie tego nie potrzebujesz).
* graphene
- Wymagane dla wsparcia `GraphQLApp`.
-* ujson
- Wymagane jeżeli chcesz korzystać z `UJSONResponse`.
Używane przez FastAPI / Starlette:
* uvicorn
- jako serwer, który ładuje i obsługuje Twoją aplikację.
* orjson
- Wymagane jeżeli chcesz używać `ORJSONResponse`.
+* ujson
- Wymagane jeżeli chcesz korzystać z `UJSONResponse`.
Możesz zainstalować wszystkie te aplikacje przy pomocy `pip install fastapi[all]`.
diff --git a/docs/pl/docs/tutorial/first-steps.md b/docs/pl/docs/tutorial/first-steps.md
index 9406d703d..8fa4c75ad 100644
--- a/docs/pl/docs/tutorial/first-steps.md
+++ b/docs/pl/docs/tutorial/first-steps.md
@@ -2,9 +2,7 @@
Najprostszy plik FastAPI może wyglądać tak:
-```Python
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py *}
Skopiuj to do pliku `main.py`.
@@ -24,12 +22,15 @@ $ uvicorn main:app --reload
get
-!!! info "`@decorator` Info"
- Składnia `@something` jest w Pythonie nazywana "dekoratorem".
+/// info | `@decorator` Info
- Umieszczasz to na szczycie funkcji. Jak ładną ozdobną czapkę (chyba stąd wzięła się nazwa).
+Składnia `@something` jest w Pythonie nazywana "dekoratorem".
- "Dekorator" przyjmuje funkcję znajdującą się poniżej jego i coś z nią robi.
+Umieszczasz to na szczycie funkcji. Jak ładną ozdobną czapkę (chyba stąd wzięła się nazwa).
- W naszym przypadku dekorator mówi **FastAPI**, że poniższa funkcja odpowiada **ścieżce** `/` z **operacją** `get`.
+"Dekorator" przyjmuje funkcję znajdującą się poniżej jego i coś z nią robi.
- Jest to "**dekorator operacji na ścieżce**".
+W naszym przypadku dekorator mówi **FastAPI**, że poniższa funkcja odpowiada **ścieżce** `/` z **operacją** `get`.
+
+Jest to "**dekorator operacji na ścieżce**".
+
+///
Możesz również użyć innej operacji:
@@ -275,14 +276,17 @@ Oraz tych bardziej egzotycznych:
* `@app.patch()`
* `@app.trace()`
-!!! tip
- Możesz dowolnie używać każdej operacji (metody HTTP).
+/// tip
+
+Możesz dowolnie używać każdej operacji (metody HTTP).
- **FastAPI** nie narzuca żadnego konkretnego znaczenia.
+**FastAPI** nie narzuca żadnego konkretnego znaczenia.
- Informacje tutaj są przedstawione jako wskazówka, a nie wymóg.
+Informacje tutaj są przedstawione jako wskazówka, a nie wymóg.
- Na przykład, używając GraphQL, normalnie wykonujesz wszystkie akcje używając tylko operacji `POST`.
+Na przykład, używając GraphQL, normalnie wykonujesz wszystkie akcje używając tylko operacji `POST`.
+
+///
### Krok 4: zdefiniuj **funkcję obsługującą ścieżkę**
@@ -292,9 +296,7 @@ To jest nasza "**funkcja obsługująca ścieżkę**":
* **operacja**: to `get`.
* **funkcja**: to funkcja poniżej "dekoratora" (poniżej `@app.get("/")`).
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[7] *}
Jest to funkcja Python.
@@ -306,18 +308,17 @@ W tym przypadku jest to funkcja "asynchroniczna".
Możesz również zdefiniować to jako normalną funkcję zamiast `async def`:
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial003.py!}
-```
+{* ../../docs_src/first_steps/tutorial003.py hl[7] *}
+
+/// note
-!!! note
- Jeśli nie znasz różnicy, sprawdź [Async: *"In a hurry?"*](/async/#in-a-hurry){.internal-link target=_blank}.
+Jeśli nie znasz różnicy, sprawdź [Async: *"In a hurry?"*](../async.md#in-a-hurry){.internal-link target=_blank}.
+
+///
### Krok 5: zwróć zawartość
-```Python hl_lines="8"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[8] *}
Możesz zwrócić `dict`, `list`, pojedynczą wartość jako `str`, `int`, itp.
diff --git a/docs/pl/docs/tutorial/index.md b/docs/pl/docs/tutorial/index.md
index ed8752a95..66f7c6d62 100644
--- a/docs/pl/docs/tutorial/index.md
+++ b/docs/pl/docs/tutorial/index.md
@@ -1,4 +1,4 @@
-# Samouczek - Wprowadzenie
+# Samouczek
Ten samouczek pokaże Ci, krok po kroku, jak używać większości funkcji **FastAPI**.
@@ -52,22 +52,25 @@ $ pip install "fastapi[all]"
...wliczając w to `uvicorn`, który będzie służył jako serwer wykonujacy Twój kod.
-!!! note
- Możesz również wykonać instalację "krok po kroku".
+/// note
- Prawdopodobnie zechcesz to zrobić, kiedy będziesz wdrażać swoją aplikację w środowisku produkcyjnym:
+Możesz również wykonać instalację "krok po kroku".
- ```
- pip install fastapi
- ```
+Prawdopodobnie zechcesz to zrobić, kiedy będziesz wdrażać swoją aplikację w środowisku produkcyjnym:
- Zainstaluj też `uvicorn`, który będzie służył jako serwer:
+```
+pip install fastapi
+```
+
+Zainstaluj też `uvicorn`, który będzie służył jako serwer:
+
+```
+pip install "uvicorn[standard]"
+```
- ```
- pip install "uvicorn[standard]"
- ```
+Tak samo możesz zainstalować wszystkie dodatkowe biblioteki, których chcesz użyć.
- Tak samo możesz zainstalować wszystkie dodatkowe biblioteki, których chcesz użyć.
+///
## Zaawansowany poradnik
diff --git a/docs/pl/mkdocs.yml b/docs/pl/mkdocs.yml
index af68f1b74..de18856f4 100644
--- a/docs/pl/mkdocs.yml
+++ b/docs/pl/mkdocs.yml
@@ -1,160 +1 @@
-site_name: FastAPI
-site_description: FastAPI framework, high performance, easy to learn, fast to code, ready for production
-site_url: https://fastapi.tiangolo.com/pl/
-theme:
- name: material
- custom_dir: overrides
- palette:
- - media: '(prefers-color-scheme: light)'
- scheme: default
- primary: teal
- accent: amber
- toggle:
- icon: material/lightbulb
- name: Switch to light mode
- - media: '(prefers-color-scheme: dark)'
- scheme: slate
- primary: teal
- accent: amber
- toggle:
- icon: material/lightbulb-outline
- name: Switch to dark mode
- features:
- - search.suggest
- - search.highlight
- - content.tabs.link
- icon:
- repo: fontawesome/brands/github-alt
- logo: https://fastapi.tiangolo.com/img/icon-white.svg
- favicon: https://fastapi.tiangolo.com/img/favicon.png
- language: pl
-repo_name: tiangolo/fastapi
-repo_url: https://github.com/tiangolo/fastapi
-edit_uri: ''
-plugins:
-- search
-- markdownextradata:
- data: data
-nav:
-- FastAPI: index.md
-- Languages:
- - en: /
- - az: /az/
- - cs: /cs/
- - de: /de/
- - em: /em/
- - es: /es/
- - fa: /fa/
- - fr: /fr/
- - he: /he/
- - hy: /hy/
- - id: /id/
- - it: /it/
- - ja: /ja/
- - ko: /ko/
- - nl: /nl/
- - pl: /pl/
- - pt: /pt/
- - ru: /ru/
- - sq: /sq/
- - sv: /sv/
- - ta: /ta/
- - tr: /tr/
- - uk: /uk/
- - zh: /zh/
-- Samouczek:
- - tutorial/index.md
- - tutorial/first-steps.md
-markdown_extensions:
-- toc:
- permalink: true
-- markdown.extensions.codehilite:
- guess_lang: false
-- mdx_include:
- base_path: docs
-- admonition
-- codehilite
-- extra
-- pymdownx.superfences:
- custom_fences:
- - name: mermaid
- class: mermaid
- format: !!python/name:pymdownx.superfences.fence_code_format ''
-- pymdownx.tabbed:
- alternate_style: true
-- attr_list
-- md_in_html
-extra:
- analytics:
- provider: google
- property: G-YNEVN69SC3
- social:
- - icon: fontawesome/brands/github-alt
- link: https://github.com/tiangolo/fastapi
- - icon: fontawesome/brands/discord
- link: https://discord.gg/VQjSZaeJmf
- - icon: fontawesome/brands/twitter
- link: https://twitter.com/fastapi
- - icon: fontawesome/brands/linkedin
- link: https://www.linkedin.com/in/tiangolo
- - icon: fontawesome/brands/dev
- link: https://dev.to/tiangolo
- - icon: fontawesome/brands/medium
- link: https://medium.com/@tiangolo
- - icon: fontawesome/solid/globe
- link: https://tiangolo.com
- alternate:
- - link: /
- name: en - English
- - link: /az/
- name: az
- - link: /cs/
- name: cs
- - link: /de/
- name: de
- - link: /em/
- name: 😉
- - link: /es/
- name: es - español
- - link: /fa/
- name: fa
- - link: /fr/
- name: fr - français
- - link: /he/
- name: he
- - link: /hy/
- name: hy
- - link: /id/
- name: id
- - link: /it/
- name: it - italiano
- - link: /ja/
- name: ja - 日本語
- - link: /ko/
- name: ko - 한국어
- - link: /nl/
- name: nl
- - link: /pl/
- name: pl
- - link: /pt/
- name: pt - português
- - link: /ru/
- name: ru - русский язык
- - link: /sq/
- name: sq - shqip
- - link: /sv/
- name: sv - svenska
- - link: /ta/
- name: ta - தமிழ்
- - link: /tr/
- name: tr - Türkçe
- - link: /uk/
- name: uk - українська мова
- - link: /zh/
- name: zh - 汉语
-extra_css:
-- https://fastapi.tiangolo.com/css/termynal.css
-- https://fastapi.tiangolo.com/css/custom.css
-extra_javascript:
-- https://fastapi.tiangolo.com/js/termynal.js
-- https://fastapi.tiangolo.com/js/custom.js
+INHERIT: ../en/mkdocs.yml
diff --git a/docs/pl/overrides/.gitignore b/docs/pl/overrides/.gitignore
deleted file mode 100644
index e69de29bb..000000000
diff --git a/docs/pt/docs/about/index.md b/docs/pt/docs/about/index.md
new file mode 100644
index 000000000..1f42e8831
--- /dev/null
+++ b/docs/pt/docs/about/index.md
@@ -0,0 +1,3 @@
+# Sobre
+
+Sobre o FastAPI, seus padrões, inspirações e muito mais. 🤓
diff --git a/docs/pt/docs/advanced/additional-responses.md b/docs/pt/docs/advanced/additional-responses.md
new file mode 100644
index 000000000..1060d18af
--- /dev/null
+++ b/docs/pt/docs/advanced/additional-responses.md
@@ -0,0 +1,247 @@
+# Retornos Adicionais no OpenAPI
+
+/// warning | Aviso
+
+Este é um tema bem avançado.
+
+Se você está começando com o **FastAPI**, provavelmente você não precisa disso.
+
+///
+
+Você pode declarar retornos adicionais, com códigos de status adicionais, media types, descrições, etc.
+
+Essas respostas adicionais serão incluídas no esquema do OpenAPI, e também aparecerão na documentação da API.
+
+Porém para as respostas adicionais, você deve garantir que está retornando um `Response` como por exemplo o `JSONResponse` diretamente, junto com o código de status e o conteúdo.
+
+## Retorno Adicional com `model`
+
+Você pode fornecer o parâmetro `responses` aos seus *decoradores de caminho*.
+
+Este parâmetro recebe um `dict`, as chaves são os códigos de status para cada retorno, como por exemplo `200`, e os valores são um outro `dict` com a informação de cada um deles.
+
+Cada um desses `dict` de retorno pode ter uma chave `model`, contendo um modelo do Pydantic, assim como o `response_model`.
+
+O **FastAPI** pegará este modelo, gerará o esquema JSON dele e incluirá no local correto do OpenAPI.
+
+Por exemplo, para declarar um outro retorno com o status code `404` e um modelo do Pydantic chamado `Message`, você pode escrever:
+
+{* ../../docs_src/additional_responses/tutorial001.py hl[18,22] *}
+
+/// note | Nota
+
+Lembre-se que você deve retornar o `JSONResponse` diretamente.
+
+///
+
+/// info | Informação
+
+A chave `model` não é parte do OpenAPI.
+
+O **FastAPI** pegará o modelo do Pydantic, gerará o `JSON Schema`, e adicionará no local correto.
+
+O local correto é:
+
+* Na chave `content`, que tem como valor um outro objeto JSON (`dict`) que contém:
+ * Uma chave com o media type, como por exemplo `application/json`, que contém como valor um outro objeto JSON, contendo::
+ * Uma chave `schema`, que contém como valor o JSON Schema do modelo, sendo este o local correto.
+ * O **FastAPI** adiciona aqui a referência dos esquemas JSON globais que estão localizados em outro lugar, ao invés de incluí-lo diretamente. Deste modo, outras aplicações e clientes podem utilizar estes esquemas JSON diretamente, fornecer melhores ferramentas de geração de código, etc.
+
+///
+
+O retorno gerado no OpenAI para esta *operação de caminho* será:
+
+```JSON hl_lines="3-12"
+{
+ "responses": {
+ "404": {
+ "description": "Additional Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Message"
+ }
+ }
+ }
+ },
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Item"
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ }
+}
+```
+
+Os esquemas são referenciados em outro local dentro do esquema OpenAPI:
+
+```JSON hl_lines="4-16"
+{
+ "components": {
+ "schemas": {
+ "Message": {
+ "title": "Message",
+ "required": [
+ "message"
+ ],
+ "type": "object",
+ "properties": {
+ "message": {
+ "title": "Message",
+ "type": "string"
+ }
+ }
+ },
+ "Item": {
+ "title": "Item",
+ "required": [
+ "id",
+ "value"
+ ],
+ "type": "object",
+ "properties": {
+ "id": {
+ "title": "Id",
+ "type": "string"
+ },
+ "value": {
+ "title": "Value",
+ "type": "string"
+ }
+ }
+ },
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": [
+ "loc",
+ "msg",
+ "type"
+ ],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "msg": {
+ "title": "Message",
+ "type": "string"
+ },
+ "type": {
+ "title": "Error Type",
+ "type": "string"
+ }
+ }
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/ValidationError"
+ }
+ }
+ }
+ }
+ }
+ }
+}
+```
+
+## Media types adicionais para o retorno principal
+
+Você pode utilizar o mesmo parâmetro `responses` para adicionar diferentes media types para o mesmo retorno principal.
+
+Por exemplo, você pode adicionar um media type adicional de `image/png`, declarando que a sua *operação de caminho* pode retornar um objeto JSON (com o media type `application/json`) ou uma imagem PNG:
+
+{* ../../docs_src/additional_responses/tutorial002.py hl[19:24,28] *}
+
+/// note | Nota
+
+Note que você deve retornar a imagem utilizando um `FileResponse` diretamente.
+
+///
+
+/// info | Informação
+
+A menos que você especifique um media type diferente explicitamente em seu parâmetro `responses`, o FastAPI assumirá que o retorno possui o mesmo media type contido na classe principal de retorno (padrão `application/json`).
+
+Porém se você especificou uma classe de retorno com o valor `None` como media type, o FastAPI utilizará `application/json` para qualquer retorno adicional que possui um modelo associado.
+
+///
+
+## Combinando informações
+
+Você também pode combinar informações de diferentes lugares, incluindo os parâmetros `response_model`, `status_code`, e `responses`.
+
+Você pode declarar um `response_model`, utilizando o código de status padrão `200` (ou um customizado caso você precise), e depois adicionar informações adicionais para esse mesmo retorno em `responses`, diretamente no esquema OpenAPI.
+
+O **FastAPI** manterá as informações adicionais do `responses`, e combinará com o esquema JSON do seu modelo.
+
+Por exemplo, você pode declarar um retorno com o código de status `404` que utiliza um modelo do Pydantic que possui um `description` customizado.
+
+E um retorno com o código de status `200` que utiliza o seu `response_model`, porém inclui um `example` customizado:
+
+{* ../../docs_src/additional_responses/tutorial003.py hl[20:31] *}
+
+Isso será combinado e incluído em seu OpenAPI, e disponibilizado na documentação da sua API:
+
+uvicorn main:app --reload
...fastapi dev main.py
...email-validator
- para validação de email.
+
+Utilizado pelo Starlette:
+
+* httpx
- Obrigatório caso você queira utilizar o `TestClient`.
+* jinja2
- Obrigatório se você quer utilizar a configuração padrão de templates.
+* python-multipart
- Obrigatório se você deseja suporte a "parsing" de formulário, com `request.form()`.
+
+Utilizado pelo FastAPI / Starlette:
+
+* uvicorn
- para o servidor que carrega e serve a sua aplicação. Isto inclui `uvicorn[standard]`, que inclui algumas dependências (e.g. `uvloop`) necessárias para servir em alta performance.
+* `fastapi-cli` - que disponibiliza o comando `fastapi`.
-## Dependências opcionais
+### Sem as dependências `standard`
-Usados por Pydantic:
+Se você não deseja incluir as dependências opcionais `standard`, você pode instalar utilizando `pip install fastapi` ao invés de `pip install "fastapi[standard]"`.
-* ujson
- para JSON mais rápido "parsing".
-* email_validator
- para validação de email.
+### Dpendências opcionais adicionais
-Usados por Starlette:
+Existem algumas dependências adicionais que você pode querer instalar.
-* httpx
- Necessário se você quiser utilizar o `TestClient`.
-* jinja2
- Necessário se você quiser utilizar a configuração padrão de templates.
-* python-multipart
- Necessário se você quiser suporte com "parsing" de formulário, com `request.form()`.
-* itsdangerous
- Necessário para suporte a `SessionMiddleware`.
-* pyyaml
- Necessário para suporte a `SchemaGenerator` da Starlette (você provavelmente não precisará disso com o FastAPI).
-* graphene
- Necessário para suporte a `GraphQLApp`.
-* ujson
- Necessário se você quer utilizar `UJSONResponse`.
+Dependências opcionais adicionais do Pydantic:
-Usados por FastAPI / Starlette:
+* pydantic-settings
- para gerenciamento de configurações.
+* pydantic-extra-types
- tipos extras para serem utilizados com o Pydantic.
-* uvicorn
- para o servidor que carrega e serve sua aplicação.
-* orjson
- Necessário se você quer utilizar `ORJSONResponse`.
+Dependências opcionais adicionais do FastAPI:
-Você pode instalar todas essas dependências com `pip install fastapi[all]`.
+* orjson
- Obrigatório se você deseja utilizar o `ORJSONResponse`.
+* ujson
- Obrigatório se você deseja utilizar o `UJSONResponse`.
## Licença
diff --git a/docs/pt/docs/learn/index.md b/docs/pt/docs/learn/index.md
new file mode 100644
index 000000000..b9a7f5972
--- /dev/null
+++ b/docs/pt/docs/learn/index.md
@@ -0,0 +1,5 @@
+# Aprender
+
+Nesta parte da documentação encontramos as seções introdutórias e os tutoriais para aprendermos como usar o **FastAPI**.
+
+Nós poderíamos considerar isto um **livro**, **curso**, a maneira **oficial** e recomendada de aprender o FastAPI. 😎
diff --git a/docs/pt/docs/project-generation.md b/docs/pt/docs/project-generation.md
index c98bd069d..e5c935fd2 100644
--- a/docs/pt/docs/project-generation.md
+++ b/docs/pt/docs/project-generation.md
@@ -14,7 +14,7 @@ GitHub: **FastAPI** Python:
+* _Backend_ **FastAPI** Python:
* **Rápido**: Alta performance, no nível de **NodeJS** e **Go** (graças ao Starlette e Pydantic).
* **Intuitivo**: Ótimo suporte de editor. _Auto-Complete_ em todo lugar. Menos tempo _debugando_.
* **Fácil**: Projetado para ser fácil de usar e aprender. Menos tempo lendo documentações.
diff --git a/docs/pt/docs/python-types.md b/docs/pt/docs/python-types.md
index 9f12211c7..90a361f40 100644
--- a/docs/pt/docs/python-types.md
+++ b/docs/pt/docs/python-types.md
@@ -1,28 +1,28 @@
# Introdução aos tipos Python
-**Python 3.6 +** tem suporte para "type hints" opcionais.
+O Python possui suporte para "dicas de tipo" ou "type hints" (também chamado de "anotações de tipo" ou "type annotations")
-Esses **"type hints"** são uma nova sintaxe (desde Python 3.6+) que permite declarar o tipo de uma variável.
+Esses **"type hints"** são uma sintaxe especial que permite declarar o tipo de uma variável.
Ao declarar tipos para suas variáveis, editores e ferramentas podem oferecer um melhor suporte.
-Este é apenas um **tutorial rápido / atualização** sobre type hints Python. Ele cobre apenas o mínimo necessário para usá-los com o **FastAPI** ... que é realmente muito pouco.
+Este é apenas um **tutorial rápido / atualização** sobre type hints do Python. Ele cobre apenas o mínimo necessário para usá-los com o **FastAPI**... que é realmente muito pouco.
O **FastAPI** é baseado nesses type hints, eles oferecem muitas vantagens e benefícios.
Mas mesmo que você nunca use o **FastAPI**, você se beneficiaria de aprender um pouco sobre eles.
-!!! note "Nota"
- Se você é um especialista em Python e já sabe tudo sobre type hints, pule para o próximo capítulo.
+/// note | Nota
+Se você é um especialista em Python e já sabe tudo sobre type hints, pule para o próximo capítulo.
+
+///
## Motivação
Vamos começar com um exemplo simples:
-```Python
-{!../../../docs_src/python_types/tutorial001.py!}
-```
+{* ../../docs_src/python_types/tutorial001.py *}
A chamada deste programa gera:
@@ -33,12 +33,10 @@ John Doe
A função faz o seguinte:
* Pega um `first_name` e `last_name`.
-* Converte a primeira letra de cada uma em maiúsculas com `title ()`.
-* Concatena com um espaço no meio.
+* Converte a primeira letra de cada uma em maiúsculas com `title()`.
+* Concatena com um espaço no meio.
-```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial001.py!}
-```
+{* ../../docs_src/python_types/tutorial001.py hl[2] *}
### Edite-o
@@ -46,7 +44,7 @@ A função faz o seguinte:
Mas agora imagine que você estava escrevendo do zero.
-Em algum momento você teria iniciado a definição da função, já tinha os parâmetros prontos ...
+Em algum momento você teria iniciado a definição da função, já tinha os parâmetros prontos...
Mas então você deve chamar "esse método que converte a primeira letra em maiúscula".
@@ -80,9 +78,7 @@ para:
Esses são os "type hints":
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial002.py!}
-```
+{* ../../docs_src/python_types/tutorial002.py hl[1] *}
Isso não é o mesmo que declarar valores padrão como seria com:
@@ -94,37 +90,33 @@ Isso não é o mesmo que declarar valores padrão como seria com:
Estamos usando dois pontos (`:`), não é igual a (`=`).
-E adicionar type hints normalmente não muda o que acontece do que aconteceria sem elas.
+E adicionar type hints normalmente não muda o que acontece do que aconteceria sem eles.
Mas agora, imagine que você está novamente no meio da criação dessa função, mas com type hints.
-No mesmo ponto, você tenta acionar o preenchimento automático com o `Ctrl Space` e vê:
+No mesmo ponto, você tenta acionar o preenchimento automático com o `Ctrl+Space` e vê:
get
-!!! info "`@decorador`"
- Essa sintaxe `@alguma_coisa` em Python é chamada de "decorador".
+/// info | `@decorador`
- Você o coloca em cima de uma função. Como um chapéu decorativo (acho que é daí que vem o termo).
+Essa sintaxe `@alguma_coisa` em Python é chamada de "decorador".
- Um "decorador" pega a função abaixo e faz algo com ela.
+Você o coloca em cima de uma função. Como um chapéu decorativo (acho que é daí que vem o termo).
- Em nosso caso, este decorador informa ao **FastAPI** que a função abaixo corresponde a **rota** `/` com uma **operação** `get`.
+Um "decorador" pega a função abaixo e faz algo com ela.
- É o "**decorador de rota**".
+Em nosso caso, este decorador informa ao **FastAPI** que a função abaixo corresponde a **rota** `/` com uma **operação** `get`.
+
+É o "**decorador de rota**".
+
+///
Você também pode usar as outras operações:
@@ -274,14 +264,17 @@ E os mais exóticos:
* `@app.patch()`
* `@app.trace()`
-!!! tip "Dica"
- Você está livre para usar cada operação (método HTTP) como desejar.
+/// tip | Dica
+
+Você está livre para usar cada operação (método HTTP) como desejar.
- O **FastAPI** não impõe nenhum significado específico.
+O **FastAPI** não impõe nenhum significado específico.
- As informações aqui são apresentadas como uma orientação, não uma exigência.
+As informações aqui são apresentadas como uma orientação, não uma exigência.
- Por exemplo, ao usar GraphQL, você normalmente executa todas as ações usando apenas operações `POST`.
+Por exemplo, ao usar GraphQL, você normalmente executa todas as ações usando apenas operações `POST`.
+
+///
### Passo 4: defina uma **função de rota**
@@ -291,9 +284,7 @@ Esta é a nossa "**função de rota**":
* **operação**: é `get`.
* **função**: é a função abaixo do "decorador" (abaixo do `@app.get("/")`).
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[7] *}
Esta é uma função Python.
@@ -305,18 +296,17 @@ Neste caso, é uma função `assíncrona`.
Você também pode defini-la como uma função normal em vez de `async def`:
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial003.py!}
-```
+{* ../../docs_src/first_steps/tutorial003.py hl[7] *}
-!!! nota
- Se você não sabe a diferença, verifique o [Async: *"Com pressa?"*](../async.md#com-pressa){.internal-link target=_blank}.
+/// note | Nota
+
+Se você não sabe a diferença, verifique o [Async: *"Com pressa?"*](../async.md#com-pressa){.internal-link target=_blank}.
+
+///
### Passo 5: retorne o conteúdo
-```Python hl_lines="8"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[8] *}
Você pode retornar um `dict`, `list` e valores singulares como `str`, `int`, etc.
diff --git a/docs/pt/docs/tutorial/handling-errors.md b/docs/pt/docs/tutorial/handling-errors.md
index 97a2e3eac..098195db7 100644
--- a/docs/pt/docs/tutorial/handling-errors.md
+++ b/docs/pt/docs/tutorial/handling-errors.md
@@ -26,9 +26,7 @@ Para retornar ao cliente *responses* HTTP com erros, use o `HTTPException`.
### Import `HTTPException`
-```Python hl_lines="1"
-{!../../../docs_src/handling_errors/tutorial001.py!}
-```
+{* ../../docs_src/handling_errors/tutorial001.py hl[1] *}
### Lance o `HTTPException` no seu código.
@@ -42,9 +40,7 @@ O benefício de lançar uma exceção em vez de retornar um valor ficará mais e
Neste exemplo, quando o cliente pede, na requisição, por um item cujo ID não existe, a exceção com o status code `404` é lançada:
-```Python hl_lines="11"
-{!../../../docs_src/handling_errors/tutorial001.py!}
-```
+{* ../../docs_src/handling_errors/tutorial001.py hl[11] *}
### A response resultante
@@ -66,12 +62,14 @@ Mas se o cliente faz uma requisição para `http://example.com/items/bar` (ou se
}
```
-!!! tip "Dica"
- Quando você lançar um `HTTPException`, você pode passar qualquer valor convertível em JSON como parâmetro de `detail`, e não apenas `str`.
+/// tip | Dica
- Você pode passar um `dict` ou um `list`, etc.
- Esses tipos de dados são manipulados automaticamente pelo **FastAPI** e convertidos em JSON.
+Quando você lançar um `HTTPException`, você pode passar qualquer valor convertível em JSON como parâmetro de `detail`, e não apenas `str`.
+Você pode passar um `dict` ou um `list`, etc.
+Esses tipos de dados são manipulados automaticamente pelo **FastAPI** e convertidos em JSON.
+
+///
## Adicione headers customizados
@@ -81,9 +79,7 @@ Você provavelmente não precisará utilizar esses headers diretamente no seu c
Mas caso você precise, para um cenário mais complexo, você pode adicionar headers customizados:
-```Python hl_lines="14"
-{!../../../docs_src/handling_errors/tutorial002.py!}
-```
+{* ../../docs_src/handling_errors/tutorial002.py hl[14] *}
## Instalando manipuladores de exceções customizados
@@ -93,9 +89,7 @@ Digamos que você tenha uma exceção customizada `UnicornException` que você (
Nesse cenário, se você precisa manipular essa exceção de modo global com o FastAPI, você pode adicionar um manipulador de exceção customizada com `@app.exception_handler()`.
-```Python hl_lines="5-7 13-18 24"
-{!../../../docs_src/handling_errors/tutorial003.py!}
-```
+{* ../../docs_src/handling_errors/tutorial003.py hl[5:7,13:18,24] *}
Nesse cenário, se você fizer uma requisição para `/unicorns/yolo`, a *operação de caminho* vai lançar (`raise`) o `UnicornException`.
@@ -107,10 +101,13 @@ Dessa forma você receberá um erro "limpo", com o HTTP status code `418` e um J
{"message": "Oops! yolo did something. There goes a rainbow..."}
```
-!!! note "Detalhes Técnicos"
- Você também pode usar `from starlette.requests import Request` and `from starlette.responses import JSONResponse`.
+/// note | Detalhes Técnicos
+
+Você também pode usar `from starlette.requests import Request` and `from starlette.responses import JSONResponse`.
+
+**FastAPI** disponibiliza o mesmo `starlette.responses` através do `fastapi.responses` por conveniência ao desenvolvedor. Contudo, a maior parte das respostas disponíveis vem diretamente do Starlette. O mesmo acontece com o `Request`.
- **FastAPI** disponibiliza o mesmo `starlette.responses` através do `fastapi.responses` por conveniência ao desenvolvedor. Contudo, a maior parte das respostas disponíveis vem diretamente do Starlette. O mesmo acontece com o `Request`.
+///
## Sobrescreva o manipulador padrão de exceções
@@ -126,9 +123,7 @@ Quando a requisição contém dados inválidos, **FastAPI** internamente lança
Para sobrescrevê-lo, importe o `RequestValidationError` e use-o com o `@app.exception_handler(RequestValidationError)` para decorar o manipulador de exceções.
-```Python hl_lines="2 14-16"
-{!../../../docs_src/handling_errors/tutorial004.py!}
-```
+{* ../../docs_src/handling_errors/tutorial004.py hl[2,14:16] *}
Se você for ao `/items/foo`, em vez de receber o JSON padrão com o erro:
@@ -157,10 +152,13 @@ path -> item_id
### `RequestValidationError` vs `ValidationError`
-!!! warning "Aviso"
- Você pode pular estes detalhes técnicos caso eles não sejam importantes para você neste momento.
+/// 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.
@@ -174,15 +172,15 @@ Do mesmo modo, você pode sobreescrever o `HTTPException`.
Por exemplo, você pode querer retornar uma *response* em *plain text* ao invés de um JSON para os seguintes erros:
-```Python hl_lines="3-4 9-11 22"
-{!../../../docs_src/handling_errors/tutorial004.py!}
-```
+{* ../../docs_src/handling_errors/tutorial004.py hl[3:4,9:11,22] *}
+
+/// note | Detalhes Técnicos
-!!! note "Detalhes Técnicos"
- Você pode usar `from starlette.responses import PlainTextResponse`.
+Você pode usar `from starlette.responses import PlainTextResponse`.
- **FastAPI** disponibiliza o mesmo `starlette.responses` como `fastapi.responses`, como conveniência a você, desenvolvedor. Contudo, a maior parte das respostas disponíveis vem diretamente do Starlette.
+**FastAPI** disponibiliza o mesmo `starlette.responses` como `fastapi.responses`, como conveniência a você, desenvolvedor. Contudo, a maior parte das respostas disponíveis vem diretamente do Starlette.
+///
### Use o body do `RequestValidationError`.
@@ -244,8 +242,6 @@ from starlette.exceptions import HTTPException as StarletteHTTPException
Se você quer usar a exceção em conjunto com o mesmo manipulador de exceção *default* do **FastAPI**, você pode importar e re-usar esses manipuladores de exceção do `fastapi.exception_handlers`:
-```Python hl_lines="2-5 15 21"
-{!../../../docs_src/handling_errors/tutorial006.py!}
-```
+{* ../../docs_src/handling_errors/tutorial006.py hl[2:5,15,21] *}
Nesse exemplo você apenas imprime (`print`) o erro com uma mensagem expressiva. Mesmo assim, dá para pegar a ideia. Você pode usar a exceção e então apenas re-usar o manipulador de exceção *default*.
diff --git a/docs/pt/docs/tutorial/header-param-models.md b/docs/pt/docs/tutorial/header-param-models.md
new file mode 100644
index 000000000..9a88dbfec
--- /dev/null
+++ b/docs/pt/docs/tutorial/header-param-models.md
@@ -0,0 +1,56 @@
+# Modelos de Parâmetros do Cabeçalho
+
+Se você possui um grupo de **parâmetros de cabeçalho** relacionados, você pode criar um **modelo do Pydantic** para declará-los.
+
+Isso vai lhe permitir **reusar o modelo** em **múltiplos lugares** e também declarar validações e metadadados para todos os parâmetros de uma vez. 😎
+
+/// note | Nota
+
+Isso é possível desde a versão `0.115.0` do FastAPI. 🤓
+
+///
+
+## Parâmetros do Cabeçalho com um Modelo Pydantic
+
+Declare os **parâmetros de cabeçalho** que você precisa em um **modelo do Pydantic**, e então declare o parâmetro como `Header`:
+
+{* ../../docs_src/header_param_models/tutorial001_an_py310.py hl[9:14,18] *}
+
+O **FastAPI** irá **extrair** os dados de **cada campo** a partir dos **cabeçalhos** da requisição e te retornará o modelo do Pydantic que você definiu.
+
+### Checando a documentação
+
+Você pode ver os headers necessários na interface gráfica da documentação em `/docs`:
+
+contact
Parâmetro | Tipo | Descrição |
---|---|---|
name | str | O nome identificador da pessoa/organização de contato. |
url | str | A URL que aponta para as informações de contato. DEVE estar no formato de uma URL. |
email | str | O endereço de e-mail da pessoa/organização de contato. DEVE estar no formato de um endereço de e-mail. |
license_info
Parâmetro | Tipo | Descrição |
---|---|---|
name | str | OBRIGATÓRIO (se um license_info for definido). O nome da licença usada para a API. |
identifier | str | Uma expressão de licença SPDX para a API. O campo identifier é mutuamente exclusivo do campo url . Disponível desde OpenAPI 3.1.0, FastAPI 0.99.0. |
url | str | Uma URL para a licença usada para a API. DEVE estar no formato de uma URL. |
kwargs
. Mesmo que eles não possuam um valor padrão.
-```Python hl_lines="7"
-{!../../../docs_src/path_params_numeric_validations/tutorial003.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *}
## Validações numéricas: maior que ou igual
@@ -81,9 +60,7 @@ Com `Query` e `Path` (e outras que você verá mais tarde) você pode declarar r
Aqui, com `ge=1`, `item_id` precisará ser um número inteiro maior que ("`g`reater than") ou igual ("`e`qual") a 1.
-```Python hl_lines="8"
-{!../../../docs_src/path_params_numeric_validations/tutorial004.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial004.py hl[8] *}
## Validações numéricas: maior que e menor que ou igual
@@ -92,9 +69,7 @@ O mesmo se aplica para:
* `gt`: maior que (`g`reater `t`han)
* `le`: menor que ou igual (`l`ess than or `e`qual)
-```Python hl_lines="9"
-{!../../../docs_src/path_params_numeric_validations/tutorial005.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial005.py hl[9] *}
## Validações numéricas: valores do tipo float, maior que e menor que
@@ -106,9 +81,7 @@ Assim, `0.5` seria um valor válido. Mas `0.0` ou `0` não seria.
E o mesmo para lt
.
-```Python hl_lines="11"
-{!../../../docs_src/path_params_numeric_validations/tutorial006.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial006.py hl[11] *}
## Recapitulando
@@ -121,18 +94,24 @@ E você também pode declarar validações numéricas:
* `lt`: menor que (`l`ess `t`han)
* `le`: menor que ou igual (`l`ess than or `e`qual)
-!!! info "Informação"
- `Query`, `Path` e outras classes que você verá a frente são subclasses de uma classe comum `Param`.
+/// info | Informação
+
+`Query`, `Path` e outras classes que você verá a frente são subclasses de uma classe comum `Param`.
+
+Todas elas compartilham os mesmos parâmetros para validação adicional e metadados que você viu.
+
+///
+
+/// note | Detalhes Técnicos
- Todas elas compartilham os mesmos parâmetros para validação adicional e metadados que você viu.
+Quando você importa `Query`, `Path` e outras de `fastapi`, elas são na verdade funções.
-!!! note "Detalhes Técnicos"
- Quando você importa `Query`, `Path` e outras de `fastapi`, elas são na verdade funções.
+Que quando chamadas, retornam instâncias de classes de mesmo nome.
- Que quando chamadas, retornam instâncias de classes de mesmo nome.
+Então, você importa `Query`, que é uma função. E quando você a chama, ela retorna uma instância de uma classe também chamada `Query`.
- Então, você importa `Query`, que é uma função. E quando você a chama, ela retorna uma instância de uma classe também chamada `Query`.
+Estas funções são assim (ao invés de apenas usar as classes diretamente) para que seu editor não acuse erros sobre seus tipos.
- Estas funções são assim (ao invés de apenas usar as classes diretamente) para que seu editor não acuse erros sobre seus tipos.
+Dessa maneira você pode user seu editor e ferramentas de desenvolvimento sem precisar adicionar configurações customizadas para ignorar estes erros.
- Dessa maneira você pode user seu editor e ferramentas de desenvolvimento sem precisar adicionar configurações customizadas para ignorar estes erros.
+///
diff --git a/docs/pt/docs/tutorial/path-params.md b/docs/pt/docs/tutorial/path-params.md
index 5de3756ed..ecf77d676 100644
--- a/docs/pt/docs/tutorial/path-params.md
+++ b/docs/pt/docs/tutorial/path-params.md
@@ -2,9 +2,7 @@
Você pode declarar os "parâmetros" ou "variáveis" com a mesma sintaxe utilizada pelo formato de strings do Python:
-```Python hl_lines="6-7"
-{!../../../docs_src/path_params/tutorial001.py!}
-```
+{* ../../docs_src/path_params/tutorial001.py hl[6:7] *}
O valor do parâmetro que foi passado à `item_id` será passado para a sua função como o argumento `item_id`.
@@ -18,13 +16,16 @@ Então, se você rodar este exemplo e for até dadosPOST
.
+
+///
+
+/// warning | Aviso
+
+Você pode declarar múltiplos parâmetros `File` e `Form` em uma *operação de rota*, mas você não pode declarar campos `Body` que você espera receber como JSON, pois a requisição terá o corpo codificado usando `multipart/form-data` ao invés de `application/json`.
+
+Isso não é uma limitação do **FastAPI**, é parte do protocolo HTTP.
+
+///
+
+## Upload de Arquivo Opcional
+
+Você pode tornar um arquivo opcional usando anotações de tipo padrão e definindo um valor padrão de `None`:
+
+{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *}
+
+## `UploadFile` com Metadados Adicionais
+
+Você também pode usar `File()` com `UploadFile`, por exemplo, para definir metadados adicionais:
+
+{* ../../docs_src/request_files/tutorial001_03_an_py39.py hl[9,15] *}
+
+## Uploads de Múltiplos Arquivos
+
+É possível realizar o upload de vários arquivos ao mesmo tempo.
+
+Eles serão associados ao mesmo "campo de formulário" enviado usando "dados de formulário".
+
+Para usar isso, declare uma lista de `bytes` ou `UploadFile`:
+
+{* ../../docs_src/request_files/tutorial002_an_py39.py hl[10,15] *}
+
+Você receberá, tal como declarado, uma `list` de `bytes` ou `UploadFile`.
+
+/// note | Detalhes Técnicos
+
+Você pode também pode usar `from starlette.responses import HTMLResponse`.
+
+**FastAPI** providencia o mesmo `starlette.responses` que `fastapi.responses` apenas como uma conveniência para você, o desenvolvedor. Mas a maioria das respostas disponíveis vem diretamente do Starlette.
+
+///
+
+### Uploads de Múltiplos Arquivos com Metadados Adicionais
+
+Da mesma forma de antes, você pode usar `File()` para definir parâmetros adicionais, mesmo para `UploadFile`:
+
+{* ../../docs_src/request_files/tutorial003_an_py39.py hl[11,18:20] *}
+
+## Recapitulando
+
+Utilize `File`, `bytes` e `UploadFile` para declarar arquivos a serem enviados na requisição, enviados como dados de formulário.
diff --git a/docs/pt/docs/tutorial/request-form-models.md b/docs/pt/docs/tutorial/request-form-models.md
new file mode 100644
index 000000000..ea0e63d38
--- /dev/null
+++ b/docs/pt/docs/tutorial/request-form-models.md
@@ -0,0 +1,78 @@
+# Modelos de Formulários
+
+Você pode utilizar **Modelos Pydantic** para declarar **campos de formulários** no FastAPI.
+
+/// info | Informação
+
+Para utilizar formulários, instale primeiramente o `python-multipart`.
+
+Certifique-se de criar um [ambiente virtual](../virtual-environments.md){.internal-link target=_blank}, ativá-lo, e então instalar. Por exemplo:
+
+```console
+$ pip install python-multipart
+```
+
+///
+
+/// note | Nota
+
+Isto é suportado desde a versão `0.113.0` do FastAPI. 🤓
+
+///
+
+## Modelos Pydantic para Formulários
+
+Você precisa apenas declarar um **modelo Pydantic** com os campos que deseja receber como **campos de formulários**, e então declarar o parâmetro como um `Form`:
+
+{* ../../docs_src/request_form_models/tutorial001_an_py39.py hl[9:11,15] *}
+
+O **FastAPI** irá **extrair** as informações para **cada campo** dos **dados do formulário** na requisição e dar para você o modelo Pydantic que você definiu.
+
+## Confira os Documentos
+
+Você pode verificar na UI de documentação em `/docs`:
+
+POST
.
+
+///
- Mas quando o formulário inclui arquivos, ele é codificado como `multipart/form-data`. Você lerá sobre como lidar com arquivos no próximo capítulo.
+/// warning | Aviso
- Se você quiser ler mais sobre essas codificações e campos de formulário, vá para o MDN web docs para POST
.
+Você pode declarar vários parâmetros `Form` em uma *operação de caminho*, mas não pode declarar campos `Body` que espera receber como JSON, pois a solicitação terá o corpo codificado usando `application/x-www- form-urlencoded` em vez de `application/json`.
-!!! warning "Aviso"
- Você pode declarar vários parâmetros `Form` em uma *operação de caminho*, mas não pode declarar campos `Body` que espera receber como JSON, pois a solicitação terá o corpo codificado usando `application/x-www- form-urlencoded` em vez de `application/json`.
+Esta não é uma limitação do **FastAPI**, é parte do protocolo HTTP.
- Esta não é uma limitação do **FastAPI**, é parte do protocolo HTTP.
+///
## Recapitulando
diff --git a/docs/pt/docs/tutorial/request_files.md b/docs/pt/docs/tutorial/request_files.md
new file mode 100644
index 000000000..15c1ad825
--- /dev/null
+++ b/docs/pt/docs/tutorial/request_files.md
@@ -0,0 +1,172 @@
+# Arquivos de Requisição
+
+Você pode definir arquivos para serem enviados para o cliente utilizando `File`.
+
+/// info
+
+Para receber arquivos compartilhados, primeiro instale `python-multipart`.
+
+E.g. `pip install python-multipart`.
+
+Isso se deve por que arquivos enviados são enviados como "dados de formulário".
+
+///
+
+## Importe `File`
+
+Importe `File` e `UploadFile` do `fastapi`:
+
+{* ../../docs_src/request_files/tutorial001_an_py39.py hl[3] *}
+
+## Defina os parâmetros de `File`
+
+Cria os parâmetros do arquivo da mesma forma que você faria para `Body` ou `Form`:
+
+{* ../../docs_src/request_files/tutorial001_an_py39.py hl[9] *}
+
+/// info | Informação
+
+`File` é uma classe que herda diretamente de `Form`.
+
+Mas lembre-se que quando você importa `Query`,`Path`, `File`, entre outros, do `fastapi`, essas são na verdade funções que retornam classes especiais.
+
+///
+
+/// tip | Dica
+
+Para declarar o corpo de arquivos, você precisa utilizar `File`, do contrário os parâmetros seriam interpretados como parâmetros de consulta ou corpo (JSON) da requisição.
+
+///
+
+Os arquivos serão enviados como "form data".
+
+Se você declarar o tipo do seu parâmetro na sua *função de operação de rota* como `bytes`, o **FastAPI** irá ler o arquivo para você e você receberá o conteúdo como `bytes`.
+
+Lembre-se que isso significa que o conteúdo inteiro será armazenado em memória. Isso funciona bem para arquivos pequenos.
+
+Mas existem vários casos em que você pode se beneficiar ao usar `UploadFile`.
+
+## Parâmetros de arquivo com `UploadFile`
+
+Defina um parâmetro de arquivo com o tipo `UploadFile`
+
+{* ../../docs_src/request_files/tutorial001_an_py39.py hl[14] *}
+
+Utilizando `UploadFile` tem várias vantagens sobre `bytes`:
+
+* Você não precisa utilizar `File()` como o valor padrão do parâmetro.
+* A classe utiliza um arquivo em "spool":
+ * Um arquivo guardado em memória até um tamanho máximo, depois desse limite ele é guardado em disco.
+* Isso significa que a classe funciona bem com arquivos grandes como imagens, vídeos, binários extensos, etc. Sem consumir toda a memória.
+* Você pode obter metadados do arquivo enviado.
+* Ela possui uma interface semelhante a arquivos `async`.
+* Ela expõe um objeto python `SpooledTemporaryFile` que você pode repassar para bibliotecas que esperam um objeto com comportamento de arquivo.
+
+### `UploadFile`
+
+`UploadFile` tem os seguintes atributos:
+
+* `filename`: Uma string (`str`) com o nome original do arquivo enviado (e.g. `myimage.jpg`).
+* `content-type`: Uma `str` com o tipo do conteúdo (tipo MIME / media) (e.g. `image/jpeg`).
+* `file`: Um objeto do tipo `SpooledTemporaryFile` (um objeto file-like). O arquivo propriamente dito que você pode passar diretamente para outras funções ou bibliotecas que esperam um objeto "file-like".
+
+`UploadFile` tem os seguintes métodos `async`. Todos eles chamam os métodos de arquivos por baixo dos panos (usando o objeto `SpooledTemporaryFile` interno).
+
+* `write(data)`: escreve dados (`data`) em `str` ou `bytes` no arquivo.
+* `read(size)`: Lê um número de bytes/caracteres de acordo com a quantidade `size` (`int`).
+* `seek(offset)`: Navega para o byte na posição `offset` (`int`) do arquivo.
+ * E.g., `await myfile.seek(0)` navegaria para o ínicio do arquivo.
+ * Isso é especialmente útil se você executar `await myfile.read()` uma vez e depois precisar ler os conteúdos do arquivo de novo.
+* `close()`: Fecha o arquivo.
+
+Como todos esses métodos são assíncronos (`async`) você precisa esperar ("await") por eles.
+
+Por exemplo, dentro de uma *função de operação de rota* assíncrona você pode obter os conteúdos com:
+
+```Python
+contents = await myfile.read()
+```
+
+Se você estiver dentro de uma *função de operação de rota* definida normalmente com `def`, você pode acessar `UploadFile.file` diretamente, por exemplo:
+
+```Python
+contents = myfile.file.read()
+```
+
+/// note | Detalhes técnicos do `async`
+
+Quando você utiliza métodos assíncronos, o **FastAPI** executa os métodos do arquivo em uma threadpool e espera por eles.
+
+///
+
+/// note | Detalhes técnicos do Starlette
+
+O `UploadFile` do **FastAPI** herda diretamente do `UploadFile` do **Starlette**, mas adiciona algumas funcionalidades necessárias para ser compatível com o **Pydantic**
+
+///
+
+## O que é "Form Data"
+
+A forma como formulários HTML(``) enviam dados para o servidor normalmente utilizam uma codificação "especial" para esses dados, que é diferente do JSON.
+
+O **FastAPI** garante que os dados serão lidos da forma correta, em vez do JSON.
+
+/// note | Detalhes Técnicos
+
+Dados vindos de formulários geralmente tem a codificação com o "media type" `application/x-www-form-urlencoded` quando estes não incluem arquivos.
+
+Mas quando os dados incluem arquivos, eles são codificados como `multipart/form-data`. Se você utilizar `File`, **FastAPI** saberá que deve receber os arquivos da parte correta do corpo da requisição.
+
+Se você quer ler mais sobre essas codificações e campos de formulário, veja a documentação online da MDN sobre POST
.
+
+///
+
+/// warning | Aviso
+
+Você pode declarar múltiplos parâmetros `File` e `Form` em uma *operação de rota*, mas você não pode declarar campos `Body`que seriam recebidos como JSON junto desses parâmetros, por que a codificação do corpo da requisição será `multipart/form-data` em vez de `application/json`.
+
+Isso não é uma limitação do **FastAPI**, é uma parte do protocolo HTTP.
+
+///
+
+## Arquivo de upload opcional
+
+Você pode definir um arquivo como opcional utilizando as anotações de tipo padrão e definindo o valor padrão como `None`:
+
+{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *}
+
+## `UploadFile` com Metadados Adicionais
+
+Você também pode utilizar `File()` com `UploadFile`, por exemplo, para definir metadados adicionais:
+
+{* ../../docs_src/request_files/tutorial001_03_an_py39.py hl[9,15] *}
+
+## Envio de Múltiplos Arquivos
+
+É possível enviar múltiplos arquivos ao mesmo tmepo.
+
+Ele ficam associados ao mesmo "campo do formulário" enviado com "form data".
+
+Para usar isso, declare uma lista de `bytes` ou `UploadFile`:
+
+{* ../../docs_src/request_files/tutorial002_an_py39.py hl[10,15] *}
+
+Você irá receber, como delcarado uma lista (`list`) de `bytes` ou `UploadFile`s,
+
+/// note | Detalhes Técnicos
+
+Você também poderia utilizar `from starlette.responses import HTMLResponse`.
+
+O **FastAPI** fornece as mesmas `starlette.responses` como `fastapi.responses` apenas como um facilitador para você, desenvolvedor. Mas a maior parte das respostas vem diretamente do Starlette.
+
+///
+
+### Enviando Múltiplos Arquivos com Metadados Adicionais
+
+E da mesma forma que antes, você pode utilizar `File()` para definir parâmetros adicionais, até mesmo para `UploadFile`:
+
+{* ../../docs_src/request_files/tutorial003_an_py39.py hl[11,18:20] *}
+
+## Recapitulando
+
+Use `File`, `bytes` e `UploadFile` para declarar arquivos que serão enviados na requisição, enviados como dados do formulário.
diff --git a/docs/pt/docs/tutorial/response-model.md b/docs/pt/docs/tutorial/response-model.md
new file mode 100644
index 000000000..6726a20a7
--- /dev/null
+++ b/docs/pt/docs/tutorial/response-model.md
@@ -0,0 +1,357 @@
+# Modelo de resposta - Tipo de retorno
+
+Você pode declarar o tipo usado para a resposta anotando o **tipo de retorno** *da função de operação de rota*.
+
+Você pode usar **anotações de tipo** da mesma forma que usaria para dados de entrada em **parâmetros** de função, você pode usar modelos Pydantic, listas, dicionários, valores escalares como inteiros, booleanos, etc.
+
+{* ../../docs_src/response_model/tutorial001_01_py310.py hl[16,21] *}
+
+O FastAPI usará este tipo de retorno para:
+
+* **Validar** os dados retornados.
+ * Se os dados forem inválidos (por exemplo, se estiver faltando um campo), significa que o código do *seu* aplicativo está quebrado, não retornando o que deveria, e retornará um erro de servidor em vez de retornar dados incorretos. Dessa forma, você e seus clientes podem ter certeza de que receberão os dados e o formato de dados esperados.
+* Adicionar um **Esquema JSON** para a resposta, na *operação de rota* do OpenAPI.
+ * Isso será usado pela **documentação automática**.
+ * Também será usado por ferramentas de geração automática de código do cliente.
+
+Mas o mais importante:
+
+* Ele **limitará e filtrará** os dados de saída para o que está definido no tipo de retorno.
+ * Isso é particularmente importante para a **segurança**, veremos mais sobre isso abaixo.
+
+## Parâmetro `response_model`
+
+Existem alguns casos em que você precisa ou deseja retornar alguns dados que não são exatamente o que o tipo declara.
+
+Por exemplo, você pode querer **retornar um dicionário** ou um objeto de banco de dados, mas **declará-lo como um modelo Pydantic**. Dessa forma, o modelo Pydantic faria toda a documentação de dados, validação, etc. para o objeto que você retornou (por exemplo, um dicionário ou objeto de banco de dados).
+
+Se você adicionasse a anotação do tipo de retorno, ferramentas e editores reclamariam com um erro (correto) informando que sua função está retornando um tipo (por exemplo, um dict) diferente do que você declarou (por exemplo, um modelo Pydantic).
+
+Nesses casos, você pode usar o parâmetro `response_model` do *decorador de operação de rota* em vez do tipo de retorno.
+
+Você pode usar o parâmetro `response_model` em qualquer uma das *operações de rota*:
+
+* `@app.get()`
+* `@app.post()`
+* `@app.put()`
+* `@app.delete()`
+* etc.
+
+{* ../../docs_src/response_model/tutorial001_py310.py hl[17,22,24:27] *}
+
+/// note | Nota
+
+Observe que `response_model` é um parâmetro do método "decorator" (`get`, `post`, etc). Não da sua *função de operação de rota*, como todos os parâmetros e corpo.
+
+///
+
+`response_model` recebe o mesmo tipo que você declararia para um campo de modelo Pydantic, então, pode ser um modelo Pydantic, mas também pode ser, por exemplo, uma `lista` de modelos Pydantic, como `List[Item]`.
+
+O FastAPI usará este `response_model` para fazer toda a documentação de dados, validação, etc. e também para **converter e filtrar os dados de saída** para sua declaração de tipo.
+
+/// tip | Dica
+
+Se você tiver verificações de tipo rigorosas em seu editor, mypy, etc, você pode declarar o tipo de retorno da função como `Any`.
+
+Dessa forma, você diz ao editor que está retornando qualquer coisa intencionalmente. Mas o FastAPI ainda fará a documentação de dados, validação, filtragem, etc. com o `response_model`.
+
+///
+
+### Prioridade `response_model`
+
+Se você declarar tanto um tipo de retorno quanto um `response_model`, o `response_model` terá prioridade e será usado pelo FastAPI.
+
+Dessa forma, você pode adicionar anotações de tipo corretas às suas funções, mesmo quando estiver retornando um tipo diferente do modelo de resposta, para ser usado pelo editor e ferramentas como mypy. E ainda assim você pode fazer com que o FastAPI faça a validação de dados, documentação, etc. usando o `response_model`.
+
+Você também pode usar `response_model=None` para desabilitar a criação de um modelo de resposta para essa *operação de rota*, você pode precisar fazer isso se estiver adicionando anotações de tipo para coisas que não são campos Pydantic válidos, você verá um exemplo disso em uma das seções abaixo.
+
+## Retorna os mesmos dados de entrada
+
+Aqui estamos declarando um modelo `UserIn`, ele conterá uma senha em texto simples:
+
+{* ../../docs_src/response_model/tutorial002_py310.py hl[7,9] *}
+
+/// info | Informação
+
+Para usar `EmailStr`, primeiro instale `email-validator`.
+
+Certifique-se de criar um [ambiente virtual](../virtual-environments.md){.internal-link target=_blank}, ative-o e instale-o, por exemplo:
+
+```console
+$ pip install email-validator
+```
+
+ou com:
+
+```console
+$ pip install "pydantic[email]"
+```
+
+///
+
+E estamos usando este modelo para declarar nossa entrada e o mesmo modelo para declarar nossa saída:
+
+{* ../../docs_src/response_model/tutorial002_py310.py hl[16] *}
+
+Agora, sempre que um navegador estiver criando um usuário com uma senha, a API retornará a mesma senha na resposta.
+
+Neste caso, pode não ser um problema, porque é o mesmo usuário enviando a senha.
+
+Mas se usarmos o mesmo modelo para outra *operação de rota*, poderíamos estar enviando as senhas dos nossos usuários para todos os clientes.
+
+/// danger | Perigo
+
+Nunca armazene a senha simples de um usuário ou envie-a em uma resposta como esta, a menos que você saiba todas as ressalvas e saiba o que está fazendo.
+
+///
+
+## Adicionar um modelo de saída
+
+Podemos, em vez disso, criar um modelo de entrada com a senha em texto simples e um modelo de saída sem ela:
+
+{* ../../docs_src/response_model/tutorial003_py310.py hl[9,11,16] *}
+
+Aqui, embora nossa *função de operação de rota* esteja retornando o mesmo usuário de entrada que contém a senha:
+
+{* ../../docs_src/response_model/tutorial003_py310.py hl[24] *}
+
+...declaramos o `response_model` como nosso modelo `UserOut`, que não inclui a senha:
+
+{* ../../docs_src/response_model/tutorial003_py310.py hl[22] *}
+
+Então, **FastAPI** cuidará de filtrar todos os dados que não são declarados no modelo de saída (usando Pydantic).
+
+### `response_model` ou Tipo de Retorno
+
+Neste caso, como os dois modelos são diferentes, se anotássemos o tipo de retorno da função como `UserOut`, o editor e as ferramentas reclamariam que estamos retornando um tipo inválido, pois são classes diferentes.
+
+É por isso que neste exemplo temos que declará-lo no parâmetro `response_model`.
+
+...mas continue lendo abaixo para ver como superar isso.
+
+## Tipo de Retorno e Filtragem de Dados
+
+Vamos continuar do exemplo anterior. Queríamos **anotar a função com um tipo**, mas queríamos poder retornar da função algo que realmente incluísse **mais dados**.
+
+Queremos que o FastAPI continue **filtrando** os dados usando o modelo de resposta. Para que, embora a função retorne mais dados, a resposta inclua apenas os campos declarados no modelo de resposta.
+
+No exemplo anterior, como as classes eram diferentes, tivemos que usar o parâmetro `response_model`. Mas isso também significa que não temos suporte do editor e das ferramentas verificando o tipo de retorno da função.
+
+Mas na maioria dos casos em que precisamos fazer algo assim, queremos que o modelo apenas **filtre/remova** alguns dados como neste exemplo.
+
+E nesses casos, podemos usar classes e herança para aproveitar as **anotações de tipo** de função para obter melhor suporte no editor e nas ferramentas, e ainda obter a **filtragem de dados** FastAPI.
+
+{* ../../docs_src/response_model/tutorial003_01_py310.py hl[7:10,13:14,18] *}
+
+Com isso, temos suporte de ferramentas, de editores e mypy, pois este código está correto em termos de tipos, mas também obtemos a filtragem de dados do FastAPI.
+
+Como isso funciona? Vamos verificar. 🤓
+
+### Anotações de tipo e ferramentas
+
+Primeiro, vamos ver como editores, mypy e outras ferramentas veriam isso.
+
+`BaseUser` tem os campos base. Então `UserIn` herda de `BaseUser` e adiciona o campo `password`, então, ele incluirá todos os campos de ambos os modelos.
+
+Anotamos o tipo de retorno da função como `BaseUser`, mas na verdade estamos retornando uma instância `UserIn`.
+
+O editor, mypy e outras ferramentas não reclamarão disso porque, em termos de digitação, `UserIn` é uma subclasse de `BaseUser`, o que significa que é um tipo *válido* quando o que é esperado é qualquer coisa que seja um `BaseUser`.
+
+### Filtragem de dados FastAPI
+
+Agora, para FastAPI, ele verá o tipo de retorno e garantirá que o que você retornar inclua **apenas** os campos que são declarados no tipo.
+
+O FastAPI faz várias coisas internamente com o Pydantic para garantir que essas mesmas regras de herança de classe não sejam usadas para a filtragem de dados retornados, caso contrário, você pode acabar retornando muito mais dados do que o esperado.
+
+Dessa forma, você pode obter o melhor dos dois mundos: anotações de tipo com **suporte a ferramentas** e **filtragem de dados**.
+
+## Veja na documentação
+
+Quando você vê a documentação automática, pode verificar se o modelo de entrada e o modelo de saída terão seus próprios esquemas JSON:
+
+
-
-
+
+
-
-
+
+
@@ -23,11 +29,11 @@
**Документация**: https://fastapi.tiangolo.com
-**Исходный код**: https://github.com/tiangolo/fastapi
+**Исходный код**: https://github.com/fastapi/fastapi
---
-FastAPI — это современный, быстрый (высокопроизводительный) веб-фреймворк для создания API используя Python 3.6+, в основе которого лежит стандартная аннотация типов Python.
+FastAPI — это современный, быстрый (высокопроизводительный) веб-фреймворк для создания API используя Python, в основе которого лежит стандартная аннотация типов Python.
Ключевые особенности:
@@ -63,7 +69,7 @@ FastAPI — это современный, быстрый (высокопрои
"_В последнее время я много где использую **FastAPI**. [...] На самом деле я планирую использовать его для всех **сервисов машинного обучения моей команды в Microsoft**. Некоторые из них интегрируются в основной продукт **Windows**, а некоторые — в продукты **Office**._"
-
ujson
- для более быстрого JSON "парсинга".
-* email_validator
- для проверки электронной почты.
+* email-validator
- для проверки электронной почты.
Используется Starlette:
* HTTPX
- Обязательно, если вы хотите использовать `TestClient`.
* jinja2
- Обязательно, если вы хотите использовать конфигурацию шаблона по умолчанию.
-* python-multipart
- Обязательно, если вы хотите поддерживать форму "парсинга" с помощью `request.form()`.
+* python-multipart
- Обязательно, если вы хотите поддерживать форму "парсинга" с помощью `request.form()`.
* itsdangerous
- Обязательно, для поддержки `SessionMiddleware`.
* pyyaml
- Обязательно, для поддержки `SchemaGenerator` Starlette (возможно, вам это не нужно с FastAPI).
-* ujson
- Обязательно, если вы хотите использовать `UJSONResponse`.
Используется FastAPI / Starlette:
* uvicorn
- сервер, который загружает и обслуживает ваше приложение.
* orjson
- Обязательно, если вы хотите использовать `ORJSONResponse`.
+* ujson
- Обязательно, если вы хотите использовать `UJSONResponse`.
Вы можете установить все это с помощью `pip install "fastapi[all]"`.
diff --git a/docs/ru/docs/learn/index.md b/docs/ru/docs/learn/index.md
new file mode 100644
index 000000000..b2e4cabc7
--- /dev/null
+++ b/docs/ru/docs/learn/index.md
@@ -0,0 +1,5 @@
+# Обучение
+
+Здесь представлены вводные разделы и учебные пособия для изучения **FastAPI**.
+
+Вы можете считать это **книгой**, **курсом**, **официальным** и рекомендуемым способом изучения FastAPI. 😎
diff --git a/docs/ru/docs/project-generation.md b/docs/ru/docs/project-generation.md
index 76253d6f2..efd6794ad 100644
--- a/docs/ru/docs/project-generation.md
+++ b/docs/ru/docs/project-generation.md
@@ -14,7 +14,7 @@ GitHub: **FastAPI**:
+* Бэкенд построен на фреймворке **FastAPI**:
* **Быстрый**: Высокопроизводительный, на уровне **NodeJS** и **Go** (благодаря Starlette и Pydantic).
* **Интуитивно понятный**: Отличная поддержка редактора. Автодополнение кода везде. Меньше времени на отладку.
* **Простой**: Разработан так, чтоб быть простым в использовании и изучении. Меньше времени на чтение документации.
diff --git a/docs/ru/docs/python-types.md b/docs/ru/docs/python-types.md
index 7523083c8..b1d4715fd 100644
--- a/docs/ru/docs/python-types.md
+++ b/docs/ru/docs/python-types.md
@@ -12,16 +12,18 @@ Python имеет поддержку необязательных аннотац
Но даже если вы никогда не используете **FastAPI**, вам будет полезно немного узнать о них.
-!!! note
- Если вы являетесь экспертом в Python и уже знаете всё об аннотациях типов, переходите к следующему разделу.
+/// note
+
+Если вы являетесь экспертом в Python и уже знаете всё об аннотациях типов, переходите к следующему разделу.
+
+///
## Мотивация
Давайте начнем с простого примера:
-```Python
-{!../../../docs_src/python_types/tutorial001.py!}
-```
+{* ../../docs_src/python_types/tutorial001.py *}
+
Вызов этой программы выводит:
@@ -35,9 +37,8 @@ John Doe
* Преобразует первую букву содержимого каждой переменной в верхний регистр с `title()`.
* Соединяет их через пробел.
-```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial001.py!}
-```
+{* ../../docs_src/python_types/tutorial001.py hl[2] *}
+
### Отредактируем пример
@@ -79,9 +80,8 @@ John Doe
Это аннотации типов:
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial002.py!}
-```
+{* ../../docs_src/python_types/tutorial002.py hl[1] *}
+
Это не то же самое, что объявление значений по умолчанию, например:
@@ -109,9 +109,8 @@ John Doe
Проверьте эту функцию, она уже имеет аннотации типов:
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial003.py!}
-```
+{* ../../docs_src/python_types/tutorial003.py hl[1] *}
+
Поскольку редактор знает типы переменных, вы получаете не только дополнение, но и проверки ошибок:
@@ -119,9 +118,8 @@ John Doe
Теперь вы знаете, что вам нужно исправить, преобразовав `age` в строку с `str(age)`:
-```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial004.py!}
-```
+{* ../../docs_src/python_types/tutorial004.py hl[2] *}
+
## Объявление типов
@@ -140,9 +138,8 @@ John Doe
* `bool`
* `bytes`
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial005.py!}
-```
+{* ../../docs_src/python_types/tutorial005.py hl[1] *}
+
### Generic-типы с параметрами типов
@@ -158,9 +155,8 @@ John Doe
Импортируйте `List` из `typing` (с заглавной `L`):
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial006.py!}
-```
+{* ../../docs_src/python_types/tutorial006.py hl[1] *}
+
Объявите переменную с тем же синтаксисом двоеточия (`:`).
@@ -168,14 +164,16 @@ John Doe
Поскольку список является типом, содержащим некоторые внутренние типы, вы помещаете их в квадратные скобки:
-```Python hl_lines="4"
-{!../../../docs_src/python_types/tutorial006.py!}
-```
+{* ../../docs_src/python_types/tutorial006.py hl[4] *}
+
-!!! tip
- Эти внутренние типы в квадратных скобках называются «параметрами типов».
+/// tip
- В этом случае `str` является параметром типа, передаваемым в `List`.
+Эти внутренние типы в квадратных скобках называются «параметрами типов».
+
+В этом случае `str` является параметром типа, передаваемым в `List`.
+
+///
Это означает: "переменная `items` является `list`, и каждый из элементов этого списка является `str`".
@@ -193,9 +191,8 @@ John Doe
Вы бы сделали то же самое, чтобы объявить `tuple` и `set`:
-```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial007.py!}
-```
+{* ../../docs_src/python_types/tutorial007.py hl[1,4] *}
+
Это означает:
@@ -210,9 +207,8 @@ John Doe
Второй параметр типа предназначен для значений `dict`:
-```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial008.py!}
-```
+{* ../../docs_src/python_types/tutorial008.py hl[1,4] *}
+
Это означает:
@@ -225,7 +221,7 @@ John Doe
Вы также можете использовать `Optional`, чтобы объявить, что переменная имеет тип, например, `str`, но это является «необязательным», что означает, что она также может быть `None`:
```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009.py!}
+{!../../docs_src/python_types/tutorial009.py!}
```
Использование `Optional[str]` вместо просто `str` позволит редактору помочь вам в обнаружении ошибок, в которых вы могли бы предположить, что значение всегда является `str`, хотя на самом деле это может быть и `None`.
@@ -249,15 +245,13 @@ John Doe
Допустим, у вас есть класс `Person` с полем `name`:
-```Python hl_lines="1-3"
-{!../../../docs_src/python_types/tutorial010.py!}
-```
+{* ../../docs_src/python_types/tutorial010.py hl[1:3] *}
+
Тогда вы можете объявить переменную типа `Person`:
-```Python hl_lines="6"
-{!../../../docs_src/python_types/tutorial010.py!}
-```
+{* ../../docs_src/python_types/tutorial010.py hl[6] *}
+
И снова вы получаете полную поддержку редактора:
@@ -265,7 +259,7 @@ John Doe
## Pydantic-модели
-Pydantic является Python-библиотекой для выполнения валидации данных.
+Pydantic является Python-библиотекой для выполнения валидации данных.
Вы объявляете «форму» данных как классы с атрибутами.
@@ -277,12 +271,14 @@ John Doe
Взято из официальной документации Pydantic:
-```Python
-{!../../../docs_src/python_types/tutorial011.py!}
-```
+{* ../../docs_src/python_types/tutorial011.py *}
+
-!!! info
- Чтобы узнать больше о Pydantic, читайте его документацию.
+/// info
+
+Чтобы узнать больше о Pydantic, читайте его документацию.
+
+///
**FastAPI** целиком основан на Pydantic.
@@ -310,5 +306,8 @@ John Doe
Важно то, что при использовании стандартных типов Python в одном месте (вместо добавления дополнительных классов, декораторов и т.д.) **FastAPI** сделает за вас большую часть работы.
-!!! info
- Если вы уже прошли всё руководство и вернулись, чтобы узнать больше о типах, хорошим ресурсом является «шпаргалка» от `mypy`.
+/// info
+
+Если вы уже прошли всё руководство и вернулись, чтобы узнать больше о типах, хорошим ресурсом является «шпаргалка» от `mypy`.
+
+///
diff --git a/docs/ru/docs/tutorial/background-tasks.md b/docs/ru/docs/tutorial/background-tasks.md
index 81efda786..bf2e9dec3 100644
--- a/docs/ru/docs/tutorial/background-tasks.md
+++ b/docs/ru/docs/tutorial/background-tasks.md
@@ -15,9 +15,7 @@
Сначала импортируйте `BackgroundTasks`, потом добавьте в функцию параметр с типом `BackgroundTasks`:
-```Python hl_lines="1 13"
-{!../../../docs_src/background_tasks/tutorial001.py!}
-```
+{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *}
**FastAPI** создаст объект класса `BackgroundTasks` для вас и запишет его в параметр.
@@ -33,17 +31,13 @@
Так как операция записи не использует `async` и `await`, мы определим ее как обычную `def`:
-```Python hl_lines="6-9"
-{!../../../docs_src/background_tasks/tutorial001.py!}
-```
+{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *}
## Добавление фоновой задачи
Внутри функции вызовите метод `.add_task()` у объекта *background tasks* и передайте ему функцию, которую хотите выполнить в фоне:
-```Python hl_lines="14"
-{!../../../docs_src/background_tasks/tutorial001.py!}
-```
+{* ../../docs_src/background_tasks/tutorial001.py hl[14] *}
`.add_task()` принимает следующие аргументы:
@@ -57,21 +51,11 @@
**FastAPI** знает, что нужно сделать в каждом случае и как переиспользовать тот же объект `BackgroundTasks`, так чтобы все фоновые задачи собрались и запустились вместе в фоне:
-=== "Python 3.10+"
-
- ```Python hl_lines="11 13 20 23"
- {!> ../../../docs_src/background_tasks/tutorial002_py310.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="13 15 22 25"
- {!> ../../../docs_src/background_tasks/tutorial002.py!}
- ```
+{* ../../docs_src/background_tasks/tutorial002_py310.py hl[11,13,20,23] *}
В этом примере сообщения будут записаны в `log.txt` *после* того, как ответ сервера был отправлен.
-Если бы в запросе была очередь `q`, она бы первой записалась в `log.txt` фоновой задачей (потому что вызывается в зависимости `get_query`).
+Если бы в запрос был передан query-параметр `q`, он бы первыми записался в `log.txt` фоновой задачей (потому что вызывается в зависимости `get_query`).
После другая фоновая задача, которая была сгенерирована в функции, запишет сообщение из параметра `email`.
@@ -93,8 +77,6 @@
Их тяжелее настраивать, также им нужен брокер сообщений наподобие RabbitMQ или Redis, но зато они позволяют вам запускать фоновые задачи в нескольких процессах и даже на нескольких серверах.
-Для примера, посмотрите [Project Generators](../project-generation.md){.internal-link target=_blank}, там есть проект с уже настроенным Celery.
-
Но если вам нужен доступ к общим переменным и объектам вашего **FastAPI** приложения или вам нужно выполнять простые фоновые задачи (наподобие отправки письма из примера) вы можете просто использовать `BackgroundTasks`.
## Резюме
diff --git a/docs/ru/docs/tutorial/bigger-applications.md b/docs/ru/docs/tutorial/bigger-applications.md
new file mode 100644
index 000000000..8b9080d39
--- /dev/null
+++ b/docs/ru/docs/tutorial/bigger-applications.md
@@ -0,0 +1,556 @@
+# Большие приложения, в которых много файлов
+
+При построении приложения или веб-API нам редко удается поместить всё в один файл.
+
+**FastAPI** предоставляет удобный инструментарий, который позволяет нам структурировать приложение, сохраняя при этом всю необходимую гибкость.
+
+/// info | Примечание
+
+Если вы раньше использовали Flask, то это аналог шаблонов Flask (Flask's Blueprints).
+
+///
+
+## Пример структуры приложения
+
+Давайте предположим, что наше приложение имеет следующую структуру:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+│ ├── dependencies.py
+│ └── routers
+│ │ ├── __init__.py
+│ │ ├── items.py
+│ │ └── users.py
+│ └── internal
+│ ├── __init__.py
+│ └── admin.py
+```
+
+/// tip | Подсказка
+
+Обратите внимание, что в каждом каталоге и подкаталоге имеется файл `__init__.py`
+
+Это как раз то, что позволяет импортировать код из одного файла в другой.
+
+Например, в файле `app/main.py` может быть следующая строка:
+
+```
+from app.routers import items
+```
+
+///
+
+* Всё помещается в каталоге `app`. В нём также находится пустой файл `app/__init__.py`. Таким образом, `app` является "Python-пакетом" (коллекцией модулей Python).
+* Он содержит файл `app/main.py`. Данный файл является частью пакета (т.е. находится внутри каталога, содержащего файл `__init__.py`), и, соответственно, он является модулем пакета: `app.main`.
+* Он также содержит файл `app/dependencies.py`, который также, как и `app/main.py`, является модулем: `app.dependencies`.
+* Здесь также находится подкаталог `app/routers/`, содержащий `__init__.py`. Он является суб-пакетом: `app.routers`.
+* Файл `app/routers/items.py` находится внутри пакета `app/routers/`. Таким образом, он является суб-модулем: `app.routers.items`.
+* Точно также `app/routers/users.py` является ещё одним суб-модулем: `app.routers.users`.
+* Подкаталог `app/internal/`, содержащий файл `__init__.py`, является ещё одним суб-пакетом: `app.internal`.
+* А файл `app/internal/admin.py` является ещё одним суб-модулем: `app.internal.admin`.
+
+get
операцию
+
+/// info | `@decorator` Дополнительная информация
+
+Синтаксис `@something` в Python называется "декоратор".
+
+Вы помещаете его над функцией. Как красивую декоративную шляпу (думаю, что оттуда и происходит этот термин).
+
+"Декоратор" принимает функцию ниже и выполняет с ней какое-то действие.
+
+В нашем случае, этот декоратор сообщает **FastAPI**, что функция ниже соответствует **пути** `/` и **операции** `get`.
+
+Это и есть "**декоратор операции пути**".
+
+///
+
+Можно также использовать операции:
+
+* `@app.post()`
+* `@app.put()`
+* `@app.delete()`
+
+И более экзотические:
+
+* `@app.options()`
+* `@app.head()`
+* `@app.patch()`
+* `@app.trace()`
+
+/// tip | Подсказка
+
+Вы можете использовать каждую операцию (HTTP-метод) по своему усмотрению.
+
+**FastAPI** не навязывает определенного значения для каждого метода.
+
+Информация здесь представлена как рекомендация, а не требование.
+
+Например, при использовании GraphQL обычно все действия выполняются только с помощью POST операций.
+
+///
+
+### Шаг 4: определите **функцию операции пути**
+
+Вот "**функция операции пути**":
+
+* **путь**: `/`.
+* **операция**: `get`.
+* **функция**: функция ниже "декоратора" (ниже `@app.get("/")`).
+
+{* ../../docs_src/first_steps/tutorial001.py hl[7] *}
+
+Это обычная Python функция.
+
+**FastAPI** будет вызывать её каждый раз при получении `GET` запроса к URL "`/`".
+
+В данном случае это асинхронная функция.
+
+---
+
+Вы также можете определить ее как обычную функцию вместо `async def`:
+
+{* ../../docs_src/first_steps/tutorial003.py hl[7] *}
+
+/// note | Технические детали
+
+Если не знаете в чём разница, посмотрите [Конкурентность: *"Нет времени?"*](../async.md#_1){.internal-link target=_blank}.
+
+///
+
+### Шаг 5: верните результат
+
+{* ../../docs_src/first_steps/tutorial001.py hl[8] *}
+
+Вы можете вернуть `dict`, `list`, отдельные значения `str`, `int` и т.д.
+
+Также можно вернуть модели Pydantic (рассмотрим это позже).
+
+Многие объекты и модели будут автоматически преобразованы в JSON (включая ORM). Пробуйте использовать другие объекты, которые предпочтительней для Вас, вероятно, они уже поддерживаются.
+
+## Резюме
+
+* Импортируем `FastAPI`.
+* Создаём экземпляр `app`.
+* Пишем **декоратор операции пути** (такой как `@app.get("/")`).
+* Пишем **функцию операции пути** (`def root(): ...`).
+* Запускаем сервер в режиме разработки (`uvicorn main:app --reload`).
diff --git a/docs/ru/docs/tutorial/handling-errors.md b/docs/ru/docs/tutorial/handling-errors.md
new file mode 100644
index 000000000..c596abe1f
--- /dev/null
+++ b/docs/ru/docs/tutorial/handling-errors.md
@@ -0,0 +1,257 @@
+# Обработка ошибок
+
+Существует множество ситуаций, когда необходимо сообщить об ошибке клиенту, использующему ваш API.
+
+Таким клиентом может быть браузер с фронтендом, чужой код, IoT-устройство и т.д.
+
+Возможно, вам придется сообщить клиенту о следующем:
+
+* Клиент не имеет достаточных привилегий для выполнения данной операции.
+* Клиент не имеет доступа к данному ресурсу.
+* Элемент, к которому клиент пытался получить доступ, не существует.
+* и т.д.
+
+В таких случаях обычно возвращается **HTTP-код статуса ответа** в диапазоне **400** (от 400 до 499).
+
+Они похожи на двухсотые HTTP статус-коды (от 200 до 299), которые означают, что запрос обработан успешно.
+
+Четырёхсотые статус-коды означают, что ошибка произошла по вине клиента.
+
+Помните ли ошибки **"404 Not Found "** (и шутки) ?
+
+## Использование `HTTPException`
+
+Для возврата клиенту HTTP-ответов с ошибками используется `HTTPException`.
+
+### Импортируйте `HTTPException`
+
+{* ../../docs_src/handling_errors/tutorial001.py hl[1] *}
+
+### Вызовите `HTTPException` в своем коде
+
+`HTTPException` - это обычное исключение Python с дополнительными данными, актуальными для API.
+
+Поскольку это исключение Python, то его не `возвращают`, а `вызывают`.
+
+Это также означает, что если вы находитесь внутри функции, которая вызывается внутри вашей *функции операции пути*, и вы поднимаете `HTTPException` внутри этой функции, то она не будет выполнять остальной код в *функции операции пути*, а сразу завершит запрос и отправит HTTP-ошибку из `HTTPException` клиенту.
+
+О том, насколько выгоднее `вызывать` исключение, чем `возвращать` значение, будет рассказано в разделе, посвященном зависимостям и безопасности.
+
+В данном примере, когда клиент запрашивает элемент по несуществующему ID, возникает исключение со статус-кодом `404`:
+
+{* ../../docs_src/handling_errors/tutorial001.py hl[11] *}
+
+### Возвращаемый ответ
+
+Если клиент запросит `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. Например, для некоторых типов безопасности.
+
+Скорее всего, вам не потребуется использовать его непосредственно в коде.
+
+Но в случае, если это необходимо для продвинутого сценария, можно добавить пользовательские заголовки:
+
+{* ../../docs_src/handling_errors/tutorial002.py hl[14] *}
+
+## Установка пользовательских обработчиков исключений
+
+Вы можете добавить пользовательские обработчики исключений с помощью то же самое исключение - утилиты от Starlette.
+
+Допустим, у вас есть пользовательское исключение `UnicornException`, которое вы (или используемая вами библиотека) можете `вызвать`.
+
+И вы хотите обрабатывать это исключение глобально с помощью FastAPI.
+
+Можно добавить собственный обработчик исключений с помощью `@app.exception_handler()`:
+
+{* ../../docs_src/handling_errors/tutorial003.py hl[5:7,13:18,24] *}
+
+Здесь, если запросить `/unicorns/yolo`, то *операция пути* вызовет `UnicornException`.
+
+Но оно будет обработано `unicorn_exception_handler`.
+
+Таким образом, вы получите чистую ошибку с кодом состояния HTTP `418` и содержимым JSON:
+
+```JSON
+{"message": "Oops! yolo did something. There goes a rainbow..."}
+```
+
+/// note | Технические детали
+
+Также можно использовать `from starlette.requests import Request` и `from starlette.responses import JSONResponse`.
+
+**FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette. То же самое касается и `Request`.
+
+///
+
+## Переопределение стандартных обработчиков исключений
+
+**FastAPI** имеет некоторые обработчики исключений по умолчанию.
+
+Эти обработчики отвечают за возврат стандартных JSON-ответов при `вызове` `HTTPException` и при наличии в запросе недопустимых данных.
+
+Вы можете переопределить эти обработчики исключений на свои собственные.
+
+### Переопределение исключений проверки запроса
+
+Когда запрос содержит недопустимые данные, **FastAPI** внутренне вызывает ошибку `RequestValidationError`.
+
+А также включает в себя обработчик исключений по умолчанию.
+
+Чтобы переопределить его, импортируйте `RequestValidationError` и используйте его с `@app.exception_handler(RequestValidationError)` для создания обработчика исключений.
+
+Обработчик исключения получит объект `Request` и исключение.
+
+{* ../../docs_src/handling_errors/tutorial004.py hl[2,14:16] *}
+
+Теперь, если перейти к `/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:
+
+{* ../../docs_src/handling_errors/tutorial004.py hl[3:4,9:11,22] *}
+
+/// note | Технические детали
+
+Можно также использовать `from starlette.responses import PlainTextResponse`.
+
+**FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette.
+
+///
+
+### Используйте тело `RequestValidationError`
+
+Ошибка `RequestValidationError` содержит полученное `тело` с недопустимыми данными.
+
+Вы можете использовать его при разработке приложения для регистрации тела и его отладки, возврата пользователю и т.д.
+
+{* ../../docs_src/handling_errors/tutorial005.py hl[14] *}
+
+Теперь попробуйте отправить недействительный элемент, например:
+
+```JSON
+{
+ "title": "towel",
+ "size": "XL"
+}
+```
+
+Вы получите ответ о том, что данные недействительны, содержащий следующее тело:
+
+```JSON hl_lines="12-15"
+{
+ "detail": [
+ {
+ "loc": [
+ "body",
+ "size"
+ ],
+ "msg": "value is not a valid integer",
+ "type": "type_error.integer"
+ }
+ ],
+ "body": {
+ "title": "towel",
+ "size": "XL"
+ }
+}
+```
+
+#### `HTTPException` в FastAPI или в Starlette
+
+**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`:
+
+{* ../../docs_src/handling_errors/tutorial006.py hl[2:5,15,21] *}
+
+В этом примере вы просто `выводите в терминал` ошибку с очень выразительным сообщением, но идея вам понятна. Вы можете использовать исключение, а затем просто повторно использовать стандартные обработчики исключений.
diff --git a/docs/ru/docs/tutorial/header-param-models.md b/docs/ru/docs/tutorial/header-param-models.md
new file mode 100644
index 000000000..4f54e3e15
--- /dev/null
+++ b/docs/ru/docs/tutorial/header-param-models.md
@@ -0,0 +1,72 @@
+# Модели Header-параметров
+
+Если у вас есть группа связанных **header-параметров**, то вы можете объединить их в одну **Pydantic-модель**.
+
+Это позволит вам **переиспользовать модель** в **разных местах**, а также задать валидацию и метаданные сразу для всех параметров. 😎
+
+/// note | Заметка
+
+Этот функционал доступен в FastAPI начиная с версии `0.115.0`. 🤓
+
+///
+
+## Header-параметры в виде Pydantic-модели
+
+Объявите нужные **header-параметры** в **Pydantic-модели** и затем аннотируйте параметр как `Header`:
+
+{* ../../docs_src/header_param_models/tutorial001_an_py310.py hl[9:14,18] *}
+
+**FastAPI** **извлечёт** данные для **каждого поля** из **заголовков** запроса и выдаст заданную вами Pydantic-модель.
+
+## Проверьте документацию
+
+Вы можете посмотреть нужные header-параметры в графическом интерфейсе сгенерированной документации по пути `/docs`:
+
+contact
Параметр | Тип | Описание |
---|---|---|
name | str | Идентификационное имя контактного лица/организации. |
url | str | URL указывающий на контактную информацию. ДОЛЖЕН быть в формате URL. |
email | str | Email адрес контактного лица/организации. ДОЛЖЕН быть в формате email адреса. |
license_info
Параметр | Тип | Описание |
---|---|---|
name | str | ОБЯЗАТЕЛЬНО (если установлен параметр license_info ). Название лицензии, используемой для API |
url | str | URL, указывающий на лицензию, используемую для API. ДОЛЖЕН быть в формате URL. |
kwargs
, даже если у них нет значений по умолчанию.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *}
+
+### Лучше с `Annotated`
+
+Имейте в виду, что если вы используете `Annotated`, то, поскольку вы не используете значений по умолчанию для параметров функции, то у вас не возникнет подобной проблемы и вам не придётся использовать `*`.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py hl[10] *}
+
+## Валидация числовых данных: больше или равно
+
+С помощью `Query` и `Path` (и других классов, которые мы разберём позже) вы можете добавлять ограничения для числовых данных.
+
+В этом примере при указании `ge=1`, параметр `item_id` должен быть больше или равен `1` ("`g`reater than or `e`qual").
+
+{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py hl[10] *}
+
+## Валидация числовых данных: больше и меньше или равно
+
+То же самое применимо к:
+
+* `gt`: больше (`g`reater `t`han)
+* `le`: меньше или равно (`l`ess than or `e`qual)
+
+{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py hl[10] *}
+
+## Валидация числовых данных: числа с плавающей точкой, больше и меньше
+
+Валидация также применима к значениям типа `float`.
+
+В этом случае становится важной возможность добавить ограничение gt
, вместо ge
, поскольку в таком случае вы можете, например, создать ограничение, чтобы значение было больше `0`, даже если оно меньше `1`.
+
+Таким образом, `0.5` будет корректным значением. А `0.0` или `0` — нет.
+
+То же самое справедливо и для lt
.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py hl[13] *}
+
+## Резюме
+
+С помощью `Query`, `Path` (и других классов, которые мы пока не затронули) вы можете добавлять метаданные и строковую валидацию тем же способом, как и в главе [Query-параметры и валидация строк](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 | Технические детали
+
+`Query`, `Path` и другие "классы", которые вы импортируете из `fastapi`, на самом деле являются функциями, которые при вызове возвращают экземпляры одноимённых классов.
+
+Объект `Query`, который вы импортируете, является функцией. И при вызове она возвращает экземпляр одноимённого класса `Query`.
+
+Использование функций (вместо использования классов напрямую) нужно для того, чтобы ваш редактор не подсвечивал ошибки, связанные с их типами.
+
+Таким образом вы можете использовать привычный вам редактор и инструменты разработки, не добавляя дополнительных конфигураций для игнорирования подобных ошибок.
+
+///
diff --git a/docs/ru/docs/tutorial/path-params.md b/docs/ru/docs/tutorial/path-params.md
new file mode 100644
index 000000000..5c2d82a65
--- /dev/null
+++ b/docs/ru/docs/tutorial/path-params.md
@@ -0,0 +1,255 @@
+# Path-параметры
+
+Вы можете определить "параметры" или "переменные" пути, используя синтаксис форматированных строк Python:
+
+{* ../../docs_src/path_params/tutorial001.py hl[6:7] *}
+
+Значение параметра пути `item_id` будет передано в функцию в качестве аргумента `item_id`.
+
+Если запустите этот пример и перейдёте по адресу: http://127.0.0.1:8000/items/foo, то увидите ответ:
+
+```JSON
+{"item_id":"foo"}
+```
+
+## Параметры пути с типами
+
+Вы можете объявить тип параметра пути в функции, используя стандартные аннотации типов Python.
+
+{* ../../docs_src/path_params/tutorial002.py hl[7] *}
+
+Здесь, `item_id` объявлен типом `int`.
+
+/// check | Заметка
+
+Это обеспечит поддержку редактора внутри функции (проверка ошибок, автодополнение и т.п.).
+
+///
+
+## Преобразование данных
+
+Если запустите этот пример и перейдёте по адресу: http://127.0.0.1:8000/items/3, то увидите ответ:
+
+```JSON
+{"item_id":3}
+```
+
+/// check | Заметка
+
+Обратите внимание на значение `3`, которое получила (и вернула) функция. Это целочисленный Python `int`, а не строка `"3"`.
+
+Используя определения типов, **FastAPI** выполняет автоматический "парсинг" запросов.
+
+///
+
+## Проверка данных
+
+Если откроете браузер по адресу http://127.0.0.1:8000/items/foo, то увидите интересную HTTP-ошибку:
+
+```JSON
+{
+ "detail": [
+ {
+ "loc": [
+ "path",
+ "item_id"
+ ],
+ "msg": "value is not a valid integer",
+ "type": "type_error.integer"
+ }
+ ]
+}
+```
+
+из-за того, что параметр пути `item_id` имеет значение `"foo"`, которое не является типом `int`.
+
+Та же ошибка возникнет, если вместо `int` передать `float` , например: http://127.0.0.1:8000/items/4.2
+
+/// check | Заметка
+
+**FastAPI** обеспечивает проверку типов, используя всё те же определения типов.
+
+Обратите внимание, что в тексте ошибки явно указано место не прошедшее проверку.
+
+Это очень полезно при разработке и отладке кода, который взаимодействует с API.
+
+///
+
+## Документация
+
+И теперь, когда откроете браузер по адресу: http://127.0.0.1:8000/docs, то увидите вот такую автоматически сгенерированную документацию API:
+
+POST
.
+
+///
+
+/// warning | Внимание
+
+В операции *функции операции пути* можно объявить несколько параметров `File` и `Form`, но нельзя также объявлять поля `Body`, которые предполагается получить в виде JSON, поскольку тело запроса будет закодировано с помощью `multipart/form-data`, а не `application/json`.
+
+Это не является ограничением **FastAPI**, это часть протокола HTTP.
+
+///
+
+## Необязательная загрузка файлов
+
+Вы можете сделать загрузку файла необязательной, используя стандартные аннотации типов и установив значение по умолчанию `None`:
+
+{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *}
+
+## `UploadFile` с дополнительными метаданными
+
+Вы также можете использовать `File()` вместе с `UploadFile`, например, для установки дополнительных метаданных:
+
+{* ../../docs_src/request_files/tutorial001_03_an_py39.py hl[9,15] *}
+
+## Загрузка нескольких файлов
+
+Можно одновременно загружать несколько файлов.
+
+Они будут связаны с одним и тем же "полем формы", отправляемым с помощью данных формы.
+
+Для этого необходимо объявить список `bytes` или `UploadFile`:
+
+{* ../../docs_src/request_files/tutorial002_an_py39.py hl[10,15] *}
+
+Вы получите, как и было объявлено, список `list` из `bytes` или `UploadFile`.
+
+/// note | Technical Details
+
+Можно также использовать `from starlette.responses import HTMLResponse`.
+
+**FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette.
+
+///
+
+### Загрузка нескольких файлов с дополнительными метаданными
+
+Так же, как и раньше, вы можете использовать `File()` для задания дополнительных параметров, даже для `UploadFile`:
+
+{* ../../docs_src/request_files/tutorial003_an_py39.py hl[11,18:20] *}
+
+## Резюме
+
+Используйте `File`, `bytes` и `UploadFile` для работы с файлами, которые будут загружаться и передаваться в виде данных формы.
diff --git a/docs/ru/docs/tutorial/request-form-models.md b/docs/ru/docs/tutorial/request-form-models.md
new file mode 100644
index 000000000..1034ed27f
--- /dev/null
+++ b/docs/ru/docs/tutorial/request-form-models.md
@@ -0,0 +1,78 @@
+# Модели форм
+
+Вы можете использовать **Pydantic-модели** для объявления **полей форм** в FastAPI.
+
+/// info | Дополнительная информация
+
+Чтобы использовать формы, сначала установите `python-multipart`.
+
+Убедитесь, что вы создали и активировали [виртуальное окружение](../virtual-environments.md){.internal-link target=_blank}, а затем установите пакет, например:
+
+```console
+$ pip install python-multipart
+```
+
+///
+
+/// note | Заметка
+
+Этот функционал доступен с версии `0.113.0`. 🤓
+
+///
+
+## Pydantic-модель для формы
+
+Вам просто нужно объявить **Pydantic-модель** с полями, которые вы хотите получить как **поля формы**, а затем объявить параметр как `Form`:
+
+{* ../../docs_src/request_form_models/tutorial001_an_py39.py hl[9:11,15] *}
+
+**FastAPI** **извлечёт** данные для **каждого поля** из **данных формы** в запросе и выдаст вам объявленную Pydantic-модель.
+
+## Проверка сгенерированной документации
+
+Вы можете посмотреть поля формы в графическом интерфейсе Документации по пути `/docs`:
+
+- FastAPI framework, high performance, easy to learn, fast to code, ready for production -
- - ---- - -**Documentation**: https://fastapi.tiangolo.com - -**Source Code**: https://github.com/tiangolo/fastapi - ---- - -FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.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 -%} -async def
...uvicorn main:app --reload
...ujson
- for faster JSON "parsing".
-* email_validator
- for email validation.
-
-Used by Starlette:
-
-* httpx
- Required if you want to use the `TestClient`.
-* jinja2
- Required if you want to use the default template configuration.
-* python-multipart
- Required if you want to support form "parsing", with `request.form()`.
-* itsdangerous
- Required for `SessionMiddleware` support.
-* pyyaml
- Required for Starlette's `SchemaGenerator` support (you probably don't need it with FastAPI).
-* 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/sq/mkdocs.yml b/docs/sq/mkdocs.yml
deleted file mode 100644
index ca20bce30..000000000
--- a/docs/sq/mkdocs.yml
+++ /dev/null
@@ -1,157 +0,0 @@
-site_name: FastAPI
-site_description: FastAPI framework, high performance, easy to learn, fast to code, ready for production
-site_url: https://fastapi.tiangolo.com/sq/
-theme:
- name: material
- custom_dir: overrides
- palette:
- - media: '(prefers-color-scheme: light)'
- scheme: default
- primary: teal
- accent: amber
- toggle:
- icon: material/lightbulb
- name: Switch to light mode
- - media: '(prefers-color-scheme: dark)'
- scheme: slate
- primary: teal
- accent: amber
- toggle:
- icon: material/lightbulb-outline
- name: Switch to dark mode
- features:
- - search.suggest
- - search.highlight
- - content.tabs.link
- icon:
- repo: fontawesome/brands/github-alt
- logo: https://fastapi.tiangolo.com/img/icon-white.svg
- favicon: https://fastapi.tiangolo.com/img/favicon.png
- language: en
-repo_name: tiangolo/fastapi
-repo_url: https://github.com/tiangolo/fastapi
-edit_uri: ''
-plugins:
-- search
-- markdownextradata:
- data: data
-nav:
-- FastAPI: index.md
-- Languages:
- - en: /
- - az: /az/
- - cs: /cs/
- - de: /de/
- - em: /em/
- - es: /es/
- - fa: /fa/
- - fr: /fr/
- - he: /he/
- - hy: /hy/
- - id: /id/
- - it: /it/
- - ja: /ja/
- - ko: /ko/
- - nl: /nl/
- - pl: /pl/
- - pt: /pt/
- - ru: /ru/
- - sq: /sq/
- - sv: /sv/
- - ta: /ta/
- - tr: /tr/
- - uk: /uk/
- - zh: /zh/
-markdown_extensions:
-- toc:
- permalink: true
-- markdown.extensions.codehilite:
- guess_lang: false
-- mdx_include:
- base_path: docs
-- admonition
-- codehilite
-- extra
-- pymdownx.superfences:
- custom_fences:
- - name: mermaid
- class: mermaid
- format: !!python/name:pymdownx.superfences.fence_code_format ''
-- pymdownx.tabbed:
- alternate_style: true
-- attr_list
-- md_in_html
-extra:
- analytics:
- provider: google
- property: G-YNEVN69SC3
- social:
- - icon: fontawesome/brands/github-alt
- link: https://github.com/tiangolo/fastapi
- - icon: fontawesome/brands/discord
- link: https://discord.gg/VQjSZaeJmf
- - icon: fontawesome/brands/twitter
- link: https://twitter.com/fastapi
- - icon: fontawesome/brands/linkedin
- link: https://www.linkedin.com/in/tiangolo
- - icon: fontawesome/brands/dev
- link: https://dev.to/tiangolo
- - icon: fontawesome/brands/medium
- link: https://medium.com/@tiangolo
- - icon: fontawesome/solid/globe
- link: https://tiangolo.com
- alternate:
- - link: /
- name: en - English
- - link: /az/
- name: az
- - link: /cs/
- name: cs
- - link: /de/
- name: de
- - link: /em/
- name: 😉
- - link: /es/
- name: es - español
- - link: /fa/
- name: fa
- - link: /fr/
- name: fr - français
- - link: /he/
- name: he
- - link: /hy/
- name: hy
- - link: /id/
- name: id
- - link: /it/
- name: it - italiano
- - link: /ja/
- name: ja - 日本語
- - link: /ko/
- name: ko - 한국어
- - link: /nl/
- name: nl
- - link: /pl/
- name: pl
- - link: /pt/
- name: pt - português
- - link: /ru/
- name: ru - русский язык
- - link: /sq/
- name: sq - shqip
- - link: /sv/
- name: sv - svenska
- - link: /ta/
- name: ta - தமிழ்
- - link: /tr/
- name: tr - Türkçe
- - link: /uk/
- name: uk - українська мова
- - link: /zh/
- name: zh - 汉语
-extra_css:
-- https://fastapi.tiangolo.com/css/termynal.css
-- https://fastapi.tiangolo.com/css/custom.css
-extra_javascript:
-- https://fastapi.tiangolo.com/js/termynal.js
-- https://fastapi.tiangolo.com/js/custom.js
diff --git a/docs/sq/overrides/.gitignore b/docs/sq/overrides/.gitignore
deleted file mode 100644
index e69de29bb..000000000
diff --git a/docs/sv/docs/index.md b/docs/sv/docs/index.md
deleted file mode 100644
index 23143a96f..000000000
--- a/docs/sv/docs/index.md
+++ /dev/null
@@ -1,468 +0,0 @@
-
-{!../../../docs/missing-translation.md!}
-
-
-
-- FastAPI framework, high performance, easy to learn, fast to code, ready for production -
- - ---- - -**Documentation**: https://fastapi.tiangolo.com - -**Source Code**: https://github.com/tiangolo/fastapi - ---- - -FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.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 -%} -async def
...uvicorn main:app --reload
...ujson
- for faster JSON "parsing".
-* email_validator
- for email validation.
-
-Used by Starlette:
-
-* httpx
- Required if you want to use the `TestClient`.
-* jinja2
- Required if you want to use the default template configuration.
-* python-multipart
- Required if you want to support form "parsing", with `request.form()`.
-* itsdangerous
- Required for `SessionMiddleware` support.
-* pyyaml
- Required for Starlette's `SchemaGenerator` support (you probably don't need it with FastAPI).
-* ujson
- Required if you want to use `UJSONResponse`.
-
-Used by FastAPI / Starlette:
-
-* uvicorn
- for the server that loads and serves your application.
-* orjson
- Required if you want to use `ORJSONResponse`.
-
-You can install all of these with `pip install "fastapi[all]"`.
-
-## License
-
-This project is licensed under the terms of the MIT license.
diff --git a/docs/sv/mkdocs.yml b/docs/sv/mkdocs.yml
deleted file mode 100644
index ce6ee3f83..000000000
--- a/docs/sv/mkdocs.yml
+++ /dev/null
@@ -1,157 +0,0 @@
-site_name: FastAPI
-site_description: FastAPI framework, high performance, easy to learn, fast to code, ready for production
-site_url: https://fastapi.tiangolo.com/sv/
-theme:
- name: material
- custom_dir: overrides
- palette:
- - media: '(prefers-color-scheme: light)'
- scheme: default
- primary: teal
- accent: amber
- toggle:
- icon: material/lightbulb
- name: Switch to light mode
- - media: '(prefers-color-scheme: dark)'
- scheme: slate
- primary: teal
- accent: amber
- toggle:
- icon: material/lightbulb-outline
- name: Switch to dark mode
- features:
- - search.suggest
- - search.highlight
- - content.tabs.link
- icon:
- repo: fontawesome/brands/github-alt
- logo: https://fastapi.tiangolo.com/img/icon-white.svg
- favicon: https://fastapi.tiangolo.com/img/favicon.png
- language: sv
-repo_name: tiangolo/fastapi
-repo_url: https://github.com/tiangolo/fastapi
-edit_uri: ''
-plugins:
-- search
-- markdownextradata:
- data: data
-nav:
-- FastAPI: index.md
-- Languages:
- - en: /
- - az: /az/
- - cs: /cs/
- - de: /de/
- - em: /em/
- - es: /es/
- - fa: /fa/
- - fr: /fr/
- - he: /he/
- - hy: /hy/
- - id: /id/
- - it: /it/
- - ja: /ja/
- - ko: /ko/
- - nl: /nl/
- - pl: /pl/
- - pt: /pt/
- - ru: /ru/
- - sq: /sq/
- - sv: /sv/
- - ta: /ta/
- - tr: /tr/
- - uk: /uk/
- - zh: /zh/
-markdown_extensions:
-- toc:
- permalink: true
-- markdown.extensions.codehilite:
- guess_lang: false
-- mdx_include:
- base_path: docs
-- admonition
-- codehilite
-- extra
-- pymdownx.superfences:
- custom_fences:
- - name: mermaid
- class: mermaid
- format: !!python/name:pymdownx.superfences.fence_code_format ''
-- pymdownx.tabbed:
- alternate_style: true
-- attr_list
-- md_in_html
-extra:
- analytics:
- provider: google
- property: G-YNEVN69SC3
- social:
- - icon: fontawesome/brands/github-alt
- link: https://github.com/tiangolo/fastapi
- - icon: fontawesome/brands/discord
- link: https://discord.gg/VQjSZaeJmf
- - icon: fontawesome/brands/twitter
- link: https://twitter.com/fastapi
- - icon: fontawesome/brands/linkedin
- link: https://www.linkedin.com/in/tiangolo
- - icon: fontawesome/brands/dev
- link: https://dev.to/tiangolo
- - icon: fontawesome/brands/medium
- link: https://medium.com/@tiangolo
- - icon: fontawesome/solid/globe
- link: https://tiangolo.com
- alternate:
- - link: /
- name: en - English
- - link: /az/
- name: az
- - link: /cs/
- name: cs
- - link: /de/
- name: de
- - link: /em/
- name: 😉
- - link: /es/
- name: es - español
- - link: /fa/
- name: fa
- - link: /fr/
- name: fr - français
- - link: /he/
- name: he
- - link: /hy/
- name: hy
- - link: /id/
- name: id
- - link: /it/
- name: it - italiano
- - link: /ja/
- name: ja - 日本語
- - link: /ko/
- name: ko - 한국어
- - link: /nl/
- name: nl
- - link: /pl/
- name: pl
- - link: /pt/
- name: pt - português
- - link: /ru/
- name: ru - русский язык
- - link: /sq/
- name: sq - shqip
- - link: /sv/
- name: sv - svenska
- - link: /ta/
- name: ta - தமிழ்
- - link: /tr/
- name: tr - Türkçe
- - link: /uk/
- name: uk - українська мова
- - link: /zh/
- name: zh - 汉语
-extra_css:
-- https://fastapi.tiangolo.com/css/termynal.css
-- https://fastapi.tiangolo.com/css/custom.css
-extra_javascript:
-- https://fastapi.tiangolo.com/js/termynal.js
-- https://fastapi.tiangolo.com/js/custom.js
diff --git a/docs/sv/overrides/.gitignore b/docs/sv/overrides/.gitignore
deleted file mode 100644
index e69de29bb..000000000
diff --git a/docs/ta/mkdocs.yml b/docs/ta/mkdocs.yml
deleted file mode 100644
index d66fc5740..000000000
--- a/docs/ta/mkdocs.yml
+++ /dev/null
@@ -1,157 +0,0 @@
-site_name: FastAPI
-site_description: FastAPI framework, high performance, easy to learn, fast to code, ready for production
-site_url: https://fastapi.tiangolo.com/ta/
-theme:
- name: material
- custom_dir: overrides
- palette:
- - media: '(prefers-color-scheme: light)'
- scheme: default
- primary: teal
- accent: amber
- toggle:
- icon: material/lightbulb
- name: Switch to light mode
- - media: '(prefers-color-scheme: dark)'
- scheme: slate
- primary: teal
- accent: amber
- toggle:
- icon: material/lightbulb-outline
- name: Switch to dark mode
- features:
- - search.suggest
- - search.highlight
- - content.tabs.link
- icon:
- repo: fontawesome/brands/github-alt
- logo: https://fastapi.tiangolo.com/img/icon-white.svg
- favicon: https://fastapi.tiangolo.com/img/favicon.png
- language: en
-repo_name: tiangolo/fastapi
-repo_url: https://github.com/tiangolo/fastapi
-edit_uri: ''
-plugins:
-- search
-- markdownextradata:
- data: data
-nav:
-- FastAPI: index.md
-- Languages:
- - en: /
- - az: /az/
- - cs: /cs/
- - de: /de/
- - em: /em/
- - es: /es/
- - fa: /fa/
- - fr: /fr/
- - he: /he/
- - hy: /hy/
- - id: /id/
- - it: /it/
- - ja: /ja/
- - ko: /ko/
- - nl: /nl/
- - pl: /pl/
- - pt: /pt/
- - ru: /ru/
- - sq: /sq/
- - sv: /sv/
- - ta: /ta/
- - tr: /tr/
- - uk: /uk/
- - zh: /zh/
-markdown_extensions:
-- toc:
- permalink: true
-- markdown.extensions.codehilite:
- guess_lang: false
-- mdx_include:
- base_path: docs
-- admonition
-- codehilite
-- extra
-- pymdownx.superfences:
- custom_fences:
- - name: mermaid
- class: mermaid
- format: !!python/name:pymdownx.superfences.fence_code_format ''
-- pymdownx.tabbed:
- alternate_style: true
-- attr_list
-- md_in_html
-extra:
- analytics:
- provider: google
- property: G-YNEVN69SC3
- social:
- - icon: fontawesome/brands/github-alt
- link: https://github.com/tiangolo/fastapi
- - icon: fontawesome/brands/discord
- link: https://discord.gg/VQjSZaeJmf
- - icon: fontawesome/brands/twitter
- link: https://twitter.com/fastapi
- - icon: fontawesome/brands/linkedin
- link: https://www.linkedin.com/in/tiangolo
- - icon: fontawesome/brands/dev
- link: https://dev.to/tiangolo
- - icon: fontawesome/brands/medium
- link: https://medium.com/@tiangolo
- - icon: fontawesome/solid/globe
- link: https://tiangolo.com
- alternate:
- - link: /
- name: en - English
- - link: /az/
- name: az
- - link: /cs/
- name: cs
- - link: /de/
- name: de
- - link: /em/
- name: 😉
- - link: /es/
- name: es - español
- - link: /fa/
- name: fa
- - link: /fr/
- name: fr - français
- - link: /he/
- name: he
- - link: /hy/
- name: hy
- - link: /id/
- name: id
- - link: /it/
- name: it - italiano
- - link: /ja/
- name: ja - 日本語
- - link: /ko/
- name: ko - 한국어
- - link: /nl/
- name: nl
- - link: /pl/
- name: pl
- - link: /pt/
- name: pt - português
- - link: /ru/
- name: ru - русский язык
- - link: /sq/
- name: sq - shqip
- - link: /sv/
- name: sv - svenska
- - link: /ta/
- name: ta - தமிழ்
- - link: /tr/
- name: tr - Türkçe
- - link: /uk/
- name: uk - українська мова
- - link: /zh/
- name: zh - 汉语
-extra_css:
-- https://fastapi.tiangolo.com/css/termynal.css
-- https://fastapi.tiangolo.com/css/custom.css
-extra_javascript:
-- https://fastapi.tiangolo.com/js/termynal.js
-- https://fastapi.tiangolo.com/js/custom.js
diff --git a/docs/ta/overrides/.gitignore b/docs/ta/overrides/.gitignore
deleted file mode 100644
index e69de29bb..000000000
diff --git a/docs/tr/docs/about/index.md b/docs/tr/docs/about/index.md
new file mode 100644
index 000000000..e9dee5217
--- /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/advanced/index.md b/docs/tr/docs/advanced/index.md
new file mode 100644
index 000000000..836e63c8a
--- /dev/null
+++ b/docs/tr/docs/advanced/index.md
@@ -0,0 +1,36 @@
+# Gelişmiş Kullanıcı Rehberi
+
+## Ek Özellikler
+
+[Tutorial - User Guide](../tutorial/index.md){.internal-link target=_blank} sayfası **FastAPI**'ın tüm ana özelliklerini tanıtmaya yetecektir.
+
+İlerleyen bölümlerde diğer seçenekler, konfigürasyonlar ve ek özellikleri göreceğiz.
+
+/// tip | İpucu
+
+Sonraki bölümler **mutlaka "gelişmiş" olmak zorunda değildir**.
+
+Kullanım şeklinize bağlı olarak, çözümünüz bu bölümlerden birinde olabilir.
+
+///
+
+## Önce Öğreticiyi Okuyun
+
+[Tutorial - User Guide](../tutorial/index.md){.internal-link target=_blank} sayfasındaki bilgilerle **FastAPI**'nın çoğu özelliğini kullanabilirsiniz.
+
+Sonraki bölümler bu sayfayı okuduğunuzu ve bu ana fikirleri bildiğinizi varsayarak hazırlanmıştır.
+
+## Diğer Kurslar
+
+[Tutorial - User Guide](../tutorial/index.md){.internal-link target=_blank} sayfası ve bu **Gelişmiş Kullanıcı Rehberi**, öğretici bir kılavuz (bir kitap gibi) şeklinde yazılmıştır ve **FastAPI'ı öğrenmek** için yeterli olsa da, ek kurslarla desteklemek isteyebilirsiniz.
+
+Belki de öğrenme tarzınıza daha iyi uyduğu için başka kursları tercih edebilirsiniz.
+
+Bazı kurs sağlayıcıları ✨ [**FastAPI destekçileridir**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨, bu FastAPI ve **ekosisteminin** sürekli ve sağlıklı bir şekilde **gelişmesini** sağlar.
+
+Ayrıca, size **iyi bir öğrenme deneyimi** sağlamakla kalmayıp, **iyi ve sağlıklı bir framework** olan FastAPI'a ve ve **topluluğuna** (yani size) olan gerçek bağlılıklarını gösterir.
+
+Onların kurslarını denemek isteyebilirsiniz:
+
+* Talk Python Training
+* Test-Driven Development
diff --git a/docs/tr/docs/advanced/security/index.md b/docs/tr/docs/advanced/security/index.md
new file mode 100644
index 000000000..709f74c72
--- /dev/null
+++ b/docs/tr/docs/advanced/security/index.md
@@ -0,0 +1,19 @@
+# Gelişmiş Güvenlik
+
+## Ek Özellikler
+
+[Tutorial - User Guide: Security](../../tutorial/security/index.md){.internal-link target=_blank} sayfasında ele alınanların dışında güvenlikle ilgili bazı ek özellikler vardır.
+
+/// tip | İpucu
+
+Sonraki bölümler **mutlaka "gelişmiş" olmak zorunda değildir**.
+
+Kullanım şeklinize bağlı olarak, çözümünüz bu bölümlerden birinde olabilir.
+
+///
+
+## Önce Öğreticiyi Okuyun
+
+Sonraki bölümler [Tutorial - User Guide: Security](../../tutorial/security/index.md){.internal-link target=_blank} sayfasını okuduğunuzu varsayarak hazırlanmıştır.
+
+Bu bölümler aynı kavramlara dayanır, ancak bazı ek işlevsellikler sağlar.
diff --git a/docs/tr/docs/advanced/testing-websockets.md b/docs/tr/docs/advanced/testing-websockets.md
new file mode 100644
index 000000000..ddacca449
--- /dev/null
+++ b/docs/tr/docs/advanced/testing-websockets.md
@@ -0,0 +1,13 @@
+# WebSockets'i Test Etmek
+
+WebSockets testi yapmak için `TestClient`'ı kullanabilirsiniz.
+
+Bu işlem için, `TestClient`'ı bir `with` ifadesinde kullanarak WebSocket'e bağlanabilirsiniz:
+
+{* ../../docs_src/app_testing/tutorial002.py hl[27:31] *}
+
+/// note | Not
+
+Daha fazla detay için Starlette'in Websockets'i Test Etmek dokümantasyonunu inceleyin.
+
+///
diff --git a/docs/tr/docs/advanced/wsgi.md b/docs/tr/docs/advanced/wsgi.md
new file mode 100644
index 000000000..00815a4b2
--- /dev/null
+++ b/docs/tr/docs/advanced/wsgi.md
@@ -0,0 +1,35 @@
+# WSGI - Flask, Django ve Daha Fazlasını FastAPI ile Kullanma
+
+WSGI uygulamalarını [Sub Applications - Mounts](sub-applications.md){.internal-link target=_blank}, [Behind a Proxy](behind-a-proxy.md){.internal-link target=_blank} bölümlerinde gördüğünüz gibi bağlayabilirsiniz.
+
+Bunun için `WSGIMiddleware` ile Flask, Django vb. WSGI uygulamanızı sarmalayabilir ve FastAPI'ya bağlayabilirsiniz.
+
+## `WSGIMiddleware` Kullanımı
+
+`WSGIMiddleware`'ı projenize dahil edin.
+
+Ardından WSGI (örneğin Flask) uygulamanızı middleware ile sarmalayın.
+
+Son olarak da bir yol altında bağlama işlemini gerçekleştirin.
+
+{* ../../docs_src/wsgi/tutorial001.py hl[2:3,23] *}
+
+## Kontrol Edelim
+
+Artık `/v1/` yolunun altındaki her istek Flask uygulaması tarafından işlenecektir.
+
+Geri kalanı ise **FastAPI** tarafından işlenecektir.
+
+Eğer uygulamanızı çalıştırıp http://localhost:8000/v1/ adresine giderseniz, Flask'tan gelen yanıtı göreceksiniz:
+
+```txt
+Hello, World from Flask!
+```
+
+Eğer http://localhost:8000/v2/ adresine giderseniz, FastAPI'dan gelen yanıtı göreceksiniz:
+
+```JSON
+{
+ "message": "Hello World"
+}
+```
diff --git a/docs/tr/docs/alternatives.md b/docs/tr/docs/alternatives.md
new file mode 100644
index 000000000..c98b966b5
--- /dev/null
+++ b/docs/tr/docs/alternatives.md
@@ -0,0 +1,483 @@
+# 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 000000000..558a79cb7
--- /dev/null
+++ b/docs/tr/docs/async.md
@@ -0,0 +1,407 @@
+# 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
+```
+
+/// note | 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ı](index.md#performans){.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 1ce3c758f..eb5472869 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/deployment/cloud.md b/docs/tr/docs/deployment/cloud.md
new file mode 100644
index 000000000..5639567d4
--- /dev/null
+++ b/docs/tr/docs/deployment/cloud.md
@@ -0,0 +1,17 @@
+# FastAPI Uygulamasını Bulut Sağlayıcılar Üzerinde Yayınlama
+
+FastAPI uygulamasını yayınlamak için hemen hemen **herhangi bir bulut sağlayıcıyı** kullanabilirsiniz.
+
+Büyük bulut sağlayıcıların çoğu FastAPI uygulamasını yayınlamak için kılavuzlara sahiptir.
+
+## Bulut Sağlayıcılar - Sponsorlar
+
+Bazı bulut sağlayıcılar ✨ [**FastAPI destekçileridir**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨, bu FastAPI ve **ekosisteminin** sürekli ve sağlıklı bir şekilde **gelişmesini** sağlar.
+
+Ayrıca, size **iyi servisler** sağlamakla kalmayıp, **iyi ve sağlıklı bir framework** olan FastAPI'a bağlılıklarını gösterir.
+
+Bu hizmetleri denemek ve kılavuzlarını incelemek isteyebilirsiniz:
+
+* Platform.sh
+* Porter
+* Coherence
diff --git a/docs/tr/docs/deployment/index.md b/docs/tr/docs/deployment/index.md
new file mode 100644
index 000000000..e03bb4ee0
--- /dev/null
+++ b/docs/tr/docs/deployment/index.md
@@ -0,0 +1,21 @@
+# Deployment (Yayınlama)
+
+**FastAPI** uygulamasını deploy etmek oldukça kolaydır.
+
+## Deployment Ne Anlama Gelir?
+
+Bir uygulamayı **deploy** etmek (yayınlamak), uygulamayı **kullanıcılara erişilebilir hale getirmek** için gerekli adımları gerçekleştirmek anlamına gelir.
+
+Bir **Web API** için bu süreç normalde uygulamayı **uzak bir makineye** yerleştirmeyi, iyi performans, kararlılık vb. özellikler sağlayan bir **sunucu programı** ile **kullanıcılarınızın** uygulamaya etkili ve kesintisiz bir şekilde **erişebilmesini** kapsar.
+
+Bu, kodu sürekli olarak değiştirdiğiniz, hata alıp hata giderdiğiniz, geliştirme sunucusunu durdurup yeniden başlattığınız vb. **geliştirme** aşamalarının tam tersidir.
+
+## Deployment Stratejileri
+
+Kullanım durumunuza ve kullandığınız araçlara bağlı olarak bir kaç farklı yol izleyebilirsiniz.
+
+Bir dizi araç kombinasyonunu kullanarak kendiniz **bir sunucu yayınlayabilirsiniz**, yayınlama sürecinin bir kısmını sizin için gerçekleştiren bir **bulut hizmeti** veya diğer olası seçenekleri kullanabilirsiniz.
+
+**FastAPI** uygulamasını yayınlarken aklınızda bulundurmanız gereken ana kavramlardan bazılarını size göstereceğim (ancak bunların çoğu diğer web uygulamaları için de geçerlidir).
+
+Sonraki bölümlerde akılda tutulması gereken diğer ayrıntıları ve yayınlama tekniklerinden bazılarını göreceksiniz. ✨
diff --git a/docs/tr/docs/fastapi-people.md b/docs/tr/docs/fastapi-people.md
deleted file mode 100644
index 3e459036a..000000000
--- a/docs/tr/docs/fastapi-people.md
+++ /dev/null
@@ -1,178 +0,0 @@
-# FastAPI Topluluğu
-
-FastAPI, her kökenden insanı ağırlayan harika bir topluluğa sahip.
-
-## Yazan - Geliştiren
-
-Hey! 👋
-
-İşte bu benim:
-
-{% if people %}
-+ +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/general.md b/docs/tr/docs/how-to/general.md new file mode 100644 index 000000000..cbfa7beb2 --- /dev/null +++ b/docs/tr/docs/how-to/general.md @@ -0,0 +1,39 @@ +# Genel - Nasıl Yapılır - Tarifler + +Bu sayfada genel ve sıkça sorulan sorular için dokümantasyonun diğer sayfalarına yönlendirmeler bulunmaktadır. + +## Veri Filtreleme - Güvenlik + +Döndürmeniz gereken veriden fazlasını döndürmediğinizden emin olmak için, [Tutorial - Response Model - Return Type](../tutorial/response-model.md){.internal-link target=_blank} sayfasını okuyun. + +## Dokümantasyon Etiketleri - OpenAPI + +*Yol operasyonlarınıza* etiketler ekleyerek dokümantasyon arayüzünde gruplar halinde görünmesini sağlamak için, [Tutorial - Path Operation Configurations - Tags](../tutorial/path-operation-configuration.md#tags){.internal-link target=_blank} sayfasını okuyun. + +## Dokümantasyon Özeti ve Açıklaması - OpenAPI + +*Yol operasyonlarınıza* özet ve açıklama ekleyip dokümantasyon arayüzünde görünmesini sağlamak için, [Tutorial - Path Operation Configurations - Summary and Description](../tutorial/path-operation-configuration.md#summary-and-description){.internal-link target=_blank} sayfasını okuyun. + +## Yanıt Açıklaması Dokümantasyonu - OpenAPI + +Dokümantasyon arayüzünde yer alan yanıt açıklamasını tanımlamak için, [Tutorial - Path Operation Configurations - Response description](../tutorial/path-operation-configuration.md#response-description){.internal-link target=_blank} sayfasını okuyun. + +## *Yol Operasyonunu* Kullanımdan Kaldırma - OpenAPI + +Bir *yol işlemi*ni kullanımdan kaldırmak ve bunu dokümantasyon arayüzünde göstermek için, [Tutorial - Path Operation Configurations - Deprecation](../tutorial/path-operation-configuration.md#deprecate-a-path-operation){.internal-link target=_blank} sayfasını okuyun. + +## Herhangi Bir Veriyi JSON Uyumlu Hale Getirme + +Herhangi bir veriyi JSON uyumlu hale getirmek için, [Tutorial - JSON Compatible Encoder](../tutorial/encoder.md){.internal-link target=_blank} sayfasını okuyun. + +## OpenAPI Meta Verileri - Dokümantasyon + +OpenAPI şemanıza lisans, sürüm, iletişim vb. meta veriler eklemek için, [Tutorial - Metadata and Docs URLs](../tutorial/metadata.md){.internal-link target=_blank} sayfasını okuyun. + +## OpenAPI Bağlantı Özelleştirme + +OpenAPI bağlantısını özelleştirmek (veya kaldırmak) için, [Tutorial - Metadata and Docs URLs](../tutorial/metadata.md#openapi-url){.internal-link target=_blank} sayfasını okuyun. + +## OpenAPI Dokümantasyon Bağlantıları + +Dokümantasyonu arayüzünde kullanılan bağlantıları güncellemek için, [Tutorial - Metadata and Docs URLs](../tutorial/metadata.md#docs-urls){.internal-link target=_blank} sayfasını okuyun. diff --git a/docs/tr/docs/how-to/index.md b/docs/tr/docs/how-to/index.md new file mode 100644 index 000000000..26dd9026c --- /dev/null +++ b/docs/tr/docs/how-to/index.md @@ -0,0 +1,13 @@ +# 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 6bd30d709..f666e2d06 100644 --- a/docs/tr/docs/index.md +++ b/docs/tr/docs/index.md @@ -1,50 +1,54 @@ +# FastAPI -{!../../../docs/missing-translation.md!} - +
- 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
--- -**dokümantasyon**: https://fastapi.tiangolo.com +**Dokümantasyon**: https://fastapi.tiangolo.com -**Kaynak kodu**: https://github.com/tiangolo/fastapi +**Kaynak Kod**: https://github.com/fastapi/fastapi --- -FastAPI, Python 3.6+'nın standart type hintlerine dayanan modern ve hızlı (yüksek performanslı) API'lar oluşturmak için kullanılabilecek web framework'ü. - -Ana özellikleri: +FastAPI, Python '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 +63,70 @@ Ana özellikleri: -Other sponsors +Diğer Sponsorlar ## Görüşler +"_[...] 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._" -"_[...] 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._" - -async def
...uvicorn main:app --reload
hakkında...uvicorn main:app --reload
komutuyla ilgili...ujson
- daha hızlı JSON "dönüşümü" için.
-* email_validator
- email doğrulaması için.
+* 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.
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.
+* ujson
- `UJSONResponse` kullanacaksanız gerekli.
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 000000000..52e3aa54d
--- /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/project-generation.md b/docs/tr/docs/project-generation.md
new file mode 100644
index 000000000..c9dc24acc
--- /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 3b9ab9050..b44aa3b9d 100644
--- a/docs/tr/docs/python-types.md
+++ b/docs/tr/docs/python-types.md
@@ -12,16 +12,18 @@ Bu pythonda tip belirteçleri için **hızlı bir başlangıç / bilgi tazeleme
**FastAPI** kullanmayacak olsanız bile tür belirteçleri hakkında bilgi edinmenizde fayda var.
-!!! not
- Python uzmanıysanız ve tip belirteçleri ilgili her şeyi zaten biliyorsanız, sonraki bölüme geçin.
+/// note | Not
+
+Python uzmanıysanız ve tip belirteçleri ilgili her şeyi zaten biliyorsanız, sonraki bölüme geçin.
+
+///
## Motivasyon
Basit bir örnek ile başlayalım:
-```Python
-{!../../../docs_src/python_types/tutorial001.py!}
-```
+{* ../../docs_src/python_types/tutorial001.py *}
+
Programın çıktısı:
@@ -35,9 +37,8 @@ Fonksiyon sırayla şunları yapar:
* `title()` ile değişkenlerin ilk karakterlerini büyütür.
* Değişkenleri aralarında bir boşlukla beraber Birleştirir.
-```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial001.py!}
-```
+{* ../../docs_src/python_types/tutorial001.py hl[2] *}
+
### Düzenle
@@ -79,9 +80,8 @@ Bu kadar.
İşte bunlar "tip belirteçleri":
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial002.py!}
-```
+{* ../../docs_src/python_types/tutorial002.py hl[1] *}
+
Bu, aşağıdaki gibi varsayılan değerleri bildirmekle aynı şey değildir:
@@ -109,9 +109,8 @@ Aradığınızı bulana kadar seçenekleri kaydırabilirsiniz:
Bu fonksiyon, zaten tür belirteçlerine sahip:
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial003.py!}
-```
+{* ../../docs_src/python_types/tutorial003.py hl[1] *}
+
Editör değişkenlerin tiplerini bildiğinden, yalnızca otomatik tamamlama değil, hata kontrolleri de sağlar:
@@ -119,9 +118,8 @@ Editör değişkenlerin tiplerini bildiğinden, yalnızca otomatik tamamlama de
Artık `age` değişkenini `str(age)` olarak kullanmanız gerektiğini biliyorsunuz:
-```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial004.py!}
-```
+{* ../../docs_src/python_types/tutorial004.py hl[2] *}
+
## Tip bildirme
@@ -140,9 +138,8 @@ Yalnızca `str` değil, tüm standart Python tiplerinin bildirebilirsiniz.
* `bool`
* `bytes`
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial005.py!}
-```
+{* ../../docs_src/python_types/tutorial005.py hl[1] *}
+
### Tip parametreleri ile Generic tipler
@@ -158,9 +155,8 @@ Bu tür tip belirteçlerini desteklemek için özel olarak mevcuttur.
From `typing`, import `List` (büyük harf olan `L` ile):
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial006.py!}
-```
+{* ../../docs_src/python_types/tutorial006.py hl[1] *}
+
Değişkenin tipini yine iki nokta üstüste (`:`) ile belirleyin.
@@ -168,14 +164,16 @@ tip olarak `List` kullanın.
Liste, bazı dahili tipleri içeren bir tür olduğundan, bunları köşeli parantez içine alırsınız:
-```Python hl_lines="4"
-{!../../../docs_src/python_types/tutorial006.py!}
-```
+{* ../../docs_src/python_types/tutorial006.py hl[4] *}
+
-!!! ipucu
- Köşeli parantez içindeki bu dahili tiplere "tip parametreleri" denir.
+/// tip | Ipucu
- Bu durumda `str`, `List`e iletilen tür parametresidir.
+Köşeli parantez içindeki bu dahili tiplere "tip parametreleri" denir.
+
+Bu durumda `str`, `List`e iletilen tür parametresidir.
+
+///
Bunun anlamı şudur: "`items` değişkeni bir `list`tir ve bu listedeki öğelerin her biri bir `str`dir".
@@ -193,9 +191,8 @@ Ve yine, editör bunun bir `str` olduğunu biliyor ve bunun için destek s
`Tuple` ve `set`lerin tiplerini bildirmek için de aynısını yapıyoruz:
-```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial007.py!}
-```
+{* ../../docs_src/python_types/tutorial007.py hl[1,4] *}
+
Bu şu anlama geliyor:
@@ -210,9 +207,8 @@ Bir `dict` tanımlamak için virgülle ayrılmış iki parametre verebilirsiniz.
İkinci parametre ise `dict` değerinin `value` değeri içindir:
-```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial008.py!}
-```
+{* ../../docs_src/python_types/tutorial008.py hl[1,4] *}
+
Bu şu anlama gelir:
@@ -225,7 +221,7 @@ Bu şu anlama gelir:
`Optional` bir değişkenin `str`gibi bir tipi olabileceğini ama isteğe bağlı olarak tipinin `None` olabileceğini belirtir:
```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009.py!}
+{!../../docs_src/python_types/tutorial009.py!}
```
`str` yerine `Optional[str]` kullanmak editorün bu değerin her zaman `str` tipinde değil bazen `None` tipinde de olabileceğini belirtir ve hataları tespit etmemizde yardımcı olur.
@@ -249,15 +245,13 @@ Bir değişkenin tipini bir sınıf ile bildirebilirsiniz.
Diyelim ki `name` değerine sahip `Person` sınıfınız var:
-```Python hl_lines="1-3"
-{!../../../docs_src/python_types/tutorial010.py!}
-```
+{* ../../docs_src/python_types/tutorial010.py hl[1:3] *}
+
Sonra bir değişkeni 'Person' tipinde tanımlayabilirsiniz:
-```Python hl_lines="6"
-{!../../../docs_src/python_types/tutorial010.py!}
-```
+{* ../../docs_src/python_types/tutorial010.py hl[6] *}
+
Ve yine bütün editör desteğini alırsınız:
@@ -265,7 +259,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.
@@ -277,12 +271,14 @@ Ve ortaya çıkan nesne üzerindeki bütün editör desteğini alırsınız.
Resmi Pydantic dokümanlarından alınmıştır:
-```Python
-{!../../../docs_src/python_types/tutorial011.py!}
-```
+{* ../../docs_src/python_types/tutorial011.py *}
+
-!!! info
- Daha fazla şey öğrenmek için Pydantic'i takip edin.
+/// info
+
+Daha fazla şey öğrenmek için Pydantic'i takip edin.
+
+///
**FastAPI** tamamen Pydantic'e dayanmaktadır.
@@ -310,5 +306,8 @@ Bütün bunlar kulağa soyut gelebilir. Merak etme. Tüm bunları çalışırken
Önemli olan, standart Python türlerini tek bir yerde kullanarak (daha fazla sınıf, dekoratör vb. eklemek yerine), **FastAPI**'nin bizim için işi yapmasını sağlamak.
-!!! info
- Tüm öğreticiyi zaten okuduysanız ve türler hakkında daha fazla bilgi için geri döndüyseniz, iyi bir kaynak: the "cheat sheet" from `mypy`.
+/// info
+
+Tüm öğreticiyi zaten okuduysanız ve türler hakkında daha fazla bilgi için geri döndüyseniz, iyi bir kaynak: the "cheat sheet" from `mypy`.
+
+///
diff --git a/docs/tr/docs/resources/index.md b/docs/tr/docs/resources/index.md
new file mode 100644
index 000000000..fc71a9ca1
--- /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/cookie-params.md b/docs/tr/docs/tutorial/cookie-params.md
new file mode 100644
index 000000000..f07508c2f
--- /dev/null
+++ b/docs/tr/docs/tutorial/cookie-params.md
@@ -0,0 +1,35 @@
+# Çerez (Cookie) Parametreleri
+
+`Query` (Sorgu) ve `Path` (Yol) parametrelerini tanımladığınız şekilde çerez parametreleri tanımlayabilirsiniz.
+
+## Import `Cookie`
+
+Öncelikle, `Cookie`'yi projenize dahil edin:
+
+{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[3] *}
+
+## `Cookie` Parametrelerini Tanımlayın
+
+Çerez parametrelerini `Path` veya `Query` tanımlaması yapar gibi tanımlayın.
+
+İlk değer varsayılan değerdir; tüm ekstra doğrulama veya belirteç parametrelerini kullanabilirsiniz:
+
+{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[9] *}
+
+/// note | Teknik Detaylar
+
+`Cookie` sınıfı `Path` ve `Query` sınıflarının kardeşidir. Diğerleri gibi `Param` sınıfını miras alan bir sınıftır.
+
+Ancak `fastapi`'dan projenize dahil ettiğiniz `Query`, `Path`, `Cookie` ve diğerleri aslında özel sınıflar döndüren birer fonksiyondur.
+
+///
+
+/// info | Bilgi
+
+Çerez tanımlamak için `Cookie` sınıfını kullanmanız gerekmektedir, aksi taktirde parametreler sorgu parametreleri olarak yorumlanır.
+
+///
+
+## Özet
+
+Çerez tanımlamalarını `Cookie` sınıfını kullanarak `Query` ve `Path` tanımlar gibi tanımlayın.
diff --git a/docs/tr/docs/tutorial/first-steps.md b/docs/tr/docs/tutorial/first-steps.md
new file mode 100644
index 000000000..2d2949b50
--- /dev/null
+++ b/docs/tr/docs/tutorial/first-steps.md
@@ -0,0 +1,335 @@
+# İlk Adımlar
+
+En sade FastAPI dosyası şu şekilde görünür:
+
+{* ../../docs_src/first_steps/tutorial001.py *}
+
+Yukarıdaki içeriği bir `main.py` dosyasına kopyalayalım.
+
+Uygulamayı çalıştıralım:
+
+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.
+
+{* ../../docs_src/first_steps/tutorial001.py hl[7] *}
+
+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.
+
+{* ../../docs_src/first_steps/tutorial003.py hl[7] *}
+
+/// 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
+
+{* ../../docs_src/first_steps/tutorial001.py hl[8] *}
+
+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 b39802f5d..000000000
--- a/docs/tr/docs/tutorial/first_steps.md
+++ /dev/null
@@ -1,336 +0,0 @@
-# İlk Adımlar
-
-En basit FastAPI dosyası şu şekildedir:
-
-```Python
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
-
-Bunu bir `main.py` dosyasına kopyalayın.
-
-Projeyi çalıştırın:
-
-get
işlemi kullanılarak
-
-
-!!! info "`@decorator` Bilgisi"
- Python `@something` şeklinde ifadeleri "decorator" olarak adlandırır.
-
- Decoratoru bir fonksiyonun üzerine koyarsınız. Dekoratif bir şapka gibi (Sanırım terim buradan gelmektedir).
-
- Bir "decorator" fonksiyonu alır ve bazı işlemler gerçekleştir.
-
- Bizim durumumzda decarator **FastAPI'ye** fonksiyonun bir `get` işlemi ile `/` pathine geldiğini söyler.
-
- Bu **path işlem decoratordür**
-
-Ayrıca diğer işlemleri de kullanabilirsiniz:
-
-* `@app.post()`
-* `@app.put()`
-* `@app.delete()`
-
-Ve daha egzotik olanları:
-
-* `@app.options()`
-* `@app.head()`
-* `@app.patch()`
-* `@app.trace()`
-
-!!! tip
- Her işlemi (HTTP method) istediğiniz gibi kullanmakta özgürsünüz.
-
- **FastAPI** herhangi bir özel anlamı zorlamaz.
-
- Buradaki bilgiler bir gereklilik değil, bir kılavuz olarak sunulmaktadır.
-
- Örneğin, GraphQL kullanırkan normalde tüm işlemleri yalnızca `POST` işlemini kullanarak gerçekleştirirsiniz.
-
-### Adım 4: **path işlem fonksiyonunu** tanımlayın
-
-Aşağıdakiler bizim **path işlem fonksiyonlarımızdır**:
-
-* **path**: `/`
-* **işlem**: `get`
-* **function**: "decorator"ün altındaki fonksiyondur (`@app.get("/")` altında).
-
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
-
-Bu bir Python fonksiyonudur.
-
-Bir `GET` işlemi kullanarak "`/`" URL'sine bir istek geldiğinde **FastAPI** tarafından çağrılır.
-
-Bu durumda bir `async` fonksiyonudur.
-
----
-
-Bunu `async def` yerine normal bir fonksiyon olarakta tanımlayabilirsiniz.
-
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial003.py!}
-```
-
-!!! note
-
- Eğer farkı bilmiyorsanız, [Async: *"Acelesi var?"*](../async.md#in-a-hurry){.internal-link target=_blank} kontrol edebilirsiniz.
-
-### Adım 5: İçeriği geri döndürün
-
-
-```Python hl_lines="8"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
-
-Bir `dict`, `list` döndürebilir veya `str`, `int` gibi tekil değerler döndürebilirsiniz.
-
-Ayrıca, Pydantic modellerini de döndürebilirsiniz. (Bununla ilgili daha sonra ayrıntılı bilgi göreceksiniz.)
-
-Otomatik olarak JSON'a dönüştürülecek(ORM'ler vb. dahil) başka birçok nesne ve model vardır. En beğendiklerinizi kullanmayı deneyin, yüksek ihtimalle destekleniyordur.
-
-## Özet
-
-* `FastAPI`'yi içe aktarın.
-* Bir `app` örneği oluşturun.
-* **path işlem decorator** yazın. (`@app.get("/")` gibi)
-* **path işlem fonksiyonu** yazın. (`def root(): ...` gibi)
-* Development sunucunuzu çalıştırın. (`uvicorn main:app --reload` gibi)
diff --git a/docs/tr/docs/tutorial/path-params.md b/docs/tr/docs/tutorial/path-params.md
new file mode 100644
index 000000000..e1707a5d9
--- /dev/null
+++ b/docs/tr/docs/tutorial/path-params.md
@@ -0,0 +1,258 @@
+# Yol Parametreleri
+
+Yol "parametrelerini" veya "değişkenlerini" Python string biçimlemede kullanılan sözdizimi ile tanımlayabilirsiniz.
+
+{* ../../docs_src/path_params/tutorial001.py hl[6:7] *}
+
+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.
+
+{* ../../docs_src/path_params/tutorial002.py hl[7] *}
+
+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:
+
+POST
sayfasını ziyaret edebilirsiniz.
+
+///
+
+/// warning | Uyarı
+
+*Yol operasyonları* içerisinde birden fazla `Form` parametresi tanımlayabilirsiniz ancak bunlarla birlikte JSON verisi kabul eden `Body` alanları tanımlayamazsınız çünkü bu durumda istek gövdesi `application/json` yerine `application/x-www-form-urlencoded` ile kodlanmış olur.
+
+Bu **FastAPI**'ın getirdiği bir kısıtlama değildir, HTTP protokolünün bir parçasıdır.
+
+///
+
+## Özet
+
+Form verisi girdi parametreleri tanımlamak için `Form` sınıfını kullanın.
diff --git a/docs/tr/docs/tutorial/static-files.md b/docs/tr/docs/tutorial/static-files.md
new file mode 100644
index 000000000..db30f13bc
--- /dev/null
+++ b/docs/tr/docs/tutorial/static-files.md
@@ -0,0 +1,40 @@
+# Statik Dosyalar
+
+`StaticFiles`'ı kullanarak statik dosyaları bir yol altında sunabilirsiniz.
+
+## `StaticFiles` Kullanımı
+
+* `StaticFiles` sınıfını projenize dahil edin.
+* Bir `StaticFiles()` örneğini belirli bir yola bağlayın.
+
+{* ../../docs_src/static_files/tutorial001.py hl[2,6] *}
+
+/// note | Teknik Detaylar
+
+Projenize dahil etmek için `from starlette.staticfiles import StaticFiles` kullanabilirsiniz.
+
+**FastAPI**, geliştiricilere kolaylık sağlamak amacıyla `starlette.staticfiles`'ı `fastapi.staticfiles` olarak sağlar. Ancak `StaticFiles` sınıfı aslında doğrudan Starlette'den gelir.
+
+///
+
+### Bağlama (Mounting) Nedir?
+
+"Bağlamak", belirli bir yola tamamen "bağımsız" bir uygulama eklemek anlamına gelir ve ardından tüm alt yollara gelen istekler bu uygulama tarafından işlenir.
+
+Bu, bir `APIRouter` kullanmaktan farklıdır çünkü bağlanmış bir uygulama tamamen bağımsızdır. Ana uygulamanızın OpenAPI ve dokümanlar, bağlanmış uygulamadan hiçbir şey içermez, vb.
+
+[Advanced User Guide](../advanced/index.md){.internal-link target=_blank} bölümünde daha fazla bilgi edinebilirsiniz.
+
+## Detaylar
+
+`"/static"` ifadesi, bu "alt uygulamanın" "bağlanacağı" alt yolu belirtir. Bu nedenle, `"/static"` ile başlayan her yol, bu uygulama tarafından işlenir.
+
+`directory="static"` ifadesi, statik dosyalarınızı içeren dizinin adını belirtir.
+
+`name="static"` ifadesi, alt uygulamanın **FastAPI** tarafından kullanılacak ismini belirtir.
+
+Bu parametrelerin hepsi "`static`"den farklı olabilir, bunları kendi uygulamanızın ihtiyaçlarına göre belirleyebilirsiniz.
+
+## Daha Fazla Bilgi
+
+Daha fazla detay ve seçenek için Starlette'in Statik Dosyalar hakkındaki dokümantasyonunu incelleyin.
diff --git a/docs/tr/mkdocs.yml b/docs/tr/mkdocs.yml
index 96306ee77..de18856f4 100644
--- a/docs/tr/mkdocs.yml
+++ b/docs/tr/mkdocs.yml
@@ -1,162 +1 @@
-site_name: FastAPI
-site_description: FastAPI framework, high performance, easy to learn, fast to code, ready for production
-site_url: https://fastapi.tiangolo.com/tr/
-theme:
- name: material
- custom_dir: overrides
- palette:
- - media: '(prefers-color-scheme: light)'
- scheme: default
- primary: teal
- accent: amber
- toggle:
- icon: material/lightbulb
- name: Switch to light mode
- - media: '(prefers-color-scheme: dark)'
- scheme: slate
- primary: teal
- accent: amber
- toggle:
- icon: material/lightbulb-outline
- name: Switch to dark mode
- features:
- - search.suggest
- - search.highlight
- - content.tabs.link
- icon:
- repo: fontawesome/brands/github-alt
- logo: https://fastapi.tiangolo.com/img/icon-white.svg
- favicon: https://fastapi.tiangolo.com/img/favicon.png
- language: tr
-repo_name: tiangolo/fastapi
-repo_url: https://github.com/tiangolo/fastapi
-edit_uri: ''
-plugins:
-- search
-- markdownextradata:
- data: data
-nav:
-- FastAPI: index.md
-- Languages:
- - en: /
- - az: /az/
- - cs: /cs/
- - de: /de/
- - em: /em/
- - es: /es/
- - fa: /fa/
- - fr: /fr/
- - he: /he/
- - hy: /hy/
- - id: /id/
- - it: /it/
- - ja: /ja/
- - ko: /ko/
- - nl: /nl/
- - pl: /pl/
- - pt: /pt/
- - ru: /ru/
- - sq: /sq/
- - sv: /sv/
- - ta: /ta/
- - tr: /tr/
- - uk: /uk/
- - zh: /zh/
-- features.md
-- fastapi-people.md
-- python-types.md
-- Tutorial - User Guide:
- - tutorial/first-steps.md
-markdown_extensions:
-- toc:
- permalink: true
-- markdown.extensions.codehilite:
- guess_lang: false
-- mdx_include:
- base_path: docs
-- admonition
-- codehilite
-- extra
-- pymdownx.superfences:
- custom_fences:
- - name: mermaid
- class: mermaid
- format: !!python/name:pymdownx.superfences.fence_code_format ''
-- pymdownx.tabbed:
- alternate_style: true
-- attr_list
-- md_in_html
-extra:
- analytics:
- provider: google
- property: G-YNEVN69SC3
- social:
- - icon: fontawesome/brands/github-alt
- link: https://github.com/tiangolo/fastapi
- - icon: fontawesome/brands/discord
- link: https://discord.gg/VQjSZaeJmf
- - icon: fontawesome/brands/twitter
- link: https://twitter.com/fastapi
- - icon: fontawesome/brands/linkedin
- link: https://www.linkedin.com/in/tiangolo
- - icon: fontawesome/brands/dev
- link: https://dev.to/tiangolo
- - icon: fontawesome/brands/medium
- link: https://medium.com/@tiangolo
- - icon: fontawesome/solid/globe
- link: https://tiangolo.com
- alternate:
- - link: /
- name: en - English
- - link: /az/
- name: az
- - link: /cs/
- name: cs
- - link: /de/
- name: de
- - link: /em/
- name: 😉
- - link: /es/
- name: es - español
- - link: /fa/
- name: fa
- - link: /fr/
- name: fr - français
- - link: /he/
- name: he
- - link: /hy/
- name: hy
- - link: /id/
- name: id
- - link: /it/
- name: it - italiano
- - link: /ja/
- name: ja - 日本語
- - link: /ko/
- name: ko - 한국어
- - link: /nl/
- name: nl
- - link: /pl/
- name: pl
- - link: /pt/
- name: pt - português
- - link: /ru/
- name: ru - русский язык
- - link: /sq/
- name: sq - shqip
- - link: /sv/
- name: sv - svenska
- - link: /ta/
- name: ta - தமிழ்
- - link: /tr/
- name: tr - Türkçe
- - link: /uk/
- name: uk - українська мова
- - link: /zh/
- name: zh - 汉语
-extra_css:
-- https://fastapi.tiangolo.com/css/termynal.css
-- https://fastapi.tiangolo.com/css/custom.css
-extra_javascript:
-- https://fastapi.tiangolo.com/js/termynal.js
-- https://fastapi.tiangolo.com/js/custom.js
+INHERIT: ../en/mkdocs.yml
diff --git a/docs/tr/overrides/.gitignore b/docs/tr/overrides/.gitignore
deleted file mode 100644
index e69de29bb..000000000
diff --git a/docs/uk/docs/alternatives.md b/docs/uk/docs/alternatives.md
new file mode 100644
index 000000000..1acbe237a
--- /dev/null
+++ b/docs/uk/docs/alternatives.md
@@ -0,0 +1,483 @@
+# Альтернативи, натхнення та порівняння
+
+Що надихнуло на створення **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**.
+
+/// note | Примітка
+
+Django REST Framework створив Том Крісті. Той самий творець Starlette і Uvicorn, на яких базується **FastAPI**.
+
+///
+
+/// check | Надихнуло **FastAPI** на
+
+Мати автоматичний веб-інтерфейс документації API.
+
+///
+
+### Flask
+
+Flask — це «мікрофреймворк», він не включає інтеграцію бази даних, а також багато речей, які за замовчуванням є в Django.
+
+Ця простота та гнучкість дозволяють використовувати бази даних NoSQL як основну систему зберігання даних.
+
+Оскільки він дуже простий, він порівняно легкий та інтуїтивний для освоєння, хоча в деяких моментах документація стає дещо технічною.
+
+Він також зазвичай використовується для інших програм, яким не обов’язково потрібна база даних, керування користувачами або будь-яка з багатьох функцій, які є попередньо вбудованими в Django. Хоча багато з цих функцій можна додати за допомогою плагінів.
+
+Відокремлення частин було ключовою особливістю, яку я хотів зберегти, при цьому залишаючись «мікрофреймворком», який можна розширити, щоб охопити саме те, що потрібно.
+
+Враховуючи простоту Flask, він здавався хорошим підходом для створення API. Наступним, що знайшов, був «Django REST Framework» для Flask.
+
+/// check | Надихнуло **FastAPI** на
+
+Бути мікрофреймоворком. Зробити легким комбінування та поєднання необхідних інструментів та частин.
+
+ Мати просту та легку у використанні систему маршрутизації.
+
+///
+
+### Requests
+
+**FastAPI** насправді не є альтернативою **Requests**. Сфера їх застосування дуже різна.
+
+Насправді цілком звична річ використовувати Requests *всередині* програми FastAPI.
+
+Але все ж FastAPI черпав натхнення з Requests.
+
+**Requests** — це бібліотека для *взаємодії* з API (як клієнт), а **FastAPI** — це бібліотека для *створення* API (як сервер).
+
+Вони більш-менш знаходяться на протилежних кінцях, доповнюючи одна одну.
+
+Requests мають дуже простий та інтуїтивно зрозумілий дизайн, дуже простий у використанні, з розумними параметрами за замовчуванням. Але в той же час він дуже потужний і налаштовується.
+
+Ось чому, як сказано на офіційному сайті:
+
+> Requests є одним із найбільш завантажуваних пакетів Python усіх часів
+
+Використовувати його дуже просто. Наприклад, щоб виконати запит `GET`, ви повинні написати:
+
+```Python
+response = requests.get("http://example.com/some/url")
+```
+
+Відповідна операція *роуту* API FastAPI може виглядати так:
+
+```Python hl_lines="1"
+@app.get("/some/url")
+def read_url():
+ return {"message": "Hello World"}
+```
+
+Зверніть увагу на схожість у `requests.get(...)` і `@app.get(...)`.
+
+/// check | Надихнуло **FastAPI** на
+
+* Майте простий та інтуїтивно зрозумілий API.
+ * Використовуйте імена (операції) методів HTTP безпосередньо, простим та інтуїтивно зрозумілим способом.
+ * Розумні параметри за замовчуванням, але потужні налаштування.
+
+///
+
+### Swagger / OpenAPI
+
+Головною функцією, яку я хотів від Django REST Framework, була автоматична API документація.
+
+Потім я виявив, що існує стандарт для документування API з використанням JSON (або YAML, розширення JSON) під назвою Swagger.
+
+І вже був створений веб-інтерфейс користувача для Swagger API. Отже, можливість генерувати документацію Swagger для API дозволить використовувати цей веб-інтерфейс автоматично.
+
+У якийсь момент Swagger було передано Linux Foundation, щоб перейменувати його на OpenAPI.
+
+Тому, коли говорять про версію 2.0, прийнято говорити «Swagger», а про версію 3+ «OpenAPI».
+
+/// check | Надихнуло **FastAPI** на
+
+Прийняти і використовувати відкритий стандарт для специфікацій API замість спеціальної схеми.
+
+ Інтегрувати інструменти інтерфейсу на основі стандартів:
+
+ * Інтерфейс Swagger
+ * ReDoc
+
+ Ці два було обрано через те, що вони досить популярні та стабільні, але, виконавши швидкий пошук, ви можете знайти десятки додаткових альтернативних інтерфейсів для OpenAPI (які можна використовувати з **FastAPI**).
+
+///
+
+### Фреймворки REST для Flask
+
+Існує кілька фреймворків Flask REST, але, витративши час і роботу на їх дослідження, я виявив, що багато з них припинено або залишено, з кількома постійними проблемами, які зробили їх непридатними.
+
+### Marshmallow
+
+Однією з головних функцій, необхідних для систем API, є "серіалізація", яка бере дані з коду (Python) і перетворює їх на щось, що можна надіслати через мережу. Наприклад, перетворення об’єкта, що містить дані з бази даних, на об’єкт JSON. Перетворення об’єктів `datetime` на строки тощо.
+
+Іншою важливою функцією, необхідною для API, є перевірка даних, яка забезпечує дійсність даних за певними параметрами. Наприклад, що деяке поле є `int`, а не деяка випадкова строка. Це особливо корисно для вхідних даних.
+
+Без системи перевірки даних вам довелося б виконувати всі перевірки вручну, у коді.
+
+Marshmallow створено для забезпечення цих функцій. Це чудова бібліотека, і я часто нею користувався раніше.
+
+Але він був створений до того, як існували підказки типу Python. Отже, щоб визначити кожну схему, вам потрібно використовувати спеціальні утиліти та класи, надані Marshmallow.
+
+/// check | Надихнуло **FastAPI** на
+
+Використовувати код для автоматичного визначення "схем", які надають типи даних і перевірку.
+
+///
+
+### Webargs
+
+Іншою важливою функцією, необхідною для API, є аналіз даних із вхідних запитів.
+
+Webargs — це інструмент, створений, щоб забезпечити це поверх кількох фреймворків, включаючи Flask.
+
+Він використовує Marshmallow в основі для перевірки даних. І створений тими ж розробниками.
+
+Це чудовий інструмент, і я також часто використовував його, перш ніж створити **FastAPI**.
+
+/// info | Інформація
+
+Webargs був створений тими ж розробниками Marshmallow.
+
+///
+
+/// check | Надихнуло **FastAPI** на
+
+Мати автоматичну перевірку даних вхідного запиту.
+
+///
+
+### APISpec
+
+Marshmallow і Webargs забезпечують перевірку, аналіз і серіалізацію як плагіни.
+
+Але документація досі відсутня. Потім було створено APISpec.
+
+Це плагін для багатьох фреймворків (також є плагін для Starlette).
+
+Принцип роботи полягає в тому, що ви пишете визначення схеми, використовуючи формат YAML, у docstring кожної функції, що обробляє маршрут.
+
+І він генерує схеми OpenAPI.
+
+Так це працює у Flask, Starlette, Responder тощо.
+
+Але потім ми знову маємо проблему наявності мікросинтаксису всередині Python строки (великий YAML).
+
+Редактор тут нічим не може допомогти. І якщо ми змінимо параметри чи схеми Marshmallow і забудемо також змінити цю строку документа YAML, згенерована схема буде застарілою.
+
+/// info | Інформація
+
+APISpec був створений тими ж розробниками Marshmallow.
+
+///
+
+/// check | Надихнуло **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}.
+
+/// info | Інформація
+
+Flask-apispec був створений тими ж розробниками Marshmallow.
+
+///
+
+/// check | Надихнуло **FastAPI** на
+
+Створення схеми OpenAPI автоматично з того самого коду, який визначає серіалізацію та перевірку.
+
+///
+
+### NestJS (та Angular)
+
+Це навіть не Python, NestJS — це фреймворк NodeJS JavaScript (TypeScript), натхненний Angular.
+
+Це досягає чогось подібного до того, що можна зробити з Flask-apispec.
+
+Він має інтегровану систему впровадження залежностей, натхненну Angular two. Він потребує попередньої реєстрації «injectables» (як і всі інші системи впровадження залежностей, які я знаю), тому це збільшує багатослівність та повторення коду.
+
+Оскільки параметри описані за допомогою типів TypeScript (подібно до підказок типу Python), підтримка редактора досить хороша.
+
+Але оскільки дані TypeScript не зберігаються після компіляції в JavaScript, вони не можуть покладатися на типи для визначення перевірки, серіалізації та документації одночасно. Через це та деякі дизайнерські рішення, щоб отримати перевірку, серіалізацію та автоматичну генерацію схеми, потрібно додати декоратори в багатьох місцях. Таким чином код стає досить багатослівним.
+
+Він не дуже добре обробляє вкладені моделі. Отже, якщо тіло JSON у запиті є об’єктом JSON із внутрішніми полями, які, у свою чергу, є вкладеними об’єктами JSON, його неможливо належним чином задокументувати та перевірити.
+
+/// check | Надихнуло **FastAPI** на
+
+Використовувати типи Python, щоб мати чудову підтримку редактора.
+
+ Мати потужну систему впровадження залежностей. Знайдіть спосіб звести до мінімуму повторення коду.
+
+///
+
+### Sanic
+
+Це був один із перших надзвичайно швидких фреймворків Python на основі `asyncio`. Він був дуже схожий на Flask.
+
+/// note | Технічні деталі
+
+Він використовував `uvloop` замість стандартного циклу Python `asyncio`. Ось що зробило його таким швидким.
+
+ Це явно надихнуло Uvicorn і Starlette, які зараз швидші за Sanic у відкритих тестах.
+
+///
+
+/// check | Надихнуло **FastAPI** на
+
+Знайти спосіб отримати божевільну продуктивність.
+
+ Ось чому **FastAPI** базується на Starlette, оскільки це найшвидша доступна структура (перевірена тестами сторонніх розробників).
+
+///
+
+### Falcon
+
+Falcon — ще один високопродуктивний фреймворк Python, він розроблений як мінімальний і працює як основа інших фреймворків, таких як Hug.
+
+Він розроблений таким чином, щоб мати функції, які отримують два параметри, один «запит» і один «відповідь». Потім ви «читаєте» частини запиту та «записуєте» частини у відповідь. Через такий дизайн неможливо оголосити параметри запиту та тіла за допомогою стандартних підказок типу Python як параметри функції.
+
+Таким чином, перевірка даних, серіалізація та документація повинні виконуватися в коді, а не автоматично. Або вони повинні бути реалізовані як фреймворк поверх Falcon, як Hug. Така сама відмінність спостерігається в інших фреймворках, натхненних дизайном Falcon, що мають один об’єкт запиту та один об’єкт відповіді як параметри.
+
+/// check | Надихнуло **FastAPI** на
+
+Знайти способи отримати чудову продуктивність.
+
+ Разом із Hug (оскільки Hug базується на Falcon) надихнув **FastAPI** оголосити параметр `response` у функціях.
+
+ Хоча у FastAPI це необов’язково, і використовується в основному для встановлення заголовків, файлів cookie та альтернативних кодів стану.
+
+///
+
+### Molten
+
+Я відкрив для себе Molten на перших етапах створення **FastAPI**. І він має досить схожі ідеї:
+
+* Базується на підказках типу Python.
+* Перевірка та документація цих типів.
+* Система впровадження залежностей.
+
+Він не використовує перевірку даних, серіалізацію та бібліотеку документації сторонніх розробників, як Pydantic, він має свою власну. Таким чином, ці визначення типів даних не можна було б використовувати повторно так легко.
+
+Це вимагає трохи більш докладних конфігурацій. І оскільки він заснований на WSGI (замість ASGI), він не призначений для використання високопродуктивних інструментів, таких як Uvicorn, Starlette і Sanic.
+
+Система впровадження залежностей вимагає попередньої реєстрації залежностей, і залежності вирішуються на основі оголошених типів. Отже, неможливо оголосити більше ніж один «компонент», який надає певний тип.
+
+Маршрути оголошуються в одному місці з використанням функцій, оголошених в інших місцях (замість використання декораторів, які можна розмістити безпосередньо поверх функції, яка обробляє кінцеву точку). Це ближче до того, як це робить Django, ніж до Flask (і Starlette). Він розділяє в коді речі, які відносно тісно пов’язані.
+
+/// check | Надихнуло **FastAPI** на
+
+Визначити додаткові перевірки для типів даних, використовуючи значення "за замовчуванням" атрибутів моделі. Це покращує підтримку редактора, а раніше вона була недоступна в Pydantic.
+
+ Це фактично надихнуло оновити частини Pydantic, щоб підтримувати той самий стиль оголошення перевірки (всі ці функції вже доступні в Pydantic).
+
+///
+
+### Hug
+
+Hug був одним із перших фреймворків, який реалізував оголошення типів параметрів API за допомогою підказок типу Python. Це була чудова ідея, яка надихнула інші інструменти зробити те саме.
+
+Він використовував спеціальні типи у своїх оголошеннях замість стандартних типів Python, але це все одно був величезний крок вперед.
+
+Це також був один із перших фреймворків, який генерував спеціальну схему, що оголошувала весь API у JSON.
+
+Він не базувався на таких стандартах, як OpenAPI та JSON Schema. Тому було б непросто інтегрувати його з іншими інструментами, як-от Swagger UI. Але знову ж таки, це була дуже інноваційна ідея.
+
+Він має цікаву незвичайну функцію: використовуючи ту саму структуру, можна створювати API, а також CLI.
+
+Оскільки він заснований на попередньому стандарті для синхронних веб-фреймворків Python (WSGI), він не може працювати з Websockets та іншими речами, хоча він також має високу продуктивність.
+
+/// info | Інформація
+
+Hug створив Тімоті Крослі, той самий творець `isort`, чудовий інструмент для автоматичного сортування імпорту у файлах Python.
+
+///
+
+/// check | Надихнуло **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, а не веб-фреймворк.
+
+/// info | Інформація
+
+APIStar створив Том Крісті. Той самий хлопець, який створив:
+
+ * Django REST Framework
+ * Starlette (на якому базується **FastAPI**)
+ * Uvicorn (використовується Starlette і **FastAPI**)
+
+///
+
+/// check | Надихнуло **FastAPI** на
+
+Існувати.
+
+ Ідею оголошення кількох речей (перевірки даних, серіалізації та документації) за допомогою тих самих типів Python, які в той же час забезпечували чудову підтримку редактора, я вважав геніальною ідеєю.
+
+ І після тривалого пошуку подібної структури та тестування багатьох різних альтернатив, APIStar став найкращим доступним варіантом.
+
+ Потім APIStar перестав існувати як сервер, і було створено Starlette, який став новою кращою основою для такої системи. Це стало останнім джерелом натхнення для створення **FastAPI**. Я вважаю **FastAPI** «духовним спадкоємцем» APIStar, удосконалюючи та розширюючи функції, систему введення тексту та інші частини на основі досвіду, отриманого від усіх цих попередніх інструментів.
+
+///
+
+## Використовується **FastAPI**
+
+### Pydantic
+
+Pydantic — це бібліотека для визначення перевірки даних, серіалізації та документації (за допомогою схеми JSON) на основі підказок типу Python.
+
+Це робить його надзвичайно інтуїтивним.
+
+Його можна порівняти з Marshmallow. Хоча він швидший за Marshmallow у тестах. Оскільки він базується на тих самих підказках типу Python, підтримка редактора чудова.
+
+/// check | **FastAPI** використовує його для
+
+Виконання перевірки всіх даних, серіалізації даних і автоматичної документацію моделі (на основі схеми JSON).
+
+ Потім **FastAPI** бере ці дані схеми JSON і розміщує їх у OpenAPI, окремо від усіх інших речей, які він робить.
+
+///
+
+### Starlette
+
+Starlette — це легкий фреймворк/набір інструментів ASGI, який ідеально підходить для створення високопродуктивних asyncio сервісів.
+
+Він дуже простий та інтуїтивно зрозумілий. Його розроблено таким чином, щоб його можна було легко розширювати та мати модульні компоненти.
+
+Він має:
+
+* Серйозно вражаючу продуктивність.
+* Підтримку WebSocket.
+* Фонові завдання в процесі.
+* Події запуску та завершення роботи.
+* Тестового клієнта, побудований на HTTPX.
+* CORS, GZip, статичні файли, потокові відповіді.
+* Підтримку сеансів і файлів cookie.
+* 100% покриття тестом.
+* 100% анотовану кодову базу.
+* Кілька жорстких залежностей.
+
+Starlette наразі є найшвидшим фреймворком Python із перевірених. Перевершує лише Uvicorn, який є не фреймворком, а сервером.
+
+Starlette надає всі основні функції веб-мікрофреймворку.
+
+Але він не забезпечує автоматичної перевірки даних, серіалізації чи документації.
+
+Це одна з головних речей, які **FastAPI** додає зверху, все на основі підказок типу Python (з використанням Pydantic). Це, а також система впровадження залежностей, утиліти безпеки, створення схеми OpenAPI тощо.
+
+/// note | Технічні деталі
+
+ASGI — це новий «стандарт», який розробляється членами основної команди Django. Це ще не «стандарт Python» (PEP), хоча вони в процесі цього.
+
+ Тим не менш, він уже використовується як «стандарт» кількома інструментами. Це значно покращує сумісність, оскільки ви можете переключити Uvicorn на будь-який інший сервер ASGI (наприклад, Daphne або Hypercorn), або ви можете додати інструменти, сумісні з ASGI, як-от `python-socketio`.
+
+///
+
+/// check | **FastAPI** використовує його для
+
+Керування всіма основними веб-частинами. Додавання функцій зверху.
+
+ Сам клас `FastAPI` безпосередньо успадковує клас `Starlette`.
+
+ Отже, усе, що ви можете робити зі Starlette, ви можете робити це безпосередньо за допомогою **FastAPI**, оскільки це, по суті, Starlette на стероїдах.
+
+///
+
+### Uvicorn
+
+Uvicorn — це блискавичний сервер ASGI, побудований на uvloop і httptools.
+
+Це не веб-фреймворк, а сервер. Наприклад, він не надає інструментів для маршрутизації. Це те, що фреймворк на кшталт Starlette (або **FastAPI**) забезпечить поверх нього.
+
+Це рекомендований сервер для Starlette і **FastAPI**.
+
+/// check | **FastAPI** рекомендує це як
+
+Основний веб-сервер для запуску програм **FastAPI**.
+
+ Ви можете поєднати його з Gunicorn, щоб мати асинхронний багатопроцесний сервер.
+
+ Додаткову інформацію див. у розділі [Розгортання](deployment/index.md){.internal-link target=_blank}.
+
+///
+
+## Орієнтири та швидкість
+
+Щоб зрозуміти, порівняти та побачити різницю між Uvicorn, Starlette і FastAPI, перегляньте розділ про [Бенчмарки](benchmarks.md){.internal-link target=_blank}.
diff --git a/docs/uk/docs/fastapi-cli.md b/docs/uk/docs/fastapi-cli.md
new file mode 100644
index 000000000..6bbbbc326
--- /dev/null
+++ b/docs/uk/docs/fastapi-cli.md
@@ -0,0 +1,83 @@
+# FastAPI CLI
+
+**FastAPI CLI** це програма командного рядка, яку Ви можете використовувати, щоб обслуговувати Ваш додаток FastAPI, керувати Вашими FastApi проектами, тощо.
+
+Коли Ви встановлюєте FastApi (тобто виконуєте `pip install "fastapi[standard]"`), Ви також встановлюєте пакунок `fastapi-cli`, цей пакунок надає команду `fastapi` в терміналі.
+
+Для запуску Вашого FastAPI проекту для розробки, Ви можете скористатись командою `fastapi dev`:
+
+- FastAPI framework, high performance, easy to learn, fast to code, ready for production + Готовий до продакшину, високопродуктивний, простий у вивченні та швидкий для написання коду фреймворк
--- -**Documentation**: https://fastapi.tiangolo.com +**Документація**: https://fastapi.tiangolo.com -**Source Code**: https://github.com/tiangolo/fastapi +**Програмний код**: https://github.com/fastapi/fastapi --- -FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints. +FastAPI - це сучасний, швидкий (високопродуктивний), вебфреймворк для створення API за допомогою Python,в основі якого лежить стандартна анотація типів Python. -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). +* **Швидкий**: Дуже висока продуктивність, на рівні з **NodeJS** та **Go** (завдяки Starlette та Pydantic). [Один із найшвидших фреймворків](#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. +* **Швидке написання коду**: Пришвидшує розробку функціоналу приблизно на 200%-300%. * +* **Менше помилок**: Зменшить кількість помилок спричинених людиною (розробником) на 40%. * +* **Інтуїтивний**: Чудова підтримка редакторами коду. Доповнення всюди. Зменште час на налагодження. +* **Простий**: Спроектований, для легкого використання та навчання. Знадобиться менше часу на читання документації. +* **Короткий**: Зведе до мінімуму дублювання коду. Кожен оголошений параметр може виконувати кілька функцій. +* **Надійний**: Ви матимете стабільний код готовий до продакшину з автоматичною інтерактивною документацією. +* **Стандартизований**: Оснований та повністю сумісний з відкритими стандартами для API: OpenAPI (попередньо відомий як Swagger) та JSON Schema. -* estimation based on tests on an internal development team, building production applications. +* оцінка на основі тестів внутрішньої команди розробників, створення продуктових застосунків. -## Sponsors +## Спонсори @@ -61,11 +60,11 @@ The key features are: 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._" -async def
...async def
...uvicorn main:app --reload
...uvicorn main:app --reload
...email-validator
- для валідації електронної пошти.
+* pydantic-settings
- для управління налаштуваннями.
+* pydantic-extra-types
- для додаткових типів, що можуть бути використані з Pydantic.
-* ujson
- for faster JSON "parsing".
-* email_validator
- for email validation.
-Used by Starlette:
+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`.
+* httpx
- Необхідно, якщо Ви хочете використовувати `TestClient`.
+* jinja2
- Необхідно, якщо Ви хочете використовувати шаблони як конфігурацію за замовчуванням.
+* python-multipart
- Необхідно, якщо Ви хочете підтримувати "розбір" форми за допомогою `request.form()`.
+* itsdangerous
- Необхідно для підтримки `SessionMiddleware`.
+* pyyaml
- Необхідно для підтримки Starlette `SchemaGenerator` (ймовірно, вам це не потрібно з FastAPI).
-Used by FastAPI / Starlette:
+FastAPI / Starlette використовують:
-* uvicorn
- for the server that loads and serves your application.
-* orjson
- Required if you want to use `ORJSONResponse`.
+* uvicorn
- для сервера, який завантажує та обслуговує вашу програму.
+* orjson
- Необхідно, якщо Ви хочете використовувати `ORJSONResponse`.
+* ujson
- Необхідно, якщо Ви хочете використовувати `UJSONResponse`.
-You can install all of these with `pip install fastapi[all]`.
+Ви можете встановити все це за допомогою `pip install fastapi[all]`.
-## License
+## Ліцензія
-This project is licensed under the terms of the MIT license.
+Цей проєкт ліцензовано згідно з умовами ліцензії MIT.
diff --git a/docs/uk/docs/learn/index.md b/docs/uk/docs/learn/index.md
new file mode 100644
index 000000000..7f9f21e57
--- /dev/null
+++ b/docs/uk/docs/learn/index.md
@@ -0,0 +1,5 @@
+# Навчання
+
+У цьому розділі надані вступні та навчальні матеріали для вивчення FastAPI.
+
+Це можна розглядати як **книгу**, **курс**, або **офіційний** та рекомендований спосіб освоїти FastAPI. 😎
diff --git a/docs/uk/docs/python-types.md b/docs/uk/docs/python-types.md
new file mode 100644
index 000000000..676bafb15
--- /dev/null
+++ b/docs/uk/docs/python-types.md
@@ -0,0 +1,489 @@
+# Вступ до типів Python
+
+Python підтримує додаткові "підказки типу" ("type hints") (також звані "анотаціями типу" ("type annotations")).
+
+Ці **"type hints"** є спеціальним синтаксисом, що дозволяє оголошувати тип змінної.
+
+За допомогою оголошення типів для ваших змінних, редактори та інструменти можуть надати вам кращу підтримку.
+
+Це просто **швидкий посібник / нагадування** про анотації типів у Python. Він покриває лише мінімум, необхідний щоб використовувати їх з **FastAPI**... що насправді дуже мало.
+
+**FastAPI** повністю базується на цих анотаціях типів, вони дають йому багато переваг.
+
+Але навіть якщо ви ніколи не використаєте **FastAPI**, вам буде корисно дізнатись трохи про них.
+
+/// note
+
+Якщо ви експерт у Python і ви вже знаєте усе про анотації типів - перейдіть до наступного розділу.
+
+///
+
+## Мотивація
+
+Давайте почнемо з простого прикладу:
+
+{* ../../docs_src/python_types/tutorial001.py *}
+
+
+Виклик цієї програми виводить:
+
+```
+John Doe
+```
+
+Функція виконує наступне:
+
+* Бере `first_name` та `last_name`.
+* Конвертує кожну літеру кожного слова у верхній регістр за допомогою `title()`.
+* Конкатенує їх разом із пробілом по середині.
+
+{* ../../docs_src/python_types/tutorial001.py hl[2] *}
+
+
+### Редагуйте це
+
+Це дуже проста програма.
+
+Але тепер уявіть, що ви писали це з нуля.
+
+У певний момент ви розпочали б визначення функції, у вас були б готові параметри...
+
+Але тоді вам потрібно викликати "той метод, який переводить першу літеру у верхній регістр".
+
+Це буде `upper`? Чи `uppercase`? `first_uppercase`? `capitalize`?
+
+Тоді ви спробуєте давнього друга програміста - автозаповнення редактора коду.
+
+Ви надрукуєте перший параметр функції, `first_name`, тоді крапку (`.`), а тоді натиснете `Ctrl+Space`, щоб запустити автозаповнення.
+
+Але, на жаль, ви не отримаєте нічого корисного:
+
+get
операцію
+
+/// info | `@decorator` Додаткова інформація
+
+Синтаксис `@something` у Python називається "декоратором".
+
+Ви розташовуєте його над функцією. Як гарний декоративний капелюх (мабуть, звідти походить термін).
+
+"Декоратор" приймає функцію нижче і виконує з нею якусь дію.
+
+У нашому випадку, цей декоратор повідомляє **FastAPI**, що функція нижче відповідає **шляху** `/` і **операції** `get`.
+
+Це і є "декоратор операції шляху (path operation decorator)".
+
+///
+
+Можна також використовувати операції:
+
+* `@app.post()`
+* `@app.put()`
+* `@app.delete()`
+
+І більш екзотичні:
+
+* `@app.options()`
+* `@app.head()`
+* `@app.patch()`
+* `@app.trace()`
+
+/// tip | Порада
+
+Ви можете використовувати кожну операцію (HTTP-метод) на свій розсуд.
+
+**FastAPI** не нав'язує жодного певного значення для кожного методу.
+
+Наведена тут інформація є рекомендацією, а не обов'язковою вимогою.
+
+Наприклад, під час використання GraphQL зазвичай усі дії виконуються тільки за допомогою `POST` операцій.
+
+///
+
+### Крок 4: визначте **функцію операції шляху (path operation function)**
+
+Ось "**функція операції шляху**":
+
+* **шлях**: це `/`.
+* **операція**: це `get`.
+* **функція**: це функція, яка знаходиться нижче "декоратора" (нижче `@app.get("/")`).
+
+{* ../../docs_src/first_steps/tutorial001.py hl[7] *}
+
+Це звичайна функція Python.
+
+FastAPI викликатиме її щоразу, коли отримає запит до URL із шляхом "/", використовуючи операцію `GET`.
+
+У даному випадку це асинхронна функція.
+
+---
+
+Ви також можете визначити її як звичайну функцію замість `async def`:
+
+{* ../../docs_src/first_steps/tutorial003.py hl[7] *}
+
+/// note | Примітка
+
+Якщо не знаєте в чому різниця, подивіться [Конкурентність: *"Поспішаєш?"*](../async.md#in-a-hurry){.internal-link target=_blank}.
+
+///
+
+### Крок 5: поверніть результат
+
+{* ../../docs_src/first_steps/tutorial001.py hl[8] *}
+
+Ви можете повернути `dict`, `list`, а також окремі значення `str`, `int`, ітд.
+
+Також можна повернути моделі Pydantic (про це ви дізнаєтесь пізніше).
+
+Існує багато інших об'єктів і моделей, які будуть автоматично конвертовані в JSON (зокрема ORM тощо). Спробуйте використати свої улюблені, велика ймовірність, що вони вже підтримуються.
+
+## Підіб'ємо підсумки
+
+* Імпортуємо `FastAPI`.
+* Створюємо екземпляр `app`.
+* Пишемо **декоратор операції шляху** як `@app.get("/")`.
+* Пишемо **функцію операції шляху**; наприклад, `def root(): ...`.
+* Запускаємо сервер у режимі розробки `fastapi dev`.
diff --git a/docs/uk/docs/tutorial/handling-errors.md b/docs/uk/docs/tutorial/handling-errors.md
new file mode 100644
index 000000000..12a356cd0
--- /dev/null
+++ b/docs/uk/docs/tutorial/handling-errors.md
@@ -0,0 +1,255 @@
+# Обробка Помилок
+
+Є багато ситуацій, коли потрібно повідомити клієнта, який використовує Ваш API, про помилку.
+
+Цим клієнтом може бути браузер із фронтендом, код іншого розробника, IoT-пристрій тощо.
+
+Можливо, Вам потрібно повідомити клієнта, що:
+
+* У нього недостатньо прав для виконання цієї операції.
+* Він не має доступу до цього ресурсу.
+* Елемент, до якого він намагається отримати доступ, не існує.
+* тощо.
+
+У таких випадках зазвичай повертається **HTTP статус-код** в діапазоні **400** (від 400 до 499).
+
+Це схоже на HTTP статус-коди 200 (від 200 до 299). Ці "200" статус-коди означають, що запит пройшов успішно.
+
+Статус-коди в діапазоні 400 означають, що сталася помилка з боку клієнта.
+
+Пам'ятаєте всі ці помилки **404 Not Found** (і жарти про них)?
+
+## Використання `HTTPException`
+
+Щоб повернути HTTP-відповіді з помилками клієнту, використовуйте `HTTPException`.
+
+### Імпорт `HTTPException`
+
+{* ../../docs_src/handling_errors/tutorial001.py hl[1] *}
+
+### Використання `HTTPException` у коді
+
+`HTTPException` — це звичайна помилка Python із додатковими даними, які стосуються API.
+
+Оскільки це помилка Python, Ви не `повертаєте` його, а `генеруєте` (генеруєте помилку).
+
+Це також означає, що якщо Ви перебуваєте всередині допоміжної функції, яку викликаєте всередині своєї *функції операції шляху*, і там генеруєте `HTTPException`, всередині цієї допоміжної функції, то решта коду в *функції операції шляху* не буде виконана. Запит одразу завершиться, і HTTP-помилка з `HTTPException` буде надіслана клієнту.
+
+Перевага використання `генерації` (raise) помилки замість `повернення` значення (return) стане більш очевидним в розділі про Залежності та Безпеку.
+
+У цьому прикладі, якщо клієнт запитує елемент за ID, якого не існує, буде згенеровано помилку зі статус-кодом `404`:
+
+{* ../../docs_src/handling_errors/tutorial001.py hl[11] *}
+
+### Отримана відповідь
+
+Якщо клієнт робить запит за шляхом `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
+{
+ "detail": "Item not found"
+}
+```
+
+/// tip | Порада
+
+Під час виклику `HTTPException` Ви можете передати будь-яке значення, яке може бути перетворене в JSON, як параметр `detail`, а не лише рядок (`str`).
+
+Ви можете передати `dict`, `list` тощо.
+
+Вони обробляються автоматично за допомогою **FastAPI** та перетворюються в JSON.
+
+///
+
+## Додавання власних заголовків
+
+Іноді потрібно додати власні заголовки до HTTP-помилки, наприклад, для певних типів безпеки.
+
+Ймовірно, Вам не доведеться використовувати це безпосередньо у своєму коді.
+
+Але якщо Вам знадобиться це для складного сценарію, Ви можете додати власні заголовки:
+
+{* ../../docs_src/handling_errors/tutorial002.py hl[14] *}
+
+## Встановлення власних обробників помилок
+
+Ви можете додати власні обробники помилок за допомогою тих самих утиліт обробки помилок зі Starlette.
+
+Припустимо, у Вас є власний обʼєкт помилки `UnicornException`, яке Ви (або бібліотека, яку Ви використовуєте) може `згенерувати` (`raise`).
+
+І Ви хочете обробляти це виключення глобально за допомогою FastAPI.
+
+Ви можете додати власний обробник виключень за допомогою `@app.exception_handler()`:
+
+{* ../../docs_src/handling_errors/tutorial003.py hl[5:7,13:18,24] *}
+
+Тут, якщо Ви звернетеся до `/unicorns/yolo`, то згенерується помилка `UnicornException`.
+
+Але вона буде оброблена функцією-обробником `unicorn_exception_handler`.
+
+Отже, Ви отримаєте зрозумілу помилку зі HTTP-статусом `418` і JSON-відповіддю:
+
+```JSON
+{"message": "Oops! yolo did something. There goes a rainbow..."}
+```
+
+/// note | Технічні деталі
+
+Ви також можете використовувати `from starlette.requests import Request` і `from starlette.responses import JSONResponse`.
+
+**FastAPI** надає ті самі `starlette.responses`, що й `fastapi.responses`, просто для зручності розробника. Але більшість доступних відповідей надходять безпосередньо зі Starlette. Те ж саме стосується і `Request`.
+
+///
+
+## Перевизначення обробників помилок за замовчуванням
+
+**FastAPI** має кілька обробників помилок за замовчуванням.
+
+Ці обробники відповідають за повернення стандартних JSON-відповідей, коли Ви `генеруєте` (`raise`) `HTTPException`, а також коли запит містить некоректні дані.
+
+Ви можете перевизначити ці обробники, створивши власні.
+
+### Перевизначення помилок валідації запиту
+
+Коли запит містить некоректні дані, **FastAPI** генерує `RequestValidationError`.
+
+І також включає обробник помилок за замовчуванням для нього.
+
+Щоб перевизначити його, імпортуйте `RequestValidationError` і використовуйте його з `@app.exception_handler(RequestValidationError)` для декорування обробника помилок.
+
+Обробник помилок отримує `Request` і саму помилку.
+
+{* ../../docs_src/handling_errors/tutorial004.py hl[2,14:16] *}
+
+Тепер, якщо Ви перейдете за посиланням `/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`.
+
+Так має бути, якщо у Вас виникла `ValidationError` Pydantic у *відповіді* або деінде у вашому коді (не у *запиті* клієнта), це насправді є помилкою у Вашому коді.
+
+І поки Ви її виправляєте, клієнти/користувачі не повинні мати доступу до внутрішньої інформації про помилку, оскільки це може призвести до вразливості безпеки.
+
+### Перевизначення обробника помилок `HTTPException`
+
+Аналогічно, Ви можете перевизначити обробник `HTTPException`.
+
+Наприклад, Ви можете захотіти повернути текстову відповідь замість JSON для цих помилок:
+
+{* ../../docs_src/handling_errors/tutorial004.py hl[3:4,9:11,22] *}
+
+/// note | Технічні деталі
+
+Ви також можете використовувати `from starlette.responses import PlainTextResponse`.
+
+**FastAPI** надає ті самі `starlette.responses`, що й `fastapi.responses`, просто для зручності розробника. Але більшість доступних відповідей надходять безпосередньо зі Starlette.
+
+///
+
+### Використання тіла `RequestValidationError`
+
+`RequestValidationError` містить `body`, який він отримав із некоректними даними.
+
+Ви можете використовувати це під час розробки свого додатка, щоб логувати тіло запиту та налагоджувати його, повертати користувачеві тощо.
+
+{* ../../docs_src/handling_errors/tutorial005.py hl[14] *}
+
+Тепер спробуйте надіслати некоректний елемент, наприклад:
+
+```JSON
+{
+ "title": "towel",
+ "size": "XL"
+}
+```
+Ви отримаєте відповідь, яка повідомить Вам, які саме дані є некоректні у вашому тілі запиту:
+
+
+```JSON hl_lines="12-15"
+{
+ "detail": [
+ {
+ "loc": [
+ "body",
+ "size"
+ ],
+ "msg": "value is not a valid integer",
+ "type": "type_error.integer"
+ }
+ ],
+ "body": {
+ "title": "towel",
+ "size": "XL"
+ }
+}
+```
+
+#### `HTTPException` FastAPI проти `HTTPException` Starlette
+
+**FastAPI** має власний `HTTPException`.
+
+І клас помилки `HTTPException` в **FastAPI** успадковується від класу помилки `HTTPException` в Starlette.
+
+Єдина різниця полягає в тому, що `HTTPException` в **FastAPI** приймає будь-які дані, які можна перетворити на JSON, для поля `detail`, тоді як `HTTPException` у Starlette приймає тільки рядки.
+
+Отже, Ви можете продовжувати використовувати `HTTPException` в **FastAPI** як зазвичай у своєму коді.
+
+Але коли Ви реєструєте обробник виключень, слід реєструвати його для `HTTPException` зі Starlette.
+
+Таким чином, якщо будь-яка частина внутрішнього коду Starlette або розширення чи плагін Starlette згенерує (raise) `HTTPException`, Ваш обробник зможе перехопити та обробити її.
+
+У цьому прикладі, щоб мати можливість використовувати обидва `HTTPException` в одному коді, помилка Starlette перейменовується на `StarletteHTTPException`:
+
+```Python
+from starlette.exceptions import HTTPException as StarletteHTTPException
+```
+
+### Повторне використання обробників помилок **FastAPI**
+
+Якщо Ви хочете використовувати помилки разом із такими ж обробниками помилок за замовчуванням, як у **FastAPI**, Ви можете імпортувати та повторно використовувати їх із `fastapi.exception_handlers`:
+
+{* ../../docs_src/handling_errors/tutorial006.py hl[2:5,15,21] *}
+
+У цьому прикладі Ви просто використовуєте `print` для виведення дуже інформативного повідомлення, але Ви зрозуміли основну ідею. Ви можете обробити помилку та повторно використовувати обробники помилок за замовчуванням.
diff --git a/docs/uk/docs/tutorial/header-param-models.md b/docs/uk/docs/tutorial/header-param-models.md
new file mode 100644
index 000000000..6f7b0bdae
--- /dev/null
+++ b/docs/uk/docs/tutorial/header-param-models.md
@@ -0,0 +1,58 @@
+# Моделі Параметрів Заголовків
+
+Якщо у Вас є група пов’язаних параметрів заголовків, Ви можете створити **Pydantic модель** для їх оголошення.
+
+Це дозволить Вам повторно **використовувати модель** в **різних місцях**, а також оголосити валідації та метадані для всіх параметрів одночасно. 😎
+
+/// note | Нотатки
+
+Ця можливість підтримується починаючи з версії FastAPI `0.115.0`. 🤓
+
+///
+
+## Параметри Заголовків з Використанням Pydantic Model
+
+Оголосіть потрібні **параметри заголовків** у **Pydantic моделі**, а потім оголосіть параметр як `Header`:
+
+{* ../../docs_src/header_param_models/tutorial001_an_py310.py hl[9:14,18] *}
+
+FastAPI буде витягувати дані для кожного поля з заголовків у запиті та передавати їх у створену Вами Pydantic модель.
+
+**FastAPI** буде **витягувати** дані для **кожного поля** з **заголовків** у запиті та передавати їх у створену Вами Pydantic модель.
+
+## Перевірка в Документації
+
+Ви можете побачити необхідні заголовки в інтерфейсі документації за адресою `/docs`:
+
+contact
поляПараметр | Тип | Опис |
---|---|---|
name | str | Ім'я контактної особи або організації. |
url | str | URL з інформацією для контакту. Повинен бути у форматі URL. |
email | str | Email контактної особи або організації. Повинен бути у форматі електронної пошти. |
license_info
поляПараметр | Тип | Опис |
---|---|---|
name | str | ОБОВ'ЯЗКОВО (якщо встановлено license_info ). Назва ліцензії для API. |
identifier | str | Ліцензійний вираз за SPDX для API. Поле identifier взаємовиключне з полем url . Доступно з OpenAPI 3.1.0, FastAPI 0.99.0. |
url | str | URL до ліцензії, яка використовується для API. Повинен бути у форматі URL. |
kwargs
. Навіть якщо вони не мають значення за замовчуванням.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *}
+
+### Краще з `Annotated`
+
+Майте на увазі, якщо Ви використовуєте `Annotated`, оскільки Ви не використовуєте значення за замовчуванням для параметрів функції, цієї проблеми не виникне, і, швидше за все, Вам не потрібно буде використовувати `*`.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py hl[10] *}
+
+## Валідація числових даних: більше або дорівнює
+
+За допомогою `Query` і `Path` (та інших, які Ви побачите пізніше) можна оголошувати числові обмеження.
+
+Тут, завдяки `ge=1`, `item_id` має бути цілим числом, яке "`g`reater than or `e`qual" (більше або дорівнює) `1`.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py hl[10] *}
+
+## Валідація числових даних: більше ніж і менше або дорівнює
+
+Те саме застосовується до:
+
+* `gt`: `g`reater `t`han (більше ніж)
+* `le`: `l`ess than or `e`qual (менше або дорівнює)
+
+{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py hl[10] *}
+
+## Валідація числових даних: float, більше ніж і менше ніж
+
+Валідація чисел також працює для значень типу `float`.
+
+Ось де стає важливо мати можливість оголошувати gt
, а не тільки ge
. Це дозволяє, наприклад, вимагати, щоб значення було більше `0`, навіть якщо воно менше `1`.
+
+Таким чином, значення `0.5` буде допустимим. Але `0.0` або `0` — ні.
+
+Те саме стосується lt
.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py hl[13] *}
+
+## Підсумок
+
+За допомогою `Query`, `Path` (і інших параметрів, які Ви ще не бачили) можна оголошувати метадані та перевірки рядків, так само як у [Query параметри та валідація рядків](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 | Технічні деталі
+
+Коли Ви імпортуєте `Query`, `Path` та інші з `fastapi`, насправді це функції.
+
+При виклику вони повертають екземпляри класів з такими ж іменами.
+
+Тобто Ви імпортуєте `Query`, яка є функцією. А коли Ви її викликаєте, вона повертає екземпляр класу, який теж називається `Query`.
+
+Ці функції створені таким чином (замість використання класів напряму), щоб Ваш редактор не відзначав їхні типи як помилки.
+
+Таким чином, Ви можете користуватися своїм звичайним редактором і інструментами для програмування без додаткових налаштувань для ігнорування таких помилок.
+
+///
diff --git a/docs/uk/docs/tutorial/path-params.md b/docs/uk/docs/tutorial/path-params.md
new file mode 100644
index 000000000..e7df1f19a
--- /dev/null
+++ b/docs/uk/docs/tutorial/path-params.md
@@ -0,0 +1,261 @@
+# Path Параметри
+
+Ви можете визначити "параметри" або "змінні" шляху, використовуючи синтаксис форматованих рядків:
+
+{* ../../docs_src/path_params/tutorial001.py hl[6:7] *}
+
+Значення параметра шляху `item_id` передається у функцію як аргумент `item_id`.
+
+Якщо запустити цей приклад та перейти за посиланням http://127.0.0.1:8000/items/foo, то отримаємо таку відповідь:
+
+```JSON
+{"item_id":"foo"}
+```
+
+## Path параметри з типами
+
+Ви можете визначити тип параметра шляху у функції, використовуючи стандартні анотації типів Python:
+
+{* ../../docs_src/path_params/tutorial002.py hl[7] *}
+
+У такому випадку `item_id` визначається як `int`.
+
+/// check | Примітка
+
+Це дасть можливість підтримки редактора всередині функції з перевірками помилок, автодоповнення тощо.
+
+///
+
+## Перетворення даних
+
+Якщо запустити цей приклад і перейти за посиланням http://127.0.0.1:8000/items/3, то отримаєте таку відповідь:
+
+```JSON
+{"item_id":3}
+```
+
+/// check | Примітка
+
+Зверніть увагу, що значення, яке отримала (і повернула) ваша функція, — це `3`. Це Python `int`, а не рядок `"3"`.
+
+Отже, з таким оголошенням типу **FastAPI** автоматично виконує "парсинг" запитів.
+
+///
+
+## Перевірка даних
+
+Якщо ж відкрити у браузері посилання http://127.0.0.1:8000/items/foo, то побачимо цікаву HTTP-помилку:
+
+```JSON
+{
+ "detail": [
+ {
+ "type": "int_parsing",
+ "loc": [
+ "path",
+ "item_id"
+ ],
+ "msg": "Input should be a valid integer, unable to parse string as an integer",
+ "input": "foo",
+ "url": "https://errors.pydantic.dev/2.1/v/int_parsing"
+ }
+ ]
+}
+```
+тому що параметр шляху має значення `"foo"`, яке не є типом `int`.
+
+Таку саму помилку отримаємо, якщо передати `float` замість `int`, як бачимо, у цьому прикладі: http://127.0.0.1:8000/items/4.2
+
+/// check | Примітка
+
+Отже, **FastAPI** надає перевірку типів з таким самим оголошенням типу в Python.
+
+Зверніть увагу, що помилка також чітко вказує саме на те місце, де валідація не пройшла.
+
+Це неймовірно корисно під час розробки та дебагінгу коду, що взаємодіє з вашим API.
+
+///
+
+## Документація
+
+Тепер коли відкриєте свій браузер за посиланням http://127.0.0.1:8000/docs, то побачите автоматично згенеровану, інтерактивну API-документацію:
+
+POST
.
+
+///
+
+/// warning | Увага
+
+Ви можете оголосити кілька параметрів `File` і `Form` в *операції шляху*, але Ви не можете одночасно оголошувати поля `Body`, які мають надходити у форматі JSON, оскільки тіло запиту буде закодоване у форматі `multipart/form-data`, а не `application/json`.
+
+Це не обмеження **FastAPI**, а особливість протоколу HTTP.
+
+///
+
+## Опціональне Завантаження Файлів
+
+Файл можна зробити необов’язковим, використовуючи стандартні анотації типів і встановлюючи значення за замовчуванням `None`:
+
+{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *}
+
+## `UploadFile` із Додатковими Мета Даними
+
+Ви також можете використовувати `File()` разом із `UploadFile`, наприклад, для встановлення додаткових метаданих:
+
+{* ../../docs_src/request_files/tutorial001_03_an_py39.py hl[9,15] *}
+
+## Завантаження Кількох Файлів
+
+Можна завантажувати кілька файлів одночасно.
+
+Вони будуть пов’язані з одним і тим самим "form field", який передається у вигляді "form data".
+
+Щоб це реалізувати, потрібно оголосити список `bytes` або `UploadFile`:
+
+{* ../../docs_src/request_files/tutorial002_an_py39.py hl[10,15] *}
+
+Ви отримаєте, як і було оголошено, `list` із `bytes` або `UploadFile`.
+
+/// note | Технічні деталі
+
+Ви також можете використати `from starlette.responses import HTMLResponse`.
+
+**FastAPI** надає ті ж самі `starlette.responses`, що й `fastapi.responses`, для зручності розробників. Однак більшість доступних відповідей надходять безпосередньо від Starlette.
+
+///
+
+### Завантаження декількох файлів із додатковими метаданими
+
+Так само як і раніше, Ви можете використовувати `File()`, щоб встановити додаткові параметри навіть для `UploadFile`:
+
+{* ../../docs_src/request_files/tutorial003_an_py39.py hl[11,18:20] *}
+
+## Підсумок
+
+Використовуйте `File`, `bytes`та `UploadFile`, щоб оголошувати файли для завантаження у запитах, які надсилаються у вигляді form data.
diff --git a/docs/uk/docs/tutorial/request-form-models.md b/docs/uk/docs/tutorial/request-form-models.md
new file mode 100644
index 000000000..7f5759e79
--- /dev/null
+++ b/docs/uk/docs/tutorial/request-form-models.md
@@ -0,0 +1,78 @@
+# Моделі форм (Form Models)
+
+У FastAPI Ви можете використовувати **Pydantic-моделі** для оголошення **полів форми**.
+
+/// info | Інформація
+
+Щоб використовувати форми, спочатку встановіть python-multipart.
+
+Переконайтеся, що Ви створили [віртуальне середовище](../virtual-environments.md){.internal-link target=_blank}, активували його, а потім встановили бібліотеку, наприклад:
+
+```console
+$ pip install python-multipart
+```
+
+///
+
+/// note | Підказка
+
+Ця функція підтримується, починаючи з FastAPI версії `0.113.0`. 🤓
+
+///
+
+## Використання Pydantic-моделей для форм
+
+Вам просто потрібно оголосити **Pydantic-модель** з полями, які Ви хочете отримати як **поля форми**, а потім оголосити параметр як `Form`:
+
+{* ../../docs_src/request_form_models/tutorial001_an_py39.py hl[9:11,15] *}
+
+**FastAPI** **витягне** дані для **кожного поля** з **формових даних** у запиті та надасть вам Pydantic-модель, яку Ви визначили.
+
+## Перевірка документації
+
+Ви можете перевірити це в UI документації за `/docs`:
+
+POST
.
+
+///
+
+/// warning | Попередження
+
+Ви можете оголосити кілька параметрів `Form` в *операції шляху*, але не можете одночасно оголосити поля `Body`, які Ви очікуєте отримати у форматі JSON, оскільки тіло запиту буде закодовано у форматі `application/x-www-form-urlencoded`, а не `application/json`.
+
+Це не обмеження **FastAPI**, а частина HTTP-протоколу.
+
+///
+
+## Підсумок
+
+Використовуйте `Form` для оголошення вхідних параметрів у вигляді даних форми.
diff --git a/docs/uk/docs/tutorial/response-status-code.md b/docs/uk/docs/tutorial/response-status-code.md
new file mode 100644
index 000000000..1ed69d6f2
--- /dev/null
+++ b/docs/uk/docs/tutorial/response-status-code.md
@@ -0,0 +1,100 @@
+# Статус коди Відповідей
+
+Так само як Ви можете вказати модель відповіді, Ви також можете оголосити HTTP код статусу для відповіді за допомогою параметра `status_code` в будь-якій з *операцій шляху*:
+
+* `@app.get()`
+* `@app.post()`
+* `@app.put()`
+* `@app.delete()`
+* тощо.
+
+{* ../../docs_src/response_status_code/tutorial001.py hl[6] *}
+
+/// note | Нотатка
+
+Зверніть увагу, що `status_code` є параметром методу "декоратора" (`get`, `post` і т.д.), а не Вашої *функції операції шляху*, як усі інші параметри та тіло запиту.
+
+///
+
+Параметр `status_code` приймає число, яке відповідає HTTP коду статусу.
+
+/// info | Інформація
+`status_code` також може отримувати значення з `IntEnum`, наприклад, з Python `http.HTTPStatus`.
+
+///
+
+Він буде:
+
+* Повертати вказаний код статусу у відповіді.
+* Документувати його як такий у схемі OpenAPI (і, таким чином, в інтерфейсі користувача):
+
++ FastAPI framework, hiệu năng cao, dễ học, dễ code, sẵn sàng để tạo ra sản phẩm +
+ + +--- + +**Tài liệu**: https://fastapi.tiangolo.com + +**Mã nguồn**: https://github.com/fastapi/fastapi + +--- + +FastAPI là một web framework hiện đại, hiệu năng cao để xây dựng web APIs với Python 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](#hieu-nang). +* **Code nhanh**: Tăng tốc độ phát triển tính năng từ 200% tới 300%. * +* **Ít lỗi hơn**: Giảm khoảng 40% những lỗi phát sinh bởi con người (nhà phát triển). * +* **Trực giác tốt hơn**: Được các trình soạn thảo hỗ tuyệt vời. Completion mọi nơi. Ít thời gian gỡ lỗi. +* **Dễ dàng**: Được thiết kế để dễ dàng học và sử dụng. Ít thời gian đọc tài liệu. +* **Ngắn**: Tối thiểu code bị trùng lặp. Nhiều tính năng được tích hợp khi định nghĩa tham số. Ít lỗi hơn. +* **Tăng tốc**: Có được sản phẩm cùng với tài liệu (được tự động tạo) có thể tương tác. +* **Được dựa trên các tiêu chuẩn**: Dựa trên (và hoàn toàn tương thích với) các tiêu chuẩn mở cho APIs : OpenAPI (trước đó được biết đến là Swagger) và JSON Schema. + +* ước tính được dựa trên những kiểm chứng trong nhóm phát triển nội bộ, xây dựng các ứng dụng sản phẩm. + +## Nhà tài trợ + + + +{% if sponsors %} +{% for sponsor in sponsors.gold -%} +async def
...uvicorn main:app --reload
...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).
+
+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`.
+* ujson
- Bắt buộc nếu bạn muốn sử dụng `UJSONResponse`.
+
+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 000000000..403e89930
--- /dev/null
+++ b/docs/vi/docs/python-types.md
@@ -0,0 +1,593 @@
+# 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:
+
+{* ../../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.
+
+{* ../../docs_src/python_types/tutorial001.py hl[2] *}
+
+
+### 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ả:
+
+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("/")`).
+
+{* ../../docs_src/first_steps/tutorial001.py hl[7] *}
+
+Đâ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`:
+
+{* ../../docs_src/first_steps/tutorial003.py hl[7] *}
+
+/// 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ề
+
+{* ../../docs_src/first_steps/tutorial001.py hl[8] *}
+
+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 000000000..dfeeed8c5
--- /dev/null
+++ b/docs/vi/docs/tutorial/index.md
@@ -0,0 +1,83 @@
+# Hướng dẫn sử dụng
+
+Hướng dẫn này cho bạn thấy từng bước cách sử dụng **FastAPI** đa số các tính năng của nó.
+
+Mỗi phần được xây dựng từ những phần trước đó, nhưng nó được cấu trúc thành các chủ đề riêng biệt, do đó bạn có thể xem trực tiếp từng phần cụ thể bất kì để giải quyết những API cụ thể mà bạn cần.
+
+Nó cũng được xây dựng để làm việc như một tham chiếu trong tương lai.
+
+Do đó bạn có thể quay lại và tìm chính xác những gì bạn cần.
+
+## Chạy mã
+
+Tất cả các code block có thể được sao chép và sử dụng trực tiếp (chúng thực chất là các tệp tin Python đã được kiểm thử).
+
+Để chạy bất kì ví dụ nào, sao chép code tới tệp tin `main.py`, và bắt đầu `uvicorn` với:
+
++ Ìlànà wẹ́ẹ́bù FastAPI, iṣẹ́ gíga, ó rọrùn láti kọ̀, o yára láti kóòdù, ó sì ṣetán fún iṣelọpọ ní lílo +
+ + +--- + +**Àkọsílẹ̀**: https://fastapi.tiangolo.com + +**Orisun Kóòdù**: https://github.com/fastapi/fastapi + +--- + +FastAPI jẹ́ ìgbàlódé, tí ó yára (iṣẹ-giga), ìlànà wẹ́ẹ́bù fún kikọ àwọn API pẹ̀lú Python è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](#isesi). +* **Ó yára láti kóòdù**: O mu iyara pọ si láti kọ àwọn ẹya tuntun kóòdù nipasẹ "Igba ìdá ọgọ́rùn-ún" (i.e. 200%) si "ọ̀ọ́dúrún ìdá ọgọ́rùn-ún" (i.e. 300%). +* **Àìtọ́ kékeré**: O n din aṣiṣe ku bi ọgbon ìdá ọgọ́rùn-ún (i.e. 40%) ti eda eniyan (oṣiṣẹ kóòdù) fa. * +* **Ọgbọ́n àti ìmọ̀**: Atilẹyin olootu nla. Ìparí nibi gbogbo. Àkókò díẹ̀ nipa wíwá ibi tí ìṣòro kóòdù wà. +* **Irọrun**: A kọ kí ó le rọrun láti lo àti láti kọ ẹkọ nínú rè. Ó máa fún ọ ní àkókò díẹ̀ látı ka àkọsílẹ. +* **Ó kúkurú ní kikọ**: Ó dín àtúnkọ àti àtúntò kóòdù kù. Ìkéde àṣàyàn kọ̀ọ̀kan nínú rẹ̀ ní ọ̀pọ̀lọpọ̀ àwọn ìlò. O ṣe iranlọwọ láti má ṣe ní ọ̀pọ̀lọpọ̀ àṣìṣe. +* **Ó lágbára**: Ó ń ṣe àgbéjáde kóòdù tí ó ṣetán fún ìṣelọ́pọ̀. Pẹ̀lú àkọsílẹ̀ tí ó máa ṣàlàyé ara rẹ̀ fún ẹ ní ìbáṣepọ̀ aládàáṣiṣẹ́ pẹ̀lú rè. +* **Ajohunše/Ìtọ́kasí**: Ó da lori (àti ibamu ni kikun pẹ̀lú) àwọn ìmọ ajohunše/ìtọ́kasí fún àwọn API: OpenAPI (èyí tí a mọ tẹlẹ si Swagger) àti JSON Schema. + +* iṣiro yi da lori àwọn idanwo tí ẹgbẹ ìdàgbàsókè FastAPI ṣe, nígbàtí wọn kọ àwọn ohun elo iṣelọpọ kóòdù pẹ̀lú rẹ. + +## Àwọn onígbọ̀wọ́ + + + +{% if sponsors %} +{% for sponsor in sponsors.gold -%} +async def
...uvicorn main:app --reload
...email-validator
- fún ifọwọsi ímeèlì.
+* pydantic-settings
- fún ètò ìsàkóso.
+* pydantic-extra-types
- fún àfikún oríṣi láti lọ pẹ̀lú Pydantic.
+
+Èyí tí Starlette ń lò:
+
+* httpx
- Nílò tí ó bá fẹ́ láti lọ `TestClient`.
+* jinja2
- Nílò tí ó bá fẹ́ láti lọ iṣeto awoṣe aiyipada.
+* python-multipart
- Nílò tí ó bá fẹ́ láti ṣe àtìlẹ́yìn fún "àyẹ̀wò" fọọmu, pẹ̀lú `request.form()`.
+* itsdangerous
- Nílò fún àtìlẹ́yìn `SessionMiddleware`.
+* pyyaml
- Nílò fún àtìlẹ́yìn Starlette's `SchemaGenerator` (ó ṣe ṣe kí ó má nílò rẹ̀ fún FastAPI).
+
+È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`.
+* ujson
- Nílò tí ó bá fẹ́ láti lọ `UJSONResponse`.
+
+Ó 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 000000000..de18856f4
--- /dev/null
+++ b/docs/yo/mkdocs.yml
@@ -0,0 +1 @@
+INHERIT: ../en/mkdocs.yml
diff --git a/docs/zh-hant/docs/about/index.md b/docs/zh-hant/docs/about/index.md
new file mode 100644
index 000000000..5dcee68f2
--- /dev/null
+++ b/docs/zh-hant/docs/about/index.md
@@ -0,0 +1,3 @@
+# 關於 FastAPI
+
+關於 FastAPI、其設計、靈感來源等更多資訊。 🤓
diff --git a/docs/zh-hant/docs/async.md b/docs/zh-hant/docs/async.md
new file mode 100644
index 000000000..6ab75d2ab
--- /dev/null
+++ b/docs/zh-hant/docs/async.md
@@ -0,0 +1,442 @@
+# 並行與 async / await
+
+有關*路徑操作函式*的 `async def` 語法的細節與非同步 (asynchronous) 程式碼、並行 (concurrency) 與平行 (parallelism) 的一些背景知識。
+
+## 趕時間嗎?
+
+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 密集型" 操作。
+
+之所以稱為「非同步」,是因為電腦/程式不需要與那些耗時的任務「同步」,等待任務完成的精確時間,然後才能取得結果並繼續工作。
+
+相反地,非同步系統在任務完成後,可以讓任務稍微等一下(幾微秒),等待電腦/程式完成手頭上的其他工作,然後再回來取得結果繼續進行。
+
+相對於「非同步」(asynchronous),「同步」(synchronous)也常被稱作「順序性」(sequential),因為電腦/程式會依序執行所有步驟,即便這些步驟涉及等待,才會切換到其他任務。
+
+### 並行與漢堡
+
+上述非同步程式碼的概念有時也被稱為「並行」,它不同於「平行」。
+
+並行和平行都與 "不同的事情或多或少同時發生" 有關。
+
+但並行和平行之間的細節是完全不同的。
+
+為了理解差異,請想像以下有關漢堡的故事:
+
+### 並行漢堡
+
+你和你的戀人去速食店,排隊等候時,收銀員正在幫排在你前面的人點餐。😍
+
++ FastAPI 框架,高效能,易於學習,快速開發,適用於生產環境 +
+ + +--- + +**文件**: https://fastapi.tiangolo.com + +**程式碼**: https://github.com/fastapi/fastapi + +--- + +FastAPI 是一個現代、快速(高效能)的 web 框架,用於 Python 並採用標準 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 -%} +async def
...uvicorn main:app --reload
...email-validator
- 用於電子郵件驗證。
+- pydantic-settings
- 用於設定管理。
+- pydantic-extra-types
- 用於與 Pydantic 一起使用的額外型別。
+
+用於 Starlette:
+
+- httpx
- 使用 `TestClient`時必須安裝。
+- jinja2
- 使用預設的模板配置時必須安裝。
+- python-multipart
- 需要使用 `request.form()` 對表單進行 "解析" 時安裝。
+- itsdangerous
- 需要使用 `SessionMiddleware` 支援時安裝。
+- pyyaml
- 用於支援 Starlette 的 `SchemaGenerator` (如果你使用 FastAPI,可能不需要它)。
+
+用於 FastAPI / Starlette:
+
+- uvicorn
- 用於加載和運行應用程式的服務器。
+- orjson
- 使用 `ORJSONResponse`時必須安裝。
+- ujson
- 使用 `UJSONResponse` 時必須安裝。
+
+你可以使用 `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 000000000..eb7d7096a
--- /dev/null
+++ b/docs/zh-hant/docs/learn/index.md
@@ -0,0 +1,5 @@
+# 學習
+
+以下是學習 FastAPI 的入門介紹和教學。
+
+你可以將其視為一本**書籍**或一門**課程**,這是**官方**認可並推薦的 FastAPI 學習方式。 😎
diff --git a/docs/zh-hant/docs/resources/index.md b/docs/zh-hant/docs/resources/index.md
new file mode 100644
index 000000000..f4c70a3a0
--- /dev/null
+++ b/docs/zh-hant/docs/resources/index.md
@@ -0,0 +1,3 @@
+# 資源
+
+額外的資源、外部連結、文章等。 ✈️
diff --git a/docs/zh-hant/docs/tutorial/first-steps.md b/docs/zh-hant/docs/tutorial/first-steps.md
new file mode 100644
index 000000000..a557fa369
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/first-steps.md
@@ -0,0 +1,331 @@
+# 第一步
+
+最簡單的 FastAPI 檔案可能看起來像這樣:
+
+{* ../../docs_src/first_steps/tutorial001.py *}
+
+將其複製到一個名為 `main.py` 的文件中。
+
+執行即時重新載入伺服器(live server):
+
+get
操作
+
+/// info | `@decorator` Info
+
+Python 中的 `@something` 語法被稱為「裝飾器」。
+
+你把它放在一個函式上面。像一個漂亮的裝飾帽子(我猜這是術語的來源)。
+
+一個「裝飾器」會對下面的函式做一些事情。
+
+在這種情況下,這個裝飾器告訴 **FastAPI** 那個函式對應於 **路徑** `/` 和 **操作** `get`.
+
+這就是「**路徑操作裝飾器**」。
+
+///
+
+你也可以使用其他的操作:
+
+* `@app.post()`
+* `@app.put()`
+* `@app.delete()`
+
+以及更少見的:
+
+* `@app.options()`
+* `@app.head()`
+* `@app.patch()`
+* `@app.trace()`
+
+/// tip
+
+你可以自由地使用每個操作(HTTP 方法)。
+
+**FastAPI** 不強制任何特定的意義。
+
+這裡的資訊作為一個指南,而不是要求。
+
+例如,當使用 GraphQL 時,你通常只使用 `POST` 操作。
+
+///
+
+### 第四步:定義 **路徑操作函式**
+
+這是我們的「**路徑操作函式**」:
+
+* **path**: 是 `/`.
+* **operation**: 是 `get`.
+* **function**: 是裝飾器下面的函式(在 `@app.get("/")` 下面)。
+
+{* ../../docs_src/first_steps/tutorial001.py h1[7] *}
+
+這就是一個 Python 函式。
+
+它將會在 **FastAPI** 收到一個請求時被呼叫,使用 `GET` 操作。
+
+在這種情況下,它是一個 `async` 函式。
+
+---
+
+你可以將它定義為一個正常的函式,而不是 `async def`:
+
+{* ../../docs_src/first_steps/tutorial003.py h1[7] *}
+
+/// note
+
+如果你不知道差別,請查看 [Async: *"In a hurry?"*](../async.md#in-a-hurry){.internal-link target=_blank}.
+
+///
+
+### 第五步:回傳內容
+
+{* ../../docs_src/first_steps/tutorial001.py h1[8] *}
+
+你可以返回一個 `dict`、`list`、單個值作為 `str`、`int` 等。
+
+你也可以返回 Pydantic 模型(稍後你會看到更多關於這方面的內容)。
+
+有很多其他物件和模型會自動轉換為 JSON(包括 ORMs,等等)。試用你最喜歡的,很有可能它們已經有支援。
+
+## 回顧
+
+* 引入 `FastAPI`.
+* 建立一個 `app` 實例。
+* 寫一個 **路徑操作裝飾器** 使用裝飾器像 `@app.get("/")`。
+* 定義一個 **路徑操作函式**;例如,`def root(): ...`。
+* 使用命令 `fastapi dev` 執行開發伺服器。
diff --git a/docs/zh-hant/docs/tutorial/index.md b/docs/zh-hant/docs/tutorial/index.md
new file mode 100644
index 000000000..ae0056f52
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/index.md
@@ -0,0 +1,102 @@
+# 教學 - 使用者指南
+
+本教學將一步一步展示如何使用 **FastAPI** 及其大多數功能。
+
+每個部分都是在前一部分的基礎上逐步建置的,但內容結構是按主題分開的,因此你可以直接跳到任何特定的部分,解決你具體的 API 需求。
+
+它也被設計成可作為未來的參考,讓你隨時回來查看所需的內容。
+
+## 運行程式碼
+
+所有程式碼區塊都可以直接複製和使用(它們實際上是經過測試的 Python 檔案)。
+
+要運行任何範例,請將程式碼複製到 `main.py` 檔案,並使用以下命令啟動 `fastapi dev`:
+
++没有大家之前所做的工作,**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/how-to/configure-swagger-ui.md b/docs/zh/docs/how-to/configure-swagger-ui.md new file mode 100644 index 000000000..108e0cb95 --- /dev/null +++ b/docs/zh/docs/how-to/configure-swagger-ui.md @@ -0,0 +1,70 @@ +# 配置 Swagger UI + +你可以配置一些额外的 Swagger UI 参数. + +如果需要配置它们,可以在创建 `FastAPI()` 应用对象时或调用 `get_swagger_ui_html()` 函数时传递 `swagger_ui_parameters` 参数。 + +`swagger_ui_parameters` 接受一个直接传递给 Swagger UI的字典,包含配置参数键值对。 + +FastAPI会将这些配置转换为 **JSON**,使其与 JavaScript 兼容,因为这是 Swagger UI 需要的。 + +## 不使用语法高亮 + +比如,你可以禁用 Swagger UI 中的语法高亮。 + +当没有改变设置时,语法高亮默认启用: + +
ujson
- 更快的 JSON 「解析」。
-* email_validator
- 用于 email 校验。
+* email-validator
- 用于 email 校验。
用于 Starlette:
* httpx
- 使用 `TestClient` 时安装。
* jinja2
- 使用默认模板配置时安装。
-* python-multipart
- 需要通过 `request.form()` 对表单进行「解析」时安装。
+* python-multipart
- 需要通过 `request.form()` 对表单进行「解析」时安装。
* itsdangerous
- 需要 `SessionMiddleware` 支持时安装。
* pyyaml
- 使用 Starlette 提供的 `SchemaGenerator` 时安装(有 FastAPI 你可能并不需要它)。
* graphene
- 需要 `GraphQLApp` 支持时安装。
-* ujson
- 使用 `UJSONResponse` 时安装。
用于 FastAPI / Starlette:
* uvicorn
- 用于加载和运行你的应用程序的服务器。
* orjson
- 使用 `ORJSONResponse` 时安装。
+* ujson
- 使用 `UJSONResponse` 时安装。
-你可以通过 `pip install fastapi[all]` 命令来安装以上所有依赖。
+你可以通过 `pip install "fastapi[all]"` 命令来安装以上所有依赖。
## 许可协议
diff --git a/docs/zh/docs/learn/index.md b/docs/zh/docs/learn/index.md
new file mode 100644
index 000000000..38696f6fe
--- /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 000000000..48eb990df
--- /dev/null
+++ b/docs/zh/docs/project-generation.md
@@ -0,0 +1,28 @@
+# FastAPI全栈模板
+
+模板通常带有特定的设置,而且被设计为灵活和可定制的。这允许您根据项目的需求修改和调整它们,使它们成为一个很好的起点。🏁
+
+您可以使用此模板开始,因为它包含了许多已经为您完成的初始设置、安全性、数据库和一些API端点。
+
+代码仓: Full Stack FastAPI Template
+
+## FastAPI全栈模板 - 技术栈和特性
+
+- ⚡ [**FastAPI**](https://fastapi.tiangolo.com) 用于Python后端API.
+ - 🧰 [SQLModel](https://sqlmodel.tiangolo.com) 用于Python和SQL数据库的集成(ORM)。
+ - 🔍 [Pydantic](https://docs.pydantic.dev) FastAPI的依赖项之一,用于数据验证和配置管理。
+ - 💾 [PostgreSQL](https://www.postgresql.org) 作为SQL数据库。
+- 🚀 [React](https://react.dev) 用于前端。
+ - 💃 使用了TypeScript、hooks、[Vite](https://vitejs.dev)和其他一些现代化的前端技术栈。
+ - 🎨 [Chakra UI](https://chakra-ui.com) 用于前端组件。
+ - 🤖 一个自动化生成的前端客户端。
+ - 🧪 [Playwright](https://playwright.dev)用于端到端测试。
+ - 🦇 支持暗黑主题(Dark mode)。
+- 🐋 [Docker Compose](https://www.docker.com) 用于开发环境和生产环境。
+- 🔒 默认使用密码哈希来保证安全。
+- 🔑 JWT令牌用于权限验证。
+- 📫 使用邮箱来进行密码恢复。
+- ✅ 单元测试用了[Pytest](https://pytest.org).
+- 📞 [Traefik](https://traefik.io) 用于反向代理和负载均衡。
+- 🚢 部署指南(Docker Compose)包含了如何起一个Traefik前端代理来自动化HTTPS认证。
+- 🏭 CI(持续集成)和 CD(持续部署)基于GitHub Actions。
diff --git a/docs/zh/docs/python-types.md b/docs/zh/docs/python-types.md
index 6cdb4b588..ba767da87 100644
--- a/docs/zh/docs/python-types.md
+++ b/docs/zh/docs/python-types.md
@@ -12,16 +12,18 @@
但即使你不会用到 **FastAPI**,了解一下类型提示也会让你从中受益。
-!!! note
- 如果你已经精通 Python,并且了解关于类型提示的一切知识,直接跳到下一章节吧。
+/// note
+
+如果你已经精通 Python,并且了解关于类型提示的一切知识,直接跳到下一章节吧。
+
+///
## 动机
让我们从一个简单的例子开始:
-```Python
-{!../../../docs_src/python_types/tutorial001.py!}
-```
+{* ../../docs_src/python_types/tutorial001.py *}
+
运行这段程序将输出:
@@ -35,9 +37,8 @@ John Doe
* 通过 `title()` 将每个参数的第一个字母转换为大写形式。
* 中间用一个空格来拼接它们。
-```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial001.py!}
-```
+{* ../../docs_src/python_types/tutorial001.py hl[2] *}
+
### 修改示例
@@ -79,9 +80,8 @@ John Doe
这些就是"类型提示":
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial002.py!}
-```
+{* ../../docs_src/python_types/tutorial002.py hl[1] *}
+
这和声明默认值是不同的,例如:
@@ -109,9 +109,8 @@ John Doe
下面是一个已经有类型提示的函数:
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial003.py!}
-```
+{* ../../docs_src/python_types/tutorial003.py hl[1] *}
+
因为编辑器已经知道了这些变量的类型,所以不仅能对代码进行补全,还能检查其中的错误:
@@ -119,9 +118,8 @@ John Doe
现在你知道了必须先修复这个问题,通过 `str(age)` 把 `age` 转换成字符串:
-```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial004.py!}
-```
+{* ../../docs_src/python_types/tutorial004.py hl[2] *}
+
## 声明类型
@@ -140,9 +138,8 @@ John Doe
* `bool`
* `bytes`
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial005.py!}
-```
+{* ../../docs_src/python_types/tutorial005.py hl[1] *}
+
### 嵌套类型
@@ -158,9 +155,8 @@ John Doe
从 `typing` 模块导入 `List`(注意是大写的 `L`):
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial006.py!}
-```
+{* ../../docs_src/python_types/tutorial006.py hl[1] *}
+
同样以冒号(`:`)来声明这个变量。
@@ -168,9 +164,8 @@ John Doe
由于列表是带有"子类型"的类型,所以我们把子类型放在方括号中:
-```Python hl_lines="4"
-{!../../../docs_src/python_types/tutorial006.py!}
-```
+{* ../../docs_src/python_types/tutorial006.py hl[4] *}
+
这表示:"变量 `items` 是一个 `list`,并且这个列表里的每一个元素都是 `str`"。
@@ -188,9 +183,8 @@ John Doe
声明 `tuple` 和 `set` 的方法也是一样的:
-```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial007.py!}
-```
+{* ../../docs_src/python_types/tutorial007.py hl[1,4] *}
+
这表示:
@@ -205,9 +199,8 @@ John Doe
第二个子类型声明 `dict` 的所有值:
-```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial008.py!}
-```
+{* ../../docs_src/python_types/tutorial008.py hl[1,4] *}
+
这表示:
@@ -221,15 +214,13 @@ John Doe
假设你有一个名为 `Person` 的类,拥有 name 属性:
-```Python hl_lines="1-3"
-{!../../../docs_src/python_types/tutorial010.py!}
-```
+{* ../../docs_src/python_types/tutorial010.py hl[1:3] *}
+
接下来,你可以将一个变量声明为 `Person` 类型:
-```Python hl_lines="6"
-{!../../../docs_src/python_types/tutorial010.py!}
-```
+{* ../../docs_src/python_types/tutorial010.py hl[6] *}
+
然后,你将再次获得所有的编辑器支持:
@@ -237,7 +228,7 @@ John Doe
## Pydantic 模型
-Pydantic 是一个用来用来执行数据校验的 Python 库。
+Pydantic 是一个用来执行数据校验的 Python 库。
你可以将数据的"结构"声明为具有属性的类。
@@ -249,12 +240,14 @@ John Doe
下面的例子来自 Pydantic 官方文档:
-```Python
-{!../../../docs_src/python_types/tutorial010.py!}
-```
+{* ../../docs_src/python_types/tutorial010.py *}
+
-!!! info
- 想进一步了解 Pydantic,请阅读其文档.
+/// info
+
+想进一步了解 Pydantic,请阅读其文档.
+
+///
整个 **FastAPI** 建立在 Pydantic 的基础之上。
@@ -282,5 +275,8 @@ John Doe
最重要的是,通过使用标准的 Python 类型,只需要在一个地方声明(而不是添加更多的类、装饰器等),**FastAPI** 会为你完成很多的工作。
-!!! info
- 如果你已经阅读了所有教程,回过头来想了解有关类型的更多信息,来自 `mypy` 的"速查表"是不错的资源。
+/// info
+
+如果你已经阅读了所有教程,回过头来想了解有关类型的更多信息,来自 `mypy` 的"速查表"是不错的资源。
+
+///
diff --git a/docs/zh/docs/tutorial/background-tasks.md b/docs/zh/docs/tutorial/background-tasks.md
new file mode 100644
index 000000000..40e61add7
--- /dev/null
+++ b/docs/zh/docs/tutorial/background-tasks.md
@@ -0,0 +1,124 @@
+# 后台任务
+
+你可以定义在返回响应后运行的后台任务。
+
+这对需要在请求之后执行的操作很有用,但客户端不必在接收响应之前等待操作完成。
+
+包括这些例子:
+
+* 执行操作后发送的电子邮件通知:
+ * 由于连接到电子邮件服务器并发送电子邮件往往很“慢”(几秒钟),您可以立即返回响应并在后台发送电子邮件通知。
+* 处理数据:
+ * 例如,假设您收到的文件必须经过一个缓慢的过程,您可以返回一个"Accepted"(HTTP 202)响应并在后台处理它。
+
+## 使用 `BackgroundTasks`
+
+首先导入 `BackgroundTasks` 并在 *路径操作函数* 中使用类型声明 `BackgroundTasks` 定义一个参数:
+
+{* ../../docs_src/background_tasks/tutorial001.py hl[1, 13] *}
+
+**FastAPI** 会创建一个 `BackgroundTasks` 类型的对象并作为该参数传入。
+
+## 创建一个任务函数
+
+创建要作为后台任务运行的函数。
+
+它只是一个可以接收参数的标准函数。
+
+它可以是 `async def` 或普通的 `def` 函数,**FastAPI** 知道如何正确处理。
+
+在这种情况下,任务函数将写入一个文件(模拟发送电子邮件)。
+
+由于写操作不使用 `async` 和 `await`,我们用普通的 `def` 定义函数:
+
+{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *}
+
+## 添加后台任务
+
+在你的 *路径操作函数* 里,用 `.add_task()` 方法将任务函数传到 *后台任务* 对象中:
+
+{* ../../docs_src/background_tasks/tutorial001.py hl[14] *}
+
+`.add_task()` 接收以下参数:
+
+* 在后台运行的任务函数(`write_notification`)。
+* 应按顺序传递给任务函数的任意参数序列(`email`)。
+* 应传递给任务函数的任意关键字参数(`message="some notification"`)。
+
+## 依赖注入
+
+使用 `BackgroundTasks` 也适用于依赖注入系统,你可以在多个级别声明 `BackgroundTasks` 类型的参数:在 *路径操作函数* 里,在依赖中(可依赖),在子依赖中,等等。
+
+**FastAPI** 知道在每种情况下该做什么以及如何复用同一对象,因此所有后台任务被合并在一起并且随后在后台运行:
+
+//// tab | Python 3.10+
+
+{* ../../docs_src/background_tasks/tutorial002_an_py310.py hl[13, 15, 22, 25] *}
+
+////
+
+//// tab | Python 3.9+
+
+{* ../../docs_src/background_tasks/tutorial002_an_py39.py hl[13, 15, 22, 25] *}
+
+////
+
+//// tab | Python 3.8+
+
+{* ../../docs_src/background_tasks/tutorial002_an.py hl[14, 16, 23, 26] *}
+
+////
+
+//// tab | Python 3.10+ 没Annotated
+
+/// tip
+
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+{* ../../docs_src/background_tasks/tutorial002_py310.py hl[11, 13, 20, 23] *}
+
+////
+
+//// tab | Python 3.8+ 没Annotated
+
+/// tip
+
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+{* ../../docs_src/background_tasks/tutorial002.py hl[13, 15, 22, 25] *}
+
+////
+
+该示例中,信息会在响应发出 *之后* 被写到 `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,但它们允许您在多个进程中运行后台任务,甚至是在多个服务器中。
+
+但是,如果您需要从同一个**FastAPI**应用程序访问变量和对象,或者您需要执行小型后台任务(如发送电子邮件通知),您只需使用 `BackgroundTasks` 即可。
+
+## 回顾
+
+导入并使用 `BackgroundTasks` 通过 *路径操作函数* 中的参数和依赖项来添加后台任务。
diff --git a/docs/zh/docs/tutorial/bigger-applications.md b/docs/zh/docs/tutorial/bigger-applications.md
index 9f0134f68..554bc654f 100644
--- a/docs/zh/docs/tutorial/bigger-applications.md
+++ b/docs/zh/docs/tutorial/bigger-applications.md
@@ -4,8 +4,11 @@
**FastAPI** 提供了一个方便的工具,可以在保持所有灵活性的同时构建你的应用程序。
-!!! info
- 如果你来自 Flask,那这将相当于 Flask 的 Blueprints。
+/// info
+
+如果你来自 Flask,那这将相当于 Flask 的 Blueprints。
+
+///
## 一个文件结构示例
@@ -26,16 +29,19 @@
│ └── admin.py
```
-!!! tip
- 上面有几个 `__init__.py` 文件:每个目录或子目录中都有一个。
+/// tip
+
+上面有几个 `__init__.py` 文件:每个目录或子目录中都有一个。
- 这就是能将代码从一个文件导入到另一个文件的原因。
+这就是能将代码从一个文件导入到另一个文件的原因。
- 例如,在 `app/main.py` 中,你可以有如下一行:
+例如,在 `app/main.py` 中,你可以有如下一行:
+
+```
+from app.routers import items
+```
- ```
- from app.routers import items
- ```
+///
* `app` 目录包含了所有内容。并且它有一个空文件 `app/__init__.py`,因此它是一个「Python 包」(「Python 模块」的集合):`app`。
* 它包含一个 `app/main.py` 文件。由于它位于一个 Python 包(一个包含 `__init__.py` 文件的目录)中,因此它是该包的一个「模块」:`app.main`。
@@ -46,7 +52,7 @@
* 还有一个子目录 `app/internal/` 包含另一个 `__init__.py` 文件,因此它是又一个「Python 子包」:`app.internal`。
* `app/internal/admin.py` 是另一个子模块:`app.internal.admin`。
-get
操作
-!!! info "`@decorator` Info"
- `@something` 语法在 Python 中被称为「装饰器」。
+/// info | `@decorator` Info
- 像一顶漂亮的装饰帽一样,将它放在一个函数的上方(我猜测这个术语的命名就是这么来的)。
+`@something` 语法在 Python 中被称为「装饰器」。
- 装饰器接收位于其下方的函数并且用它完成一些工作。
+像一顶漂亮的装饰帽一样,将它放在一个函数的上方(我猜测这个术语的命名就是这么来的)。
- 在我们的例子中,这个装饰器告诉 **FastAPI** 位于其下方的函数对应着**路径** `/` 加上 `get` **操作**。
+装饰器接收位于其下方的函数并且用它完成一些工作。
- 它是一个「**路径操作装饰器**」。
+在我们的例子中,这个装饰器告诉 **FastAPI** 位于其下方的函数对应着**路径** `/` 加上 `get` **操作**。
+
+它是一个「**路径操作装饰器**」。
+
+///
你也可以使用其他的操作:
@@ -276,14 +264,17 @@ https://example.com/items/foo
* `@app.patch()`
* `@app.trace()`
-!!! tip
- 您可以随意使用任何一个操作(HTTP方法)。
+/// tip
+
+你可以随意使用任何一个操作(HTTP方法)。
- **FastAPI** 没有强制要求操作有任何特定的含义。
+**FastAPI** 没有强制要求操作有任何特定的含义。
- 此处提供的信息仅作为指导,而不是要求。
+此处提供的信息仅作为指导,而不是要求。
- 比如,当使用 GraphQL 时通常你所有的动作都通过 `post` 一种方法执行。
+比如,当使用 GraphQL 时通常你所有的动作都通过 `POST` 一种方法执行。
+
+///
### 步骤 4:定义**路径操作函数**
@@ -293,9 +284,7 @@ https://example.com/items/foo
* **操作**:是 `get`。
* **函数**:是位于「装饰器」下方的函数(位于 `@app.get("/")` 下方)。
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[7] *}
这是一个 Python 函数。
@@ -307,18 +296,17 @@ https://example.com/items/foo
你也可以将其定义为常规函数而不使用 `async def`:
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial003.py!}
-```
+{* ../../docs_src/first_steps/tutorial003.py hl[7] *}
-!!! note
- 如果你不知道两者的区别,请查阅 [Async: *"In a hurry?"*](https://fastapi.tiangolo.com/async/#in-a-hurry){.internal-link target=_blank}。
+/// note
+
+如果你不知道两者的区别,请查阅 [并发: *赶时间吗?*](../async.md#_1){.internal-link target=_blank}。
+
+///
### 步骤 5:返回内容
-```Python hl_lines="8"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[8] *}
你可以返回一个 `dict`、`list`,像 `str`、`int` 一样的单个值,等等。
@@ -330,6 +318,6 @@ https://example.com/items/foo
* 导入 `FastAPI`。
* 创建一个 `app` 实例。
-* 编写一个**路径操作装饰器**(如 `@app.get("/")`)。
-* 编写一个**路径操作函数**(如上面的 `def root(): ...`)。
-* 运行开发服务器(如 `uvicorn main:app --reload`)。
+* 编写一个**路径操作装饰器**,如 `@app.get("/")`。
+* 定义一个**路径操作函数**,如 `def root(): ...`。
+* 使用命令 `fastapi dev` 运行开发服务器。
diff --git a/docs/zh/docs/tutorial/handling-errors.md b/docs/zh/docs/tutorial/handling-errors.md
index 9b066bc2c..0b887c292 100644
--- a/docs/zh/docs/tutorial/handling-errors.md
+++ b/docs/zh/docs/tutorial/handling-errors.md
@@ -25,10 +25,7 @@
### 导入 `HTTPException`
-```Python hl_lines="1"
-{!../../../docs_src/handling_errors/tutorial001.py!}
-
-```
+{* ../../docs_src/handling_errors/tutorial001.py hl[1] *}
### 触发 `HTTPException`
@@ -42,10 +39,7 @@
本例中,客户端用 `ID` 请求的 `item` 不存在时,触发状态码为 `404` 的异常:
-```Python hl_lines="11"
-{!../../../docs_src/handling_errors/tutorial001.py!}
-
-```
+{* ../../docs_src/handling_errors/tutorial001.py hl[11] *}
### 响应结果
@@ -67,14 +61,15 @@
```
-!!! tip "提示"
+/// tip | 提示
- 触发 `HTTPException` 时,可以用参数 `detail` 传递任何能转换为 JSON 的值,不仅限于 `str`。
+触发 `HTTPException` 时,可以用参数 `detail` 传递任何能转换为 JSON 的值,不仅限于 `str`。
- 还支持传递 `dict`、`list` 等数据结构。
+还支持传递 `dict`、`list` 等数据结构。
- **FastAPI** 能自动处理这些数据,并将之转换为 JSON。
+**FastAPI** 能自动处理这些数据,并将之转换为 JSON。
+///
## 添加自定义响应头
@@ -84,10 +79,7 @@
但对于某些高级应用场景,还是需要添加自定义响应头:
-```Python hl_lines="14"
-{!../../../docs_src/handling_errors/tutorial002.py!}
-
-```
+{* ../../docs_src/handling_errors/tutorial002.py hl[14] *}
## 安装自定义异常处理器
@@ -99,10 +91,7 @@
此时,可以用 `@app.exception_handler()` 添加自定义异常控制器:
-```Python hl_lines="5-7 13-18 24"
-{!../../../docs_src/handling_errors/tutorial003.py!}
-
-```
+{* ../../docs_src/handling_errors/tutorial003.py hl[5:7,13:18,24] *}
请求 `/unicorns/yolo` 时,路径操作会触发 `UnicornException`。
@@ -115,12 +104,13 @@
```
-!!! note "技术细节"
+/// note | 技术细节
- `from starlette.requests import Request` 和 `from starlette.responses import JSONResponse` 也可以用于导入 `Request` 和 `JSONResponse`。
+`from starlette.requests import Request` 和 `from starlette.responses import JSONResponse` 也可以用于导入 `Request` 和 `JSONResponse`。
- **FastAPI** 提供了与 `starlette.responses` 相同的 `fastapi.responses` 作为快捷方式,但大部分响应操作都可以直接从 Starlette 导入。同理,`Request` 也是如此。
+**FastAPI** 提供了与 `starlette.responses` 相同的 `fastapi.responses` 作为快捷方式,但大部分响应操作都可以直接从 Starlette 导入。同理,`Request` 也是如此。
+///
## 覆盖默认异常处理器
@@ -140,12 +130,9 @@
这样,异常处理器就可以接收 `Request` 与异常。
-```Python hl_lines="2 14-16"
-{!../../../docs_src/handling_errors/tutorial004.py!}
+{* ../../docs_src/handling_errors/tutorial004.py hl[2,14:16] *}
-```
-
-访问 `/items/foo`,可以看到以下内容替换了默认 JSON 错误信息:
+访问 `/items/foo`,可以看到默认的 JSON 错误信息:
```JSON
{
@@ -163,7 +150,7 @@
```
-以下是文本格式的错误信息:
+被替换为了以下文本格式的错误信息:
```
1 validation error
@@ -174,12 +161,13 @@ path -> item_id
### `RequestValidationError` vs `ValidationError`
-!!! warning "警告"
+/// warning | 警告
- 如果您觉得现在还用不到以下技术细节,可以先跳过下面的内容。
+如果您觉得现在还用不到以下技术细节,可以先跳过下面的内容。
+///
-`RequestValidationError` 是 Pydantic 的 `ValidationError` 的子类。
+`RequestValidationError` 是 Pydantic 的 `ValidationError` 的子类。
**FastAPI** 调用的就是 `RequestValidationError` 类,因此,如果在 `response_model` 中使用 Pydantic 模型,且数据有错误时,在日志中就会看到这个错误。
@@ -195,17 +183,15 @@ path -> item_id
例如,只为错误返回纯文本响应,而不是返回 JSON 格式的内容:
-```Python hl_lines="3-4 9-11 22"
-{!../../../docs_src/handling_errors/tutorial004.py!}
-
-```
+{* ../../docs_src/handling_errors/tutorial004.py hl[3:4,9:11,22] *}
-!!! note "技术细节"
+/// note | 技术细节
- 还可以使用 `from starlette.responses import PlainTextResponse`。
+还可以使用 `from starlette.responses import PlainTextResponse`。
- **FastAPI** 提供了与 `starlette.responses` 相同的 `fastapi.responses` 作为快捷方式,但大部分响应都可以直接从 Starlette 导入。
+**FastAPI** 提供了与 `starlette.responses` 相同的 `fastapi.responses` 作为快捷方式,但大部分响应都可以直接从 Starlette 导入。
+///
### 使用 `RequestValidationError` 的请求体
@@ -213,10 +199,7 @@ path -> item_id
开发时,可以用这个请求体生成日志、调试错误,并返回给用户。
-```Python hl_lines="14"
-{!../../../docs_src/handling_errors/tutorial005.py!}
-
-```
+{* ../../docs_src/handling_errors/tutorial005.py hl[14] *}
现在试着发送一个无效的 `item`,例如:
@@ -279,10 +262,7 @@ FastAPI 支持先对异常进行某些处理,然后再使用 **FastAPI** 中
从 `fastapi.exception_handlers` 中导入要复用的默认异常处理器:
-```Python hl_lines="2-5 15 21"
-{!../../../docs_src/handling_errors/tutorial006.py!}
-
-```
+{* ../../docs_src/handling_errors/tutorial006.py hl[2:5,15,21] *}
虽然,本例只是输出了夸大其词的错误信息。
diff --git a/docs/zh/docs/tutorial/header-param-models.md b/docs/zh/docs/tutorial/header-param-models.md
new file mode 100644
index 000000000..13366aebc
--- /dev/null
+++ b/docs/zh/docs/tutorial/header-param-models.md
@@ -0,0 +1,56 @@
+# Header 参数模型
+
+如果您有一组相关的 **header 参数**,您可以创建一个 **Pydantic 模型**来声明它们。
+
+这将允许您在**多个地方**能够**重用模型**,并且可以一次性声明所有参数的验证和元数据。😎
+
+/// note
+
+自 FastAPI 版本 `0.115.0` 起支持此功能。🤓
+
+///
+
+## 使用 Pydantic 模型的 Header 参数
+
+在 **Pydantic 模型**中声明所需的 **header 参数**,然后将参数声明为 `Header` :
+
+{* ../../docs_src/header_param_models/tutorial001_an_py310.py hl[9:14,18] *}
+
+**FastAPI** 将从请求中接收到的 **headers** 中**提取**出**每个字段**的数据,并提供您定义的 Pydantic 模型。
+
+## 查看文档
+
+您可以在文档 UI 的 `/docs` 中查看所需的 headers:
+
+contact
字段参数 | Type | 描述 |
---|---|---|
name | str | 联系人/组织的识别名称。 |
url | str | 指向联系信息的 URL。必须采用 URL 格式。 |
email | str | 联系人/组织的电子邮件地址。必须采用电子邮件地址的格式。 |
license_info
字段参数 | 类型 | 描述 |
---|---|---|
name | str | 必须的 (如果设置了license_info ). 用于 API 的许可证名称。 |
identifier | str | 一个API的SPDX许可证表达。 The identifier field is mutually exclusive of the url field. 自 OpenAPI 3.1.0、FastAPI 0.99.0 起可用。 |
url | str | 用于 API 的许可证的 URL。必须采用 URL 格式。 |
kwargs
,来调用。即使它们没有默认值。
-```Python hl_lines="7"
-{!../../../docs_src/path_params_numeric_validations/tutorial003.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *}
## 数值校验:大于等于
@@ -65,9 +60,7 @@ Python 不会对该 `*` 做任何事情,但是它将知道之后的所有参
像下面这样,添加 `ge=1` 后,`item_id` 将必须是一个大于(`g`reater than)或等于(`e`qual)`1` 的整数。
-```Python hl_lines="8"
-{!../../../docs_src/path_params_numeric_validations/tutorial004.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial004.py hl[8] *}
## 数值校验:大于和小于等于
@@ -76,9 +69,7 @@ Python 不会对该 `*` 做任何事情,但是它将知道之后的所有参
* `gt`:大于(`g`reater `t`han)
* `le`:小于等于(`l`ess than or `e`qual)
-```Python hl_lines="9"
-{!../../../docs_src/path_params_numeric_validations/tutorial005.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial005.py hl[9] *}
## 数值校验:浮点数、大于和小于
@@ -90,9 +81,7 @@ Python 不会对该 `*` 做任何事情,但是它将知道之后的所有参
对于 lt
也是一样的。
-```Python hl_lines="11"
-{!../../../docs_src/path_params_numeric_validations/tutorial006.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial006.py hl[11] *}
## 总结
@@ -105,18 +94,24 @@ Python 不会对该 `*` 做任何事情,但是它将知道之后的所有参
* `lt`:小于(`l`ess `t`han)
* `le`:小于等于(`l`ess than or `e`qual)
-!!! info
- `Query`、`Path` 以及你后面会看到的其他类继承自一个共同的 `Param` 类(不需要直接使用它)。
+/// info
+
+`Query`、`Path` 以及你后面会看到的其他类继承自一个共同的 `Param` 类(不需要直接使用它)。
+
+而且它们都共享相同的所有你已看到并用于添加额外校验和元数据的参数。
+
+///
+
+/// note | 技术细节
- 而且它们都共享相同的所有你已看到并用于添加额外校验和元数据的参数。
+当你从 `fastapi` 导入 `Query`、`Path` 和其他同类对象时,它们实际上是函数。
-!!! note "技术细节"
- 当你从 `fastapi` 导入 `Query`、`Path` 和其他同类对象时,它们实际上是函数。
+当被调用时,它们返回同名类的实例。
- 当被调用时,它们返回同名类的实例。
+如此,你导入 `Query` 这个函数。当你调用它时,它将返回一个同样命名为 `Query` 的类的实例。
- 如此,你导入 `Query` 这个函数。当你调用它时,它将返回一个同样命名为 `Query` 的类的实例。
+因为使用了这些函数(而不是直接使用类),所以你的编辑器不会标记有关其类型的错误。
- 因为使用了这些函数(而不是直接使用类),所以你的编辑器不会标记有关其类型的错误。
+这样,你可以使用常规的编辑器和编码工具,而不必添加自定义配置来忽略这些错误。
- 这样,你可以使用常规的编辑器和编码工具,而不必添加自定义配置来忽略这些错误。
+///
diff --git a/docs/zh/docs/tutorial/path-params.md b/docs/zh/docs/tutorial/path-params.md
index 1b428d662..ac9df0831 100644
--- a/docs/zh/docs/tutorial/path-params.md
+++ b/docs/zh/docs/tutorial/path-params.md
@@ -1,48 +1,50 @@
# 路径参数
-你可以使用与 Python 格式化字符串相同的语法来声明路径"参数"或"变量":
+FastAPI 支持使用 Python 字符串格式化语法声明**路径参数**(**变量**):
-```Python hl_lines="6-7"
-{!../../../docs_src/path_params/tutorial001.py!}
-```
+{* ../../docs_src/path_params/tutorial001.py hl[6:7] *}
-路径参数 `item_id` 的值将作为参数 `item_id` 传递给你的函数。
+这段代码把路径参数 `item_id` 的值传递给路径函数的参数 `item_id`。
-所以,如果你运行示例并访问 http://127.0.0.1:8000/items/foo,将会看到如下响应:
+运行示例并访问 http://127.0.0.1:8000/items/foo,可获得如下响应:
```JSON
{"item_id":"foo"}
```
-## 有类型的路径参数
+## 声明路径参数的类型
-你可以使用标准的 Python 类型标注为函数中的路径参数声明类型。
+使用 Python 标准类型注解,声明路径操作函数中路径参数的类型。
-```Python hl_lines="7"
-{!../../../docs_src/path_params/tutorial002.py!}
-```
+{* ../../docs_src/path_params/tutorial002.py hl[7] *}
+
+本例把 `item_id` 的类型声明为 `int`。
+
+/// check | 检查
-在这个例子中,`item_id` 被声明为 `int` 类型。
+类型声明将为函数提供错误检查、代码补全等编辑器支持。
-!!! check
- 这将为你的函数提供编辑器支持,包括错误检查、代码补全等等。
+///
-## 数据转换
+## 数据转换
-如果你运行示例并打开浏览器访问 http://127.0.0.1:8000/items/3,将得到如下响应:
+运行示例并访问 http://127.0.0.1:8000/items/3,返回的响应如下:
```JSON
{"item_id":3}
```
-!!! check
- 注意函数接收(并返回)的值为 3,是一个 Python `int` 值,而不是字符串 `"3"`。
+/// check | 检查
- 所以,**FastAPI** 通过上面的类型声明提供了对请求的自动"解析"。
+注意,函数接收并返回的值是 `3`( `int`),不是 `"3"`(`str`)。
+
+**FastAPI** 通过类型声明自动**解析**请求中的数据。
+
+///
## 数据校验
-但如果你通过浏览器访问 http://127.0.0.1:8000/items/foo,你会看到一个清晰可读的 HTTP 错误:
+通过浏览器访问 http://127.0.0.1:8000/items/foo,接收如下 HTTP 错误信息:
```JSON
{
@@ -59,176 +61,190 @@
}
```
-因为路径参数 `item_id` 传入的值为 `"foo"`,它不是一个 `int`。
+这是因为路径参数 `item_id` 的值 (`"foo"`)的类型不是 `int`。
+
+值的类型不是 `int ` 而是浮点数(`float`)时也会显示同样的错误,比如: http://127.0.0.1:8000/items/4.2。
+
+/// check | 检查
-如果你提供的是 `float` 而非整数也会出现同样的错误,比如: http://127.0.0.1:8000/items/4.2
+**FastAPI** 使用 Python 类型声明实现了数据校验。
-!!! check
- 所以,通过同样的 Python 类型声明,**FastAPI** 提供了数据校验功能。
+注意,上面的错误清晰地指出了未通过校验的具体原因。
- 注意上面的错误同样清楚地指出了校验未通过的具体原因。
+这在开发调试与 API 交互的代码时非常有用。
- 在开发和调试与你的 API 进行交互的代码时,这非常有用。
+///
-## 文档
+## 查看文档
-当你打开浏览器访问 http://127.0.0.1:8000/docs,你将看到自动生成的交互式 API 文档:
+访问 http://127.0.0.1:8000/docs,查看自动生成的 API 文档:
-POST
小节。
+编码和表单字段详见 MDN Web 文档的 POST
小节。
-!!! warning "警告"
+///
- 可在一个*路径操作*中声明多个 `File` 和 `Form` 参数,但不能同时声明要接收 JSON 的 `Body` 字段。因为此时请求体的编码是 `multipart/form-data`,不是 `application/json`。
+/// warning | 警告
- 这不是 **FastAPI** 的问题,而是 HTTP 协议的规定。
+可在一个*路径操作*中声明多个 `File` 和 `Form` 参数,但不能同时声明要接收 JSON 的 `Body` 字段。因为此时请求体的编码是 `multipart/form-data`,不是 `application/json`。
-## 可选文件上传
-
-您可以通过使用标准类型注解并将 None 作为默认值的方式将一个文件参数设为可选:
+这不是 **FastAPI** 的问题,而是 HTTP 协议的规定。
-=== "Python 3.9+"
+///
- ```Python hl_lines="7 14"
- {!> ../../../docs_src/request_files/tutorial001_02_py310.py!}
- ```
+## 可选文件上传
-=== "Python 3.6+"
+您可以通过使用标准类型注解并将 None 作为默认值的方式将一个文件参数设为可选:
- ```Python hl_lines="9 17"
- {!> ../../../docs_src/request_files/tutorial001_02.py!}
- ```
+{* ../../docs_src/request_files/tutorial001_02_py310.py hl[7,14] *}
## 带有额外元数据的 `UploadFile`
您也可以将 `File()` 与 `UploadFile` 一起使用,例如,设置额外的元数据:
-```Python hl_lines="13"
-{!../../../docs_src/request_files/tutorial001_03.py!}
-```
+{* ../../docs_src/request_files/tutorial001_03.py hl[13] *}
## 多文件上传
@@ -152,42 +148,24 @@ FastAPI 支持同时上传多个文件。
上传多个文件时,要声明含 `bytes` 或 `UploadFile` 的列表(`List`):
-=== "Python 3.9+"
-
- ```Python hl_lines="8 13"
- {!> ../../../docs_src/request_files/tutorial002_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="10 15"
- {!> ../../../docs_src/request_files/tutorial002.py!}
- ```
+{* ../../docs_src/request_files/tutorial002_py39.py hl[8,13] *}
接收的也是含 `bytes` 或 `UploadFile` 的列表(`list`)。
-!!! note "技术细节"
+/// note | 技术细节
+
+也可以使用 `from starlette.responses import HTMLResponse`。
- 也可以使用 `from starlette.responses import HTMLResponse`。
+`fastapi.responses` 其实与 `starlette.responses` 相同,只是为了方便开发者调用。实际上,大多数 **FastAPI** 的响应都直接从 Starlette 调用。
- `fastapi.responses` 其实与 `starlette.responses` 相同,只是为了方便开发者调用。实际上,大多数 **FastAPI** 的响应都直接从 Starlette 调用。
+///
### 带有额外元数据的多文件上传
和之前的方式一样, 您可以为 `File()` 设置额外参数, 即使是 `UploadFile`:
-=== "Python 3.9+"
-
- ```Python hl_lines="16"
- {!> ../../../docs_src/request_files/tutorial003_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="18"
- {!> ../../../docs_src/request_files/tutorial003.py!}
- ```
+{* ../../docs_src/request_files/tutorial003_py39.py hl[16] *}
## 小结
diff --git a/docs/zh/docs/tutorial/request-form-models.md b/docs/zh/docs/tutorial/request-form-models.md
new file mode 100644
index 000000000..e639e4b9f
--- /dev/null
+++ b/docs/zh/docs/tutorial/request-form-models.md
@@ -0,0 +1,78 @@
+# 表单模型
+
+您可以使用 **Pydantic 模型**在 FastAPI 中声明**表单字段**。
+
+/// info
+
+要使用表单,需预先安装 `python-multipart` 。
+
+确保您创建、激活一个[虚拟环境](../virtual-environments.md){.internal-link target=_blank}后再安装。
+
+```console
+$ pip install python-multipart
+```
+
+///
+
+/// note
+
+自 FastAPI 版本 `0.113.0` 起支持此功能。🤓
+
+///
+
+## 表单的 Pydantic 模型
+
+您只需声明一个 **Pydantic 模型**,其中包含您希望接收的**表单字段**,然后将参数声明为 `Form` :
+
+{* ../../docs_src/request_form_models/tutorial001_an_py39.py hl[9:11,15] *}
+
+**FastAPI** 将从请求中的**表单数据**中**提取**出**每个字段**的数据,并提供您定义的 Pydantic 模型。
+
+## 检查文档
+
+您可以在文档 UI 中验证它,地址为 `/docs` :
+
+POST
小节。
- 但包含文件的表单编码为 `multipart/form-data`。文件处理详见下节。
+///
- 编码和表单字段详见 MDN Web 文档的 POST
小节。
+/// warning | 警告
-!!! warning "警告"
+可在一个*路径操作*中声明多个 `Form` 参数,但不能同时声明要接收 JSON 的 `Body` 字段。因为此时请求体的编码是 `application/x-www-form-urlencoded`,不是 `application/json`。
- 可在一个*路径操作*中声明多个 `Form` 参数,但不能同时声明要接收 JSON 的 `Body` 字段。因为此时请求体的编码是 `application/x-www-form-urlencoded`,不是 `application/json`。
+这不是 **FastAPI** 的问题,而是 HTTP 协议的规定。
- 这不是 **FastAPI** 的问题,而是 HTTP 协议的规定。
+///
## 小结
diff --git a/docs/zh/docs/tutorial/response-model.md b/docs/zh/docs/tutorial/response-model.md
index ea3d0666d..049cd1223 100644
--- a/docs/zh/docs/tutorial/response-model.md
+++ b/docs/zh/docs/tutorial/response-model.md
@@ -8,12 +8,13 @@
* `@app.delete()`
* 等等。
-```Python hl_lines="17"
-{!../../../docs_src/response_model/tutorial001.py!}
-```
+{* ../../docs_src/response_model/tutorial001_py310.py hl[17,22,24:27] *}
+
+/// note
-!!! note
- 注意,`response_model`是「装饰器」方法(`get`,`post` 等)的一个参数。不像之前的所有参数和请求体,它不属于*路径操作函数*。
+注意,`response_model`是「装饰器」方法(`get`,`post` 等)的一个参数。不像之前的所有参数和请求体,它不属于*路径操作函数*。
+
+///
它接收的类型与你将为 Pydantic 模型属性所声明的类型相同,因此它可以是一个 Pydantic 模型,但也可以是一个由 Pydantic 模型组成的 `list`,例如 `List[Item]`。
@@ -28,22 +29,21 @@ FastAPI 将使用此 `response_model` 来:
* 会将输出数据限制在该模型定义内。下面我们会看到这一点有多重要。
-!!! note "技术细节"
- 响应模型在参数中被声明,而不是作为函数返回类型的注解,这是因为路径函数可能不会真正返回该响应模型,而是返回一个 `dict`、数据库对象或其他模型,然后再使用 `response_model` 来执行字段约束和序列化。
+/// note | 技术细节
+
+响应模型在参数中被声明,而不是作为函数返回类型的注解,这是因为路径函数可能不会真正返回该响应模型,而是返回一个 `dict`、数据库对象或其他模型,然后再使用 `response_model` 来执行字段约束和序列化。
+
+///
## 返回与输入相同的数据
现在我们声明一个 `UserIn` 模型,它将包含一个明文密码属性。
-```Python hl_lines="9 11"
-{!../../../docs_src/response_model/tutorial002.py!}
-```
+{* ../../docs_src/response_model/tutorial002.py hl[9,11] *}
我们正在使用此模型声明输入数据,并使用同一模型声明输出数据:
-```Python hl_lines="17-18"
-{!../../../docs_src/response_model/tutorial002.py!}
-```
+{* ../../docs_src/response_model/tutorial002.py hl[17:18] *}
现在,每当浏览器使用一个密码创建用户时,API 都会在响应中返回相同的密码。
@@ -51,28 +51,25 @@ FastAPI 将使用此 `response_model` 来:
但是,如果我们在其他的*路径操作*中使用相同的模型,则可能会将用户的密码发送给每个客户端。
-!!! danger
- 永远不要存储用户的明文密码,也不要在响应中发送密码。
+/// danger
+
+永远不要存储用户的明文密码,也不要在响应中发送密码。
+
+///
## 添加输出模型
相反,我们可以创建一个有明文密码的输入模型和一个没有明文密码的输出模型:
-```Python hl_lines="9 11 16"
-{!../../../docs_src/response_model/tutorial003.py!}
-```
+{* ../../docs_src/response_model/tutorial003_py310.py hl[9,11,16] *}
这样,即便我们的*路径操作函数*将会返回包含密码的相同输入用户:
-```Python hl_lines="24"
-{!../../../docs_src/response_model/tutorial003.py!}
-```
+{* ../../docs_src/response_model/tutorial003_py310.py hl[24] *}
...我们已经将 `response_model` 声明为了不包含密码的 `UserOut` 模型:
-```Python hl_lines="22"
-{!../../../docs_src/response_model/tutorial003.py!}
-```
+{* ../../docs_src/response_model/tutorial003_py310.py hl[22] *}
因此,**FastAPI** 将会负责过滤掉未在输出模型中声明的所有数据(使用 Pydantic)。
@@ -90,9 +87,7 @@ FastAPI 将使用此 `response_model` 来:
你的响应模型可以具有默认值,例如:
-```Python hl_lines="11 13-14"
-{!../../../docs_src/response_model/tutorial004.py!}
-```
+{* ../../docs_src/response_model/tutorial004.py hl[11,13:14] *}
* `description: Union[str, None] = None` 具有默认值 `None`。
* `tax: float = 10.5` 具有默认值 `10.5`.
@@ -106,9 +101,7 @@ FastAPI 将使用此 `response_model` 来:
你可以设置*路径操作装饰器*的 `response_model_exclude_unset=True` 参数:
-```Python hl_lines="24"
-{!../../../docs_src/response_model/tutorial004.py!}
-```
+{* ../../docs_src/response_model/tutorial004.py hl[24] *}
然后响应中将不会包含那些默认值,而是仅有实际设置的值。
@@ -121,16 +114,22 @@ FastAPI 将使用此 `response_model` 来:
}
```
-!!! info
- FastAPI 通过 Pydantic 模型的 `.dict()` 配合 该方法的 `exclude_unset` 参数 来实现此功能。
+/// info
+
+FastAPI 通过 Pydantic 模型的 `.dict()` 配合 该方法的 `exclude_unset` 参数 来实现此功能。
+
+///
+
+/// info
-!!! info
- 你还可以使用:
+你还可以使用:
- * `response_model_exclude_defaults=True`
- * `response_model_exclude_none=True`
+* `response_model_exclude_defaults=True`
+* `response_model_exclude_none=True`
- 参考 Pydantic 文档 中对 `exclude_defaults` 和 `exclude_none` 的描述。
+参考 Pydantic 文档 中对 `exclude_defaults` 和 `exclude_none` 的描述。
+
+///
#### 默认值字段有实际值的数据
@@ -165,10 +164,13 @@ FastAPI 将使用此 `response_model` 来:
因此,它们将包含在 JSON 响应中。
-!!! tip
- 请注意默认值可以是任何值,而不仅是`None`。
+/// tip
+
+请注意默认值可以是任何值,而不仅是`None`。
+
+它们可以是一个列表(`[]`),一个值为 `10.5`的 `float`,等等。
- 它们可以是一个列表(`[]`),一个值为 `10.5`的 `float`,等等。
+///
### `response_model_include` 和 `response_model_exclude`
@@ -178,29 +180,31 @@ FastAPI 将使用此 `response_model` 来:
如果你只有一个 Pydantic 模型,并且想要从输出中移除一些数据,则可以使用这种快捷方法。
-!!! tip
- 但是依然建议你使用上面提到的主意,使用多个类而不是这些参数。
+/// tip
- 这是因为即使使用 `response_model_include` 或 `response_model_exclude` 来省略某些属性,在应用程序的 OpenAPI 定义(和文档)中生成的 JSON Schema 仍将是完整的模型。
+但是依然建议你使用上面提到的主意,使用多个类而不是这些参数。
- 这也适用于作用类似的 `response_model_by_alias`。
+这是因为即使使用 `response_model_include` 或 `response_model_exclude` 来省略某些属性,在应用程序的 OpenAPI 定义(和文档)中生成的 JSON Schema 仍将是完整的模型。
-```Python hl_lines="31 37"
-{!../../../docs_src/response_model/tutorial005.py!}
-```
+这也适用于作用类似的 `response_model_by_alias`。
+
+///
+
+{* ../../docs_src/response_model/tutorial005.py hl[31,37] *}
-!!! tip
- `{"name", "description"}` 语法创建一个具有这两个值的 `set`。
+/// tip
- 等同于 `set(["name", "description"])`。
+`{"name", "description"}` 语法创建一个具有这两个值的 `set`。
+
+等同于 `set(["name", "description"])`。
+
+///
#### 使用 `list` 而不是 `set`
如果你忘记使用 `set` 而是使用 `list` 或 `tuple`,FastAPI 仍会将其转换为 `set` 并且正常工作:
-```Python hl_lines="31 37"
-{!../../../docs_src/response_model/tutorial006.py!}
-```
+{* ../../docs_src/response_model/tutorial006.py hl[31,37] *}
## 总结
diff --git a/docs/zh/docs/tutorial/response-status-code.md b/docs/zh/docs/tutorial/response-status-code.md
index 357831942..aa8032ada 100644
--- a/docs/zh/docs/tutorial/response-status-code.md
+++ b/docs/zh/docs/tutorial/response-status-code.md
@@ -1,89 +1,101 @@
# 响应状态码
-与指定响应模型的方式相同,你也可以在以下任意的*路径操作*中使用 `status_code` 参数来声明用于响应的 HTTP 状态码:
+与指定响应模型的方式相同,在以下任意*路径操作*中,可以使用 `status_code` 参数声明用于响应的 HTTP 状态码:
* `@app.get()`
* `@app.post()`
* `@app.put()`
* `@app.delete()`
-* 等等。
+* 等……
-```Python hl_lines="6"
-{!../../../docs_src/response_status_code/tutorial001.py!}
-```
+{* ../../docs_src/response_status_code/tutorial001.py hl[6] *}
-!!! note
- 注意,`status_code` 是「装饰器」方法(`get`,`post` 等)的一个参数。不像之前的所有参数和请求体,它不属于*路径操作函数*。
+/// note | 笔记
-`status_code` 参数接收一个表示 HTTP 状态码的数字。
+注意,`status_code` 是(`get`、`post` 等)**装饰器**方法中的参数。与之前的参数和请求体不同,不是*路径操作函数*的参数。
-!!! info
- `status_code` 也能够接收一个 `IntEnum` 类型,比如 Python 的 `http.HTTPStatus`。
+///
-它将会:
+`status_code` 参数接收表示 HTTP 状态码的数字。
-* 在响应中返回该状态码。
-* 在 OpenAPI 模式中(以及在用户界面中)将其记录为:
+/// info | 说明
-